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;
        }
    }
}
相关文章
相关标签/搜索