反向工程:先创建表,创建好表之后,就是持久化类和映射文件可以不用你写,而且你的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. C#可扩展编程之MEF(五):MEF高级进阶

      好久没有写博客了,今天抽空继续写MEF系列的文章.有园友提出这种系列的文章要做个目录,看起来方便,所以就抽空做了一个,放到每篇文章的最后. 前面四篇讲了MEF的基础知识,学完了前四篇,MEF中比较 ...

  2. iOS开发CoreData的多表关联

    1.多表关联 多表关联,对SQL 数据库的操作,在一张表的数据中可以引用另外一张表里的数据.通过 Entity 实体中的 Relationships 来实现,比起传统的 SQL 数据库来,更加简单. ...

  3. Docker系列(十二):Kubernetes的分布式网络实践

    tip:本节课的学习视频没有找到,所以有的地方可能不是很清晰. 可选的几种网络方案 openvswitch 是一种主流的虚拟化大二层技术 灵活 对现有物理网络没要求 业界主流 软件封装导致性能低 复杂 ...

  4. RESTful API -- rules

    RESTful介绍 REST与技术无关,代表的是一种软件架构风格,REST是Representational State Transfer的简称,中文翻译为“表征状态转移”或“表现层状态转化”. 推荐 ...

  5. 整合SSH框架最基本的例子

    ssh框架整合 一.思路 1.导包 struts2: \apps\struts2-blank\WEB-INF\lib\所有包 struts2-spring-plugin-2.3.28.jar hibe ...

  6. 经典分类CNN模型系列其五:Inception v2与Inception v3

    经典分类CNN模型系列其五:Inception v2与Inception v3 介绍 Inception v2与Inception v3被作者放在了一篇paper里面,因此我们也作为一篇blog来对其 ...

  7. C语言作用域、链接属性和存储类型

    C/C++中作用域详解 作用域 编译器可以确认的4种作用域-代码块作用域.文件作用域.函数作用域和原型作用域,一般来说,标识符(包括变量名和函数名)声明的位置决定它的作用域. (1)代码块作用域 一对 ...

  8. 【踩坑】nextSibling 和nextElementSibling的区别

    DOM 使用nextSibling属性返回指定节点之后的下一个兄弟节点,(即:相同节点树层中的下一个节点). nextSibling属性与nextElementSibling属性的差别: nextSi ...

  9. CGLayer和CALayer区别

    CGLayer是一种很好的缓存常绘内容的方法.注意,不要与CALayer混淆.CALayer是Core Animation中更加强大.复杂的图层对象,而CGLayer是Core Graphics中优化 ...

  10. java 并发 详解

    1 普通线程和 守护线程的区别. 守护线程会跟随主线程的结束而结束,普通线程不会. 2 线程的 stop  和 interrupted 的区别. stop 会停止线程,但是不会释放锁之类的资源? in ...