HibernateTools实现pojo类 数据库schma mapping映射的相互转换

亦余心之所善兮,虽九死其犹未悔。这篇文章主要讲述HibernateTools实现pojo类 数据库schma mapping映射的相互转换相关的知识,希望能为你提供帮助。
核心利用HibernateTools,从POJO类,Mapping映射文件,数据库表有其中的一项,就能生成其他两项。
概述在使用Hibernate开发系统持久层时,按照一般开发流程
 
1、分析业务
2、获得系统实体类
3、写Hibernate的mapping映射文件
4、根据映射文件,生成数据库表
 
    以上这几步是Hibernate开发的起始。根据开发习惯的不同,有些项目组可能会先写POJO类,有的项目可能会先设计数据库,有的项目组可能先写映射文件,其实完成其中的一项时,类结构或者表结构就可以确定了。
既然已经能确定结构了,完全可以使用工具来代替手工完成剩余的工作。
前提    安装Eclipse插件HibernateTools,eclipse插件安装百度下教程非常多,建议采用copy安装或者link安装,再有就是HibernateTools的版本对应着特定的Eclipse版本,所以安装前请先检查自己的eclipse版本。
 
    然后建立项目,本文建立的是Dynamic Web Project,采用了mysql数据库,建立项目后,引入mysql的驱动jar,引入Hibernate(本文用了4.3.5版本)的包,即lib下required文件夹中所有jar
 
【HibernateTools实现pojo类 数据库schma mapping映射的相互转换】    安装完了插件,首先利用tool生成Hibernate配置文件,项目右键--> new,安装完HibernateTools后,多了4种类型的文件,选择第一种:

HibernateTools实现pojo类 数据库schma mapping映射的相互转换

文章图片


根据使用的数据库,填入必须的属性:
HibernateTools实现pojo类 数据库schma mapping映射的相互转换

文章图片

生成hibernate.cfg.xml的代码:
< span style="font-family:KaiTi_GB2312; font-size:18px; "> < ?xml version="1.0" encoding="utf-8"?> < !DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> < hibernate-configuration> < session-factory> < property name="hibernate.bytecode.use_reflection_optimizer"> false< /property> < property name="hibernate.connection.driver_class"> com.mysql.jdbc.Driver< /property> < property name="hibernate.connection.password"> 123456< /property> < property name="hibernate.connection.url"> jdbc:mysql://localhost:3306/test< /property> < property name="hibernate.connection.username"> root< /property> < property name="hibernate.dialect"> org.hibernate.dialect.MySQLDialect< /property> < property name="hibernate.search.autoregister_listeners"> false< /property> < /session-factory> < /hibernate-configuration> < /span>

相互转换 
接下可以进入正题了,本文分别从三项中的每一项入手,生成其他两项。 
思路一:由POJO类生成mapping映射文件和DDLPOJO类的代码写起来非常方便,因此首先介绍这种方法,个人认为这种方法效率最高。首先建立两个POJO类
package org.hibernate.test; public class Student implements java.io.Serializable {private int id; private String name; public Student() { }public Student(int id) { this.id = id; }public Student(int id, String name) { this.id = id; this.name = name; }public int getId() { return this.id; }public void setId(int id) { this.id = id; }public String getName() { return this.name; }public void setName(String name) { this.name = name; }}

package org.hibernate.test; import java.util.ArrayList; import java.util.List; public class Class implements java.io.Serializable {private int id; private String name; private List students = new ArrayList(0); public Class() { }public Class(int id) { this.id = id; }public Class(int id, String name, List students) { this.id = id; this.name = name; this.students = students; }public int getId() { return this.id; }public void setId(int id) { this.id = id; }public String getName() { return this.name; }public void setName(String name) { this.name = name; }public List getStudents() { return this.students; }public void setStudents(List students) { this.students = students; }}

接下来一步一步生成另外两项,首先项目右键--> new,选择Hibernate下面的第四项,建立mapping映射文件,根据已存在的POJO类,生成Mapping文件
HibernateTools实现pojo类 数据库schma mapping映射的相互转换

文章图片

添加两个已经存在的POJO类
HibernateTools实现pojo类 数据库schma mapping映射的相互转换

文章图片

下一步,可以预先查看生成的hbm.xml文件,有特殊要求的可以再生成的文件基础上稍作修改。
HibernateTools实现pojo类 数据库schma mapping映射的相互转换

文章图片
HibernateTools实现pojo类 数据库schma mapping映射的相互转换

文章图片

生成代码:
< span style="font-family:KaiTi_GB2312; font-size:18px; "> < ?xml version="1.0"?> < !DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> < !-- Generated 2014-5-30 21:29:20 by Hibernate Tools 4.0.0 --> < hibernate-mapping> < class name="org.hibernate.test.Student" table="STUDENT"> < id name="id" type="int"> < column name="ID" /> < generator class="assigned"> < /generator> < /id> < property name="name" type="java.lang.String"> < column name="NAME" /> < /property> < /class> < /hibernate-mapping> < /span>

< span style="font-family:KaiTi_GB2312; font-size:18px; "> < ?xml version="1.0"?> < !DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> < !-- Generated 2014-5-30 21:29:20 by Hibernate Tools 4.0.0 --> < hibernate-mapping> < class name="org.hibernate.test.Class" table="CLASS"> < id name="id" type="int"> < column name="ID" /> < generator class="assigned"> < /generator> < /id> < property name="name" type="java.lang.String"> < column name="NAME" /> < /property> < list name="students" inverse="false" table="STUDENT" lazy="true"> < key> < column name="ID" /> < /key> < list-index> < column name="idx" /> < /list-index> < one-to-many class="org.hibernate.test.Student" /> < /list> < /class> < /hibernate-mapping> < /span>

mapping映射文件生成了,接下来生成ddl,项目右键--> new,选择Hibernate Console   Configuration
 
HibernateTools实现pojo类 数据库schma mapping映射的相互转换

文章图片

HibernateTools实现pojo类 数据库schma mapping映射的相互转换

文章图片

 
选择好对应的项后,finish,然后需要在工具栏添加Hibernate code Generation,Windows--> Customer Perspective
HibernateTools实现pojo类 数据库schma mapping映射的相互转换

文章图片

然后工具栏多了一个很像运行按钮的图标,单击下拉按钮,选第二项
HibernateTools实现pojo类 数据库schma mapping映射的相互转换

文章图片

 
HibernateTools实现pojo类 数据库schma mapping映射的相互转换

文章图片

单击Exporters选项卡,可以看到HibernateTools工具能导出和生成的项很多,可以根据配置有针对性的选择自己想要的项,这里我们勾选Schema Export,然后单击图标1下面的Properties的Add,后出现图标2所示的窗体
HibernateTools实现pojo类 数据库schma mapping映射的相互转换

文章图片

选择第二项,这就是要生成我们想要的ddl,如图,当然上图还勾选了DAO Code,生成了操作试题的DAO代码(HibernateTools确实很贴心)
HibernateTools实现pojo类 数据库schma mapping映射的相互转换

文章图片

这是生成后的图片
HibernateTools实现pojo类 数据库schma mapping映射的相互转换

文章图片

ddl的建表语句:
< span style="font-family:KaiTi_GB2312; font-size:18px; "> create table CLASS (ID integer not null, NAME varchar(255), primary key (ID)); create table STUDENT (ID integer not null, NAME varchar(255), idx integer, primary key (ID)); alter table STUDENT add index FKBACA0E1BE081A5FD (ID), add constraint FKBACA0E1BE081A5FD foreign key (ID) references CLASS (ID); < /span>

DAO代码如下:
< span style="font-family:KaiTi_GB2312; font-size:18px; "> package org.hibernate.test; // Generated 2014-5-30 23:18:05 by Hibernate Tools 4.0.0import java.util.List; import javax.naming.InitialContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.LockMode; import org.hibernate.SessionFactory; import org.hibernate.criterion.Example; /** * Home object for domain model class Class. * @see org.hibernate.test.Class * @author Hibernate Tools */ public class ClassHome {private static final Log log = LogFactory.getLog(ClassHome.class); private final SessionFactory sessionFactory = getSessionFactory(); protected SessionFactory getSessionFactory() { try { return (SessionFactory) new InitialContext() .lookup("SessionFactory"); } catch (Exception e) { log.error("Could not locate SessionFactory in JNDI", e); throw new IllegalStateException( "Could not locate SessionFactory in JNDI"); } }public void persist(Class transientInstance) { log.debug("persisting Class instance"); try { sessionFactory.getCurrentSession().persist(transientInstance); log.debug("persist successful"); } catch (RuntimeException re) { log.error("persist failed", re); throw re; } }public void attachDirty(Class instance) { log.debug("attaching dirty Class instance"); try { sessionFactory.getCurrentSession().saveOrUpdate(instance); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } }public void attachClean(Class instance) { log.debug("attaching clean Class instance"); try { sessionFactory.getCurrentSession().lock(instance, LockMode.NONE); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } }public void delete(Class persistentInstance) { log.debug("deleting Class instance"); try { sessionFactory.getCurrentSession().delete(persistentInstance); log.debug("delete successful"); } catch (RuntimeException re) { log.error("delete failed", re); throw re; } }public Class merge(Class detachedInstance) { log.debug("merging Class instance"); try { Class result = (Class) sessionFactory.getCurrentSession().merge( detachedInstance); log.debug("merge successful"); return result; } catch (RuntimeException re) { log.error("merge failed", re); throw re; } }public Class findById(int id) { log.debug("getting Class instance with id: " + id); try { Class instance = (Class) sessionFactory.getCurrentSession().get( "org.hibernate.test.Class", id); if (instance == null) { log.debug("get successful, no instance found"); } else { log.debug("get successful, instance found"); } return instance; } catch (RuntimeException re) { log.error("get failed", re); throw re; } }public List findByExample(Class instance) { log.debug("finding Class instance by example"); try { List results = sessionFactory.getCurrentSession() .createCriteria("org.hibernate.test.Class") .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; } } }< /span>

到此,我们就由POJO类,生成了hbm.xml文件和DDL
 
 
思路二:由hbm.xml生成POJO类和DDL...虽然可以实现,但个人觉着先设计数据库,然后再生成类不符合Hibernate的面对对象持久化的思维方式。好了,还是说步骤吧,首先在test数据库建立两张表,分别为course表和teacher表
[sql] view plain copy -- ---------------------------- -- Table structure for course -- ---------------------------- DROP TABLE IF EXISTS `course`; CREATE TABLE `course` ( `id` int(11) NOT NULL, `name` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Table structure for teacher -- ---------------------------- DROP TABLE IF EXISTS `teacher`; CREATE TABLE `teacher` ( `id` int(11) NOT NULL, `name` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

建好表后,在eclipse项目上右键--> new,如下图,选择框中的第三项,这个reveng.xml文件用于配置 选择要生成POJO类的数据库表。

HibernateTools实现pojo类 数据库schma mapping映射的相互转换

文章图片

选择上篇博客中创建的Console configuration项,点Database schema框下的refresh,之后可以看到test数据库,单击就出现了course和teacher表,全选后点击Include,之后点finish,如下图
HibernateTools实现pojo类 数据库schma mapping映射的相互转换

文章图片

再来到Hibernate Code Generation Configuration窗体,首先配置下Output directory输出目录,在尽挨着的复选框打上勾,然后在package栏写上生成文件要输出到哪个包,并选择刚配置好的reveng.xml文件
HibernateTools实现pojo类 数据库schma mapping映射的相互转换

文章图片

配置要输出的项,这里选定前两项,生成.java和.hbm.xml,就是我们想要的POJO类和Mapping映射文件。之后点击run就好了。
HibernateTools实现pojo类 数据库schma mapping映射的相互转换

文章图片

结果如下图:
HibernateTools实现pojo类 数据库schma mapping映射的相互转换

文章图片

生成的Mapping映射文件的代码
< ?xml version="1.0"?> < !DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> < !-- Generated 2014-5-31 11:19:19 by Hibernate Tools 4.0.0 --> < hibernate-mapping> < class name="org.hibernate.test.Course" table="course" catalog="test"> < id name="id" type="int"> < column name="id" /> < generator class="assigned" /> < /id> < many-to-one name="teacher" class="org.hibernate.test.Teacher" fetch="select"> < column name="teacherId" not-null="true" /> < /many-to-one> < property name="name" type="string"> < column name="name" /> < /property> < /class> < /hibernate-mapping>

< ?xml version="1.0"?> < !DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> < !-- Generated 2014-5-31 11:19:19 by Hibernate Tools 4.0.0 --> < hibernate-mapping> < class name="org.hibernate.test.Teacher" table="teacher" catalog="test"> < id name="id" type="int"> < column name="id" /> < generator class="assigned" /> < /id> < property name="name" type="string"> < column name="name" /> < /property> < set name="courses" table="course" inverse="true" lazy="true" fetch="select"> < key> < column name="teacherId" not-null="true" /> < /key> < one-to-many class="org.hibernate.test.Course" /> < /set> < /class> < /hibernate-mapping>

生成的POJO类:
package org.hibernate.test; // Generated 2014-5-31 11:19:19 by Hibernate Tools 4.0.0/** * Course generated by hbm2java */ public class Course implements java.io.Serializable {private int id; private Teacher teacher; private String name; public Course() { }public Course(int id, Teacher teacher) { this.id = id; this.teacher = teacher; }public Course(int id, Teacher teacher, String name) { this.id = id; this.teacher = teacher; this.name = name; }public int getId() { return this.id; }public void setId(int id) { this.id = id; }public Teacher getTeacher() { return this.teacher; }public void setTeacher(Teacher teacher) { this.teacher = teacher; }public String getName() { return this.name; }public void setName(String name) { this.name = name; }}

package org.hibernate.test; // Generated 2014-5-31 11:19:19 by Hibernate Tools 4.0.0import java.util.HashSet; import java.util.Set; /** * Teacher generated by hbm2java */ public class Teacher implements java.io.Serializable {private int id; private String name; private Set courses = new HashSet(0); public Teacher() { }public Teacher(int id) { this.id = id; }public Teacher(int id, String name, Set courses) { this.id = id; this.name = name; this.courses = courses; }public int getId() { return this.id; }public void setId(int id) { this.id = id; }public String getName() { return this.name; }public void setName(String name) { this.name = name; }public Set getCourses() { return this.courses; }public void setCourses(Set courses) { this.courses = courses; }}

到此我们就完成了由数据库表生成POJO类和Mapping映射文件的过程
思路三:由数据库表(或DDL)生成POJO类和hbm.xml首先,新建一个Mapping文件,这里在项目中建立Department.hbm.xml。
< ?xml version="1.0" encoding="UTF-8"?> < !DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" > < hibernate-mapping> < class name="org.hibernate.test.Department" table="DEPARTMENT"> < id name="id" type="int"> < column name="ID" /> < generator class="increment"> < /generator> < /id> < property name="name" type="java.lang.String"> < column name="NAME" /> < /property> < /class> < /hibernate-mapping>

接下来建一个新的Console Configuration文件,基本配置和上文中配置的过程一样,最关键的是加入mapping文件。
HibernateTools实现pojo类 数据库schma mapping映射的相互转换

文章图片

接下来,改下Hibernate Code Generation Configuration就好了,首选选择新配置的Console Configuration文件
HibernateTools实现pojo类 数据库schma mapping映射的相互转换

文章图片

接下来选择要生成的Schema和.Java文件,然后run就可以了。
HibernateTools实现pojo类 数据库schma mapping映射的相互转换

文章图片

最终结果如图:
HibernateTools实现pojo类 数据库schma mapping映射的相互转换

文章图片

生成的DDL代码为
[sql] view plain copy create table DEPARTMENT (ID integer not null, NAME varchar(255), primary key (ID)); < /span>

POJO类:
package org.hibernate.test; // Generated 2014-5-31 16:23:27 by Hibernate Tools 4.0.0/** * Department generated by hbm2java */ public class Department implements java.io.Serializable {private int id; private String name; public Department() { }public Department(String name) { this.name = name; }public int getId() { return this.id; }public void setId(int id) { this.id = id; }public String getName() { return this.name; }public void setName(String name) { this.name = name; }}

好了,至此POJO类,Mapping文件和数据库表相互转化就都介绍完了,当然这是借助eclipse的插件实现的,熟悉使用ant的朋友也可以借助ant脚本来实现,具体的教程去google吧。这里推荐下HibernateTools的官方教程,包含了eclipse插件和ant脚本两种实现方式,非常全面。
 



    推荐阅读