day37 08-Hibernate的反向工程

反向工程:先建立表,建立好表以後,就是持久化類和映射文件能夠不用你寫,並且你的DAO它也能夠幫你生成。可是它生成的DAO可能會多不少的方法。你能夠不用那麼多方法,可是它裏面提供了這種的。用hibernate,必須得用myeclipse裏面的這種自動生成的工具。其實myeclipse它裏面對Struts和Spring都有集成。可是這種集成對三大框架整合的時候會有問題。html


用hibernate的時候最好先建一個鏈接數據庫的模板。這個時候它能夠幫咱們把核心配置文件hibernate.cfg.xml中的參數所有設置好。若是你沒有hibernate.cfg.xml這個模板的話,它最多幫你把hibernate的jar包拷貝過來。最多能幫你建立一個工具類HibernateUtils.java。若是你把hibernate.cfg.xml建立好了,它能夠幫你把核心配置文件中的參數設置好。java

 


回到MyEclipse Database  Explorer Perspective,選擇數據庫表右鍵逆向工程生成類和映射文件。web

是把表全選以後再Hibernate Reverse Engineering數據庫

 


你本身引jar包是不能反向工程的,只能使用MyEclipse的hibernate支持才能夠反向工程。使用hibernate支持的web工程和普通的web工程的logo都不同。若是使用MyEclipse的hibernate、Struts、Spring的支持進行三大框架整合是會報錯的,由於裏面有不少重複的jar包。session

 


 

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;
        }
    }
}