day37 08-Hibernate的反向工程

反向工程:先创建表,创建好表之后,就是持久化类和映射文件可以不用你写,而且你的DAO它也可以帮你生成。但是它生成的DAO可能会多很多的方法。你可以不用那么多方法,但是它里面提供了这种的。用hibernate,必须得用myeclipse里面的这种自动生成的工具。其实myeclipse它里面对Struts和Spring都有集成。但是这种集成对三大框架整合的时候会有问题。


用hibernate的时候最好先建一个连接数据库的模板。这个时候它可以帮我们把核心配置文件hibernate.cfg.xml中的参数全部设置好。如果你没有hibernate.cfg.xml这个模板的话,它最多帮你把hibernate的jar包拷贝过来。最多能帮你创建一个工具类HibernateUtils.java。如果你把hibernate.cfg.xml创建好了,它可以帮你把核心配置文件中的参数设置好。


回到MyEclipse Database  Explorer Perspective,选择数据库表右键逆向工程生成类和映射文件。

是把表全选之后再Hibernate Reverse Engineering


你自己引jar包是不能反向工程的,只能使用MyEclipse的hibernate支持才可以反向工程。使用hibernate支持的web工程和普通的web工程的logo都不一样。如果使用MyEclipse的hibernate、Struts、Spring的支持进行三大框架整合是会报错的,因为里面有很多重复的jar包。


package cn.itcast.utils;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

/**
 * Configures and provides access to Hibernate sessions, tied to the
 * current thread of execution.  Follows the Thread Local Session
 * pattern, see {@link http://hibernate.org/42.html }.
 */
public class HibernateSessionFactory {

    /** 
     * Location of hibernate.cfg.xml file.
     * Location should be on the classpath as Hibernate uses  
     * #resourceAsStream style lookup for its configuration file. 
     * The default classpath location of the hibernate config file is 
     * in the default package. Use #setConfigFile() to update 
     * the location of the configuration file for the current session.   
     */
    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private  static Configuration configuration = new Configuration();    
    private static org.hibernate.SessionFactory sessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;

    static {
        try {
            configuration.configure(configFile);
            sessionFactory = configuration.buildSessionFactory();
        } catch (Exception e) {
            System.err
                    .println("%%%% Error Creating SessionFactory %%%%");
            e.printStackTrace();
        }
    }
    private HibernateSessionFactory() {
    }
    
    /**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     *  @return Session
     *  @throws HibernateException
     */
    public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();//getSession是从当前线程往外取的.从当前线程获取session
        //threadLocal获取当前线程的session 我们是getCurrentSession(),然后在核心配置文件还要配置一句

        if (session == null || !session.isOpen()) {
            if (sessionFactory == null) {
                rebuildSessionFactory();
            }
            session = (sessionFactory != null) ? sessionFactory.openSession()
                    : null;
            threadLocal.set(session);//绑定到当前线程里面
        }

        return session;
    }

    /**
     *  Rebuild hibernate session factory
     *
     */
    public static void rebuildSessionFactory() {
        try {
            configuration.configure(configFile);
            sessionFactory = configuration.buildSessionFactory();
        } catch (Exception e) {
            System.err
                    .println("%%%% Error Creating SessionFactory %%%%");
            e.printStackTrace();
        }
    }

    /**
     *  Close the single hibernate session instance.
     *
     *  @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

    /**
     *  return session factory
     *
     */
    public static org.hibernate.SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    /**
     *  return session factory
     *
     *    session factory will be rebuilded in the next call
     */
    public static void setConfigFile(String configFile) {
        HibernateSessionFactory.configFile = configFile;
        sessionFactory = null;
    }

    /**
     *  return hibernate configuration
     *
     */
    public static Configuration getConfiguration() {
        return configuration;
    }

}
package cn.itcast.vo;

import java.util.List;
import java.util.Set;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.criterion.Example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A data access object (DAO) providing persistence and search support for
 * Customer entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 * 
 * @see cn.itcast.vo.Customer
 * @author MyEclipse Persistence Tools
 */

public class CustomerDAO extends BaseHibernateDAO {
    private static final Logger log = LoggerFactory
            .getLogger(CustomerDAO.class);
    // property constants
    public static final String CNAME = "cname";
    public static final String AGE = "age";
    public static final String VERSION = "version";

    public void save(Customer transientInstance) {//保存Customer实例化
        log.debug("saving Customer instance");
        try {
            getSession().save(transientInstance);
            log.debug("save successful");
        } catch (RuntimeException re) {
            log.error("save failed", re);
            throw re;
        }
    }

    public void delete(Customer persistentInstance) {
        log.debug("deleting Customer instance");
        try {
            getSession().delete(persistentInstance);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }

    public Customer findById(java.lang.Integer id) {
        log.debug("getting Customer instance with id: " + id);
        try {
            Customer instance = (Customer) getSession().get(
                    "cn.itcast.vo.Customer", id);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }

    public List findByExample(Customer instance) {
        log.debug("finding Customer instance by example");
        try {
            List results = getSession().createCriteria("cn.itcast.vo.Customer")
                    .add(Example.create(instance)).list();
            log.debug("find by example successful, result size: "
                    + results.size());
            return results;
        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        }
    }

    public List findByProperty(String propertyName, Object value) {
        log.debug("finding Customer instance with property: " + propertyName
                + ", value: " + value);
        try {
            String queryString = "from Customer as model where model."
                    + propertyName + "= ?";
            Query queryObject = getSession().createQuery(queryString);
            queryObject.setParameter(0, value);
            return queryObject.list();
        } catch (RuntimeException re) {
            log.error("find by property name failed", re);
            throw re;
        }
    }

    public List findByCname(Object cname) {
        return findByProperty(CNAME, cname);
    }

    public List findByAge(Object age) {
        return findByProperty(AGE, age);
    }

    public List findByVersion(Object version) {
        return findByProperty(VERSION, version);
    }

    public List findAll() {
        log.debug("finding all Customer instances");
        try {
            String queryString = "from Customer";
            Query queryObject = getSession().createQuery(queryString);
            return queryObject.list();
        } catch (RuntimeException re) {
            log.error("find all failed", re);
            throw re;
        }
    }

    public Customer merge(Customer detachedInstance) {
        log.debug("merging Customer instance");
        try {
            Customer result = (Customer) getSession().merge(detachedInstance);
            log.debug("merge successful");
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public void attachDirty(Customer instance) {
        log.debug("attaching dirty Customer instance");
        try {
            getSession().saveOrUpdate(instance);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }

    public void attachClean(Customer instance) {
        log.debug("attaching clean Customer instance");
        try {
            getSession().lock(instance, LockMode.NONE);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }
}
原文地址:https://www.cnblogs.com/ZHONGZHENHUA/p/6710426.html