、数据库设计
实例对象为工作人员和部门,关系为一个部门对应多个工作人员,一个工作人员只属于一个部门
见表语句如下:(先用Navicat建的表,然后导出的sql语句),数据库名称为test
- SET FOREIGN_KEY_CHECKS=0;
-
- DROP TABLE IF EXISTS `t_department`;
- CREATE TABLE `t_department` (
- `id` int(11) NOT NULL auto_increment,
- `departmentname` varchar(40) NOT NULL,
- `departmentlocation` varchar(100) NOT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-
- DROP TABLE IF EXISTS `t_user`;
- CREATE TABLE `t_user` (
- `id` int(11) NOT NULL auto_increment,
- `username` varchar(20) NOT NULL,
- `password` varchar(20) NOT NULL,
- `departmentid` int(11) NOT NULL,
- PRIMARY KEY (`id`),
- KEY `departmentid` (`departmentid`),
- CONSTRAINT `departmentid` FOREIGN KEY (`departmentid`) REFERENCES `t_department` (`id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2、使用MyEclipse反向工程生成配置文件和POJO类
第一步:配置数据源
1、打开MyEclipse,新建一个web工程,这里命名为hibernate_demo
2、打开数据库设置器:依次单击【window】-->【Show View】-->【Other…】如下图所示:
3、在弹出的窗口ShowView中选择DB Browser,如下图所示:
4、在DB Browser窗口中,选择显示的图标,单击右键执行新建命令,如下图示
5、弹出Database Driver对话框,在此会要求我们配置数据库的相关信息,具体设置如下图所示,设置完成,单击Finish.
【第二步】引入hibernate配置文件
1、添加hibernate包:
选中我们的Web工程,依次单击鼠标右键-->MyEclipse-->Add HibernateCapabilities… 如下图所示:
2、在弹出的窗口中做如下设置:
【Next】,创建hibernate的配置文件
【Next】,指明hibernate与数据库的连接
【Next】,创建HibernateSessionFactory类,用来获得session。如果前面没有设置包名,要先单击New创建新的包。
单击【Finish】按钮
接下来要给hibernate.cfg.xml文件添加属性:在properties处选择Add…,如下图所示:
单击【Add…】,在Hibernate Properties Wizard页面填入如下图所示信息,最后单击Ok。
show_sql:默认为false,如果为true,表示在程序运行时,会在控制台输出SQL语句,这有利于跟中Hibernate的运行状态。在开发和测试阶段,可以将该属性设置为true,以便跟踪、调试程序,在应用发布以后,应将该属性值设置为false,以减少应用的输出信息,提高运行性能。
【第三步】添加hibernate映射文件和POJO类
1、新建com.lqh.beans包
2、在前面设置的数据源上找到我们要操作的表:
在DB Browser中选中新建的数据源,单击鼠标右键并选择open connection..
输入数据库的用户名和密码,以创建连接:
找到刚才新建的test数据库,然后是TABLE,如下图所示:
生成POJO:
点击Next,配置映射类型(暂时未用到)
点击Next,配置反向工程细节
点击finish即可完成,生成的映射文件以及POJO类如下:
User.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="com.lqh.beans.User" table="t_user" catalog="test">
- <id name="id" type="integer">
- <column name="id" />
- <generator class="native"></generator>
- </id>
- <many-to-one name="department" class="com.lqh.beans.Department" cascade="all" fetch="select">
- <column name="departmentid" not-null="true" />
- </many-to-one>
- <property name="username" type="string">
- <column name="username" length="20" not-null="true" />
- </property>
- <property name="password" type="string">
- <column name="password" length="20" not-null="true" />
- </property>
- </class>
- </hibernate-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="com.lqh.beans.Department" table="t_department" catalog="test">
- <id name="id" type="integer">
- <column name="id" />
- <generator class="native"></generator>
- </id>
- <property name="departmentname" type="string">
- <column name="departmentname" length="40" not-null="true" />
- </property>
- <property name="departmentlocation" type="string">
- <column name="departmentlocation" length="100" not-null="true" />
- </property>
- <set name="users" inverse="true">
- <key>
- <column name="departmentid" not-null="true" />
- </key>
- <one-to-many class="com.lqh.beans.User" />
- </set>
- </class>
- </hibernate-mapping>
User.java
- package com.lqh.beans;
-
- /**
- * User entity. @author MyEclipse Persistence Tools
- */
-
- public class User implements java.io.Serializable {
-
- // Fields
-
- private Integer id;
- private Department department;
- private String username;
- private String password;
-
- // Constructors
-
- /** default constructor */
- public User() {
- }
-
- /** full constructor */
- public User(Department department, String username, String password) {
- this.department = department;
- this.username = username;
- this.password = password;
- }
-
- // Property accessors
-
- public Integer getId() {
- return this.id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public Department getDepartment() {
- return this.department;
- }
-
- public void setDepartment(Department department) {
- this.department = department;
- }
-
- public String getUsername() {
- return this.username;
- }
-
- public void setUsername(String username) {
- this.username = username;
- }
-
- public String getPassword() {
- return this.password;
- }
-
- public void setPassword(String password) {
- this.password = password;
- }
-
- }
Department.java
- package com.lqh.beans;
-
- import java.util.HashSet;
- import java.util.Set;
-
- /**
- * Department entity. @author MyEclipse Persistence Tools
- */
-
- public class Department implements java.io.Serializable {
-
- // Fields
-
- private Integer id;
- private String departmentname;
- private String departmentlocation;
- private Set users = new HashSet(0);
-
- // Constructors
-
- /** default constructor */
- public Department() {
- }
-
- /** minimal constructor */
- public Department(String departmentname, String departmentlocation) {
- this.departmentname = departmentname;
- this.departmentlocation = departmentlocation;
- }
-
- /** full constructor */
- public Department(String departmentname, String departmentlocation,
- Set users) {
- this.departmentname = departmentname;
- this.departmentlocation = departmentlocation;
- this.users = users;
- }
-
- // Property accessors
-
- public Integer getId() {
- return this.id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getDepartmentname() {
- return this.departmentname;
- }
-
- public void setDepartmentname(String departmentname) {
- this.departmentname = departmentname;
- }
-
- public String getDepartmentlocation() {
- return this.departmentlocation;
- }
-
- public void setDepartmentlocation(String departmentlocation) {
- this.departmentlocation = departmentlocation;
- }
-
- public Set getUsers() {
- return this.users;
- }
-
- public void setUsers(Set users) {
- this.users = users;
- }
-
- }
编写测试类代码,如下:
- package com.lqh.test;
-
- import org.hibernate.Session;
- import org.junit.Test;
-
- import com.lqh.beans.Department;
- import com.lqh.beans.User;
- import com.lqh.utils.HibernateSessionFactory;
-
- public class HibernateTest {
- /**
- * 测试保存部门
- */
- @Test
- public void testSaveDepartment() {
-
- Department department = new Department();
- department.setDepartmentlocation("清河小营东路");
- department.setDepartmentname("北京信息科技");
-
- Session session = HibernateSessionFactory.getSession();
- session.beginTransaction();
- session.save(department);
- session.getTransaction().commit();
- session.close();
-
- }
-
- /**
- * 测试保存用户,该用户已存在对应Department
- */
- @Test
- public void testSavaUser() {
- Session session = HibernateSessionFactory.getSession();
- session.beginTransaction();
-
- Department department = (Department) session.load(Department.class, 1);
- User user = new User();
- user.setUsername("hehe");
- user.setPassword("123455");
- user.setDepartment(department);
- session.save(user);
-
- session.getTransaction().commit();
- session.close();
- }
-
- /**
- * 测试保存用户,该用户对应的Department未存在数据库中
- * 此处注意,要将User.hbm.xml中的cascade设为all
- */
- @Test
- public void testSaveUserAndDepartment() {
- Session session = HibernateSessionFactory.getSession();
- session.beginTransaction();
-
- Department department = new Department();
- department.setDepartmentname("中央人民政府");
- department.setDepartmentlocation("北京");
-
- User user = new User();
- user.setUsername("UserAndDepartment");
- user.setPassword("123455");
- user.setDepartment(department);
- session.save(user);
-
- session.getTransaction().commit();
- session.close();
- }
-
- }
此外,还可在POJO类上生成注解,只需在以下两步注意即可:
上面这步并不是必须,选在3.2版本以上,默认就支持注解。
二:
反向工程 逆向工程
开发项目涉及到的表太多,一个一个的写JAVA实体类很是费事。MyEclipse提供简便的方法:反向数据库
步骤大致如下:
第一步:
window-->open Perspective-->MyEclipse Java Persistence
操作后会出现一个视图DB Brower:MyEclipse Derby
在空白区点击右键,新建一个数据库对象。我用的是mysql,其实我一直想用oracle之类的,只是机子内存小,又懒得倒腾别的,结果截个图吧:
左边的属性按照自己使用的数据库填就行了,左边部分是我建好以后的结果,数据库名叫shop,有个user表 是专门这次测试用的
第二步:
新建一个WEB项目
然后选中项目右键-->MyEclipse-->add Hibernate Capabilities
如果需要用到在实体类上添加注释的话那么选中紧挨着的add Hibernate Annotations Support(据说现在都用annotations了就选上吧!!)
然后下一步选中一个目录存放自动生成hibernate.cfg.xml文件,一般毫无例外的放在src根目录下,下一步选中一个DB Driver中我们第一步建立的那个(对我来说是com.mysql....反正就是自己建的那个呗),然后下一步选中一个目录存放自动生成的 HibernateSessionFactory工具类 ,结果出来以后我看了一下,这个hibernateSessionFactory工具类就是一个拿Session的单例,还有一些其它关闭session 之类的方法,一看便知。下图是生成的配置文件:
第三步反向生成实体类
到DB Brower中找到要反向的表选中并且点击右键--->Hibernate Reverse Enginnering
看选项:java src folder 源码包,不用多解释,java package——存放将要反转出来的实体类,选择目录(应该是提前建好的com.xxx.model之类的包);Create pojo<>db。。。这个选项选中,就是我们建立从表到简单java 对象(即pojo)的配置,把下面的add hibernate mapping annotations to pojo的选上,其它不管,这个选项用来“添加映射注解到pojo对象上”,它上面的那个选项用来创建xml的,据说不太用了,就用annotation 吧!
这样应该就够了,下一步
看图:type Mapping要选上hibernatetypes,这样这些注解都是来自 javax.persistence.*了 (刚观察过!)
id generator 看下拉列表就知道是配置id生成策略的
那两个enable 是说映射关系发现(detection),明白了吧?英文好就是沾光,不用像我一样还得查字典了。
下一步:没啥理解不了的 动手点点就知道了
直接完成,发现代码很漂亮,注释很完美,而且肯定没有错误,几分钟都能搞定数十个表,不得不感叹myeclipse,真是个大金矿。