反向工程:先创建表,创建好表之后,就是持久化类和映射文件可以不用你写,而且你的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;
}
}
}

day37 08-Hibernate的反向工程的更多相关文章

  1. 关于Hibernate在反向工程时无法选择Spring DAO Type的解决方法【更新版】

    目录(?)[+] IT程序员开发必备-各类资源下载清单,史上最全IT资源,个人收藏总结! 之前有一篇文章中(Hibernate反向工程步骤及DAO Type无法选择Spring DAO解决方法)提到, ...

  2. MyEclipse从数据库反向生成实体类之Hibernate方式 反向工程

    前文: hibernate带给我们的O/RMapping思想是很正确的,即从面相对象的角度来设计工程中的实体对象,建立pojo,然后在编写hbm.xml映射文件来生成数据表.但是在实际开发中,往往我们 ...

  3. eclipse使用Hibernate tools反向工程插件遇到的几个问题

    1,在eclipse使用hibernate工具,生成hibernate配置文件时,可能会提示not parse ....xml错误 参见 加载本地dtd 2,反向工程中,生成配置文件时,一般要填写其默 ...

  4. Hibernate-ORM:08.Hibernate中的投影查询

    ------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥------------- 本篇博客将叙述hibernate中的投影查询 一,目录: 1.解释什么是投影查询 2.返回Object单个对象 ...

  5. Java进阶知识08 Hibernate多对一单向关联(Annotation+XML实现)

    1.Annotation 注解版 1.1.在多的一方加外键 1.2.创建Customer类和Order类 package com.shore.model; import javax.persisten ...

  6. 08.Hibernate的一级缓存-->>Session

    Hibernate提供了两种缓存: 1.一级缓存:自带的不可卸载的,一级缓存的生命周期与Session一致,一级缓存成为Session级别的缓存 2.二级缓存:默认没有开启,需要手动配置才可以使用,二 ...

  7. Rhythmk 学习 Hibernate 08 - Hibernate annotation 关联关系注解

    1.一对一 (One to One)    共三种情况:     1.1 主键共享    1.2 外键共享 1.3 中间表关联 1.1  code: @Entity public class arti ...

  8. Hibernate从零开始的反向工程

    首先  创建一个web项目 导入jar包 Bulid Path 先现在hibernate的插件   help-->eclipse marketplace-->输入tool  点instal ...

  9. J2EE进阶(十五)MyEclipse反向工程实现从数据库反向生成实体类之Hibernate方式

    J2EE进阶(十五)MyEclipse反向工程实现从数据库反向生成实体类之Hibernate方式   反向工程又称逆向工程.   开发项目涉及到的表太多,一个一个的写JAVA实体类很是费事.MyEcl ...

  10. Hibernate5.2之反向工程

                                                          Hibernate5.2之反向工程 一.描述 可能很多人在使用Hibernate进行项目开发 ...

随机推荐

  1. vs Code打开新的文件会覆盖窗口中的文件?

    这是因为你单击文件名的缘故,这个是“预览模式”,所以再单击其他文件时,会覆盖当前打开的文件. 如果你要每次都打开新tab,那就双击文件名好了.这个逻辑和sublime是一样的. 补充: 预览模式是现在 ...

  2. LUOGU P1613 跑路 (倍增floyd)

    解题思路 倍增$floyd$,首先设$f[i][j][k]$表示$i$这个点到$j$的距离能否为$2^k$,初值是如果x,y之间有边,那么$f[x][y][0]=1$.转移方程就是$f[i][j][t ...

  3. BZOJ 3668: [Noi2014]起床困难综合症

    Time Limit: 10 Sec Memory Limit: 512 MB Submit: 2693 Solved: 1563 [Submit][Status][Discuss] Descript ...

  4. 你知道的和不知道的sass

    关于sass,大多数人的认识一个写css的工具而已 其实就是的 但是这个工具的威力你发挥了多少呢... 以下全部都是干货,希望你能用在自己的项目里 定义集合 我们通常是这么定义变量的 $warning ...

  5. iOS开发UIView.h简介

    1.UICoordinateSpace不同坐标空间的坐标切换 @protocol UICoordinateSpace <NSObject> //将当前的坐标空间点转换到指定的坐标空间 - ...

  6. CF #578 Div2

    // 比赛链接:https://codeforces.com/contest/1200 A - Hotelier 题意: 有一家旅馆有10间房,编号0~9,从左到右顺序排列.旅馆有左右两扇门,每次新来 ...

  7. 黑裙晖安装后修改mac和sn

    d当前使用6.2 打开putty sudo -i 然后在/tmp目录下创建一个临时目录,名字随意,如:boot mkdir -p /tmp/boot 第四步:切换到dev目录 cd /dev 第五步: ...

  8. PKUOJ 区间内的真素数

    http://bailian.openjudge.cn/tm2018/A/ #include <iostream> #include <math.h> #include < ...

  9. __name__变量

    再写项目过程中,将功能函数写在 if  __name=="__main__":之外,执行代码写在之中,如下:如果在foo模块打印__name__为__main__,而如果在bin模 ...

  10. html常用标签详解2-图片标签详解

    <img /> 1.图片标签的属性 图片标签属于行内块元素,它自身的属性有一下几个,听我娓娓道来: src:图片资源的路径(resourse),可以使绝对路径,也可以是相对路径 绝对路径: ...