Hibernate3回顾-1-部署

web备份版本,详见doc版本。

一、背景(部署简单回顾)

我们知道,一个Hibernate快速上手的简单流程是这样。

1引入对应jar包。

中间涉及log4的jar包和配置,略。

2 实体类

 1 package com.test.entity;
 2 import java.util.Date;
 3 
 4 /** 
 5  * 你可以看到这个类对属性的存取方法(getter  and  setter  method)使用了标准
 6 JavaBean  命名约定,同时把类属性(field)的访问级别设成私有的(private)。这是推荐的
 7 设计,但并不是必须的 */
 8 public class Event {
 9     private Long id;
10     private String title;
11     private Date date;
12 //所有的持久化类(persistent classes)都要求有无参的构造器,因为 Hibernate 必须使用 Java
13 //反射机制来为你创建对象
14     public Event() {}
15     //getter/setter
16     public Long getId() {
17         return id;
18     }
19     public void setId(Long id) {
20         this.id = id;
21     }
22     public String getTitle() {
23         return title;
24     }
25     public void setTitle(String title) {
26         this.title = title;
27     }
28     public Date getDate() {
29         return date;
30     }
31     public void setDate(Date date) {
32         this.date = date;
33     }
34 }

3实体类映射文件

Event.hbm.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 3 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 4 <hibernate-mapping package="org.hibernate.tutorial.domain">
 5     <class name="Event" table="EVENTS">
 6         <id name="id" column="EVENT_ID">
 7             <generator class="native" />
 8         </id>
 9     </class>
10     <property name="date" type="timestamp" column="EVENT_DATE" />
11     <property name="title" />
12 </hibernate-mapping>

4配置hibernate.properties或者hibernate.cfg.xml文档

 1 <?xml version='1.0' encoding='UTF-8'?>
 2 <!DOCTYPE hibernate-configuration PUBLIC
 3           "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 4           "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 5 <!-- Generated by MyEclipse Hibernate Tools.                   -->
 6 <hibernate-configuration>
 7     <session-factory>
 8         <!--
 9             具体的配置信息可参见hibernate_home/etc/hibernate.properties相关配置项 
10             如何要移植数据时,只要将下面数据库信息修改就可以了。
11          -->
12         <!-- 配置mysql数据库连接串 -->
13         <property name="hibernate.connection.url">jdbc:mysql://localhost:3036/hibernate_first</property>
14         <!-- 配置mysql数据库jdbc驱动 -->
15         <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
16         <!-- 配置mysql数据库连接用户名 -->
17         <property name="hibernate.connection.username">root</property>
18         <!-- 配置mysql数据库连接用户密码 -->
19         <property name="hibernate.connection.password">root</property>
20         <!--配置数据库适配器(使用何中数据库)-->
21         <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
22          <!-- 是否显示hibernate的SQL语句 -->
23         <property name="hibernate.show_sql">true</property>
24       <!-- 实体类导出至数据库时,如果存在的表处理方式:
25             hibernate.hbm2ddl.auto :(create-drop、create、update、validate)
26          -->
27         <property name="hibernate.hbm2ddl.auto">update</property>
28 <!-- 配置实体类映射文件 位于property之后 
29              映射文件要求为完整路径,目录之前使用/隔开 
30 -->
31         <mapping resource="com/test/mapping/Event.hbm.xml"/>
32 </session-factory>
33 </hibernate-configuration>

5-1启动

方式一使用hibernate工具类将对象模型生成关系模型(hbm to ddl)

(也就是实体类生成数据库中的表)

 1 import org.hibernate.cfg.Configuration;
 2 import org.hibernate.tool.hbm2ddl.SchemaExport;
 3 /**
 4  * Hibernate工具<br/>
 5  * 将对象模型生成关系模型(将对象生成数据库中的表)
 6  * 把hbm映射文件转换成DDL
 7  * 生成数据表之前要求已经存在数据库
 8  * 注:这个工具类建立好后,以后就不用建立了。以后直接Copy来用。
 9 /
10 public class ExportDB {
11     public static void main(String[] args){
12         /*
13          * org.hibernate.cfg.Configuration类的作用:
14          * 读取hibernate配置文件(hibernate.cfg.xml或hiberante.properties)的.
15          * new Configuration()默认是读取hibernate.properties
16          * 所以使用new Configuration().configure();来读取hibernate.cfg.xml配置文件
17          */
18         Configuration cfg = new Configuration().configure();
19         
20         /*
21          * org.hibernate.tool.hbm2ddl.SchemaExport工具类:
22          * 需要传入Configuration参数
23          * 此工具类可以将类导出生成数据库表
24          */
25         SchemaExport export = new SchemaExport(cfg);
26         
27         /*
28          * 开始导出
29          * 第一个参数:script 是否打印DDL信息
30          * 第二个参数:export 是否导出到数据库中生成表
31          */
32         export.create(true, true);
33         
34     }
35 }

5-2启动

方式二:将引用部署于web容器。根据hibernate.cfg.xml中的配置:

<property name="hibernate.hbm2ddl.auto">create 或者update</property> Hibernate将自动更新表格结构。

6 client常规操作

以下代码来源wtj276

 1 import java.util.Date;
 2 import org.hibernate.Session;
 3 import org.hibernate.SessionFactory;
 4 import org.hibernate.cfg.Configuration;
 5 
 6 public class Client {
 7 
 8     public static void main(String[] args){
 9         
10         //1读取hibernate.cfg.xml文件
11         Configuration cfg = new Configuration().configure();
12         
13         /*
14          * 2创建SessionFactory
15          * 一个数据库对应一个SessionFactory 
16          * SessionFactory是线程安全的。
17          */
18         SessionFactory factory = cfg.buildSessionFactory();
19         
20         //3创建session
21         //此处的session并不是web中的session,而是HibernateSession
22         //session只有在用时,才建立concation,session还管理缓存。
23         //session用完后,必须关闭。
24         //session是非线程安全,一般是一个请求一个session.
25         Session session = null;
26         
27         try {
28             
29             session = factory.openSession();
30             
31             //5手动开启事务(可以在hibernate.cfg.xml配置文件中配置自动开启事务)
32             session.beginTransaction();
33             
34             User user = new User();
35             user.setName("张三");
36             user.setPassword("123");
37             user.setCreateTime(new Date());
38             user.setExpireTime(new Date());            
39             /*
40              * 6增删改查操作
41 保存数据等操作,此处的数据是保存对象,这就是hibernate操作对象的好处,
42              * 我们不用写那么多的JDBC代码,只要利用session操作对象,至于hibernat如何存在对象,这不需要我们去关心它,
43              * 这些都有hibernate来完成。我们只要将对象创建完后,交给hibernate就可以了。
44              */
45             session.save(user);
46             
47             //7.1提交事务
48             session.getTransaction().commit();
49             
50         } catch (Exception e) {
51             e.printStackTrace();
52             //7.2异常,回滚事务
53             session.getTransaction().rollback();
54         } finally {
55             if (session != null) {
56                 //8关闭session
57                 session.close();
58             }
59         }        
60     }
61 }

为了方便跟踪sql语句执行,可以在hibernate.hbm.xml中加入下以代码:

<property name="hibernate.show_sql">true</property>

 完成

原文地址:https://www.cnblogs.com/redcoatjk/p/3614727.html