Hibernate的Hello World!

一、创建Java工程,新建Lib文件夹,加入Hibernate和数据库(如MySql、Oracle、SqlServer等)的Jar包

二、创建 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 <hibernate-configuration>
 6     <session-factory>
 7     
 8         <!-- 配置连接数据库的基本信息 -->
 9         <property name="connection.username">root</property>
10         <property name="connection.password"></property>
11         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
12         <property name="connection.url">jdbc:mysql:///mis</property>
13 
14         <!-- 配置 hibernate 的基本信息 -->
15         <!-- hibernate 所使用的数据库方言 -->
16         <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
17 
18         <!-- 执行操作时是否在控制台打印 SQL -->
19         <property name="show_sql">true</property>
20 
21         <!-- 是否对 SQL 进行格式化 -->
22         <property name="format_sql">true</property>
23 
24         <!-- 指定自动生成数据表的策略 -->
25         <property name="hbm2ddl.auto">update</property>
26 
27         <!-- 指定关联的 .hbm.xml 文件 -->
28         <mapping resource="com/mcs/hibernate/helloworld/News.hbm.xml" />
29 
30     </session-factory>
31 
32 </hibernate-configuration>
View Code

三、新建News实体类并根据实体类创建对应的 hbm.xml文件

1、News实体明细如下:

 1 package com.mcs.hibernate.helloworld;
 2 
 3 import java.util.Date;
 4 
 5 public class News {
 6 
 7     private Integer id; // field
 8     private String title;
 9     private String author;
10 
11     private Date date;
12 
13     public Integer getId() { // property
14         return id;
15     }
16 
17     public void setId(Integer id) {
18         this.id = id;
19     }
20 
21     public String getTitle() {
22         return title;
23     }
24 
25     public void setTitle(String title) {
26         this.title = title;
27     }
28 
29     public String getAuthor() {
30         return author;
31     }
32 
33     public void setAuthor(String author) {
34         this.author = author;
35     }
36 
37     public Date getDate() {
38         return date;
39     }
40 
41     public void setDate(Date date) {
42         this.date = date;
43     }
44 
45     public News(String title, String author, Date date) {
46         super();
47         this.title = title;
48         this.author = author;
49         this.date = date;
50     }
51 
52     public News() {
53         // TODO Auto-generated constructor stub
54     }
55 
56     @Override
57     public String toString() {
58         return "News [id=" + id + ", title=" + title + ", author=" + author + ", date=" + date + "]";
59     }
60 
61 }
View Code

2、News.hbm.xml明细如下:

 1 <?xml version="1.0"?>
 2 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 3 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 4 <!-- Generated 2015-10-27 11:34:41 by Hibernate Tools 3.5.0.Final -->
 5 <hibernate-mapping>
 6     <class name="com.mcs.hibernate.helloworld.News" table="NEWS">
 7         <id name="id" type="java.lang.Integer">
 8             <column name="ID" />
 9             <!-- 指定主键的生成方式, native: 使用数据库本地方式 -->
10             <generator class="native" />
11         </id>
12         <property name="title" type="java.lang.String">
13             <column name="TITLE" />
14         </property>
15         <property name="author" type="java.lang.String">
16             <column name="AUTHOR" />
17         </property>
18         <property name="date" type="java.util.Date">
19             <column name="DATE" />
20         </property>
21     </class>
22 </hibernate-mapping>
View Code

四、创建Junit测试类,并写下如下代码,测试新增数据与查询数据

 1 package com.mcs.hibernate.helloworld;
 2 
 3 import java.sql.Date;
 4 
 5 import org.hibernate.Session;
 6 import org.hibernate.SessionFactory;
 7 import org.hibernate.Transaction;
 8 import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
 9 import org.hibernate.cfg.Configuration;
10 import org.hibernate.service.ServiceRegistry;
11 import org.junit.Test;
12 
13 public class HibernateTest {
14 
15     @Test
16     public void test() {
17         System.out.println("test...");
18 
19         // 1. 创建一个 SessionFactory 对象
20         SessionFactory sessionFactory = null;
21 
22         // 1). 创建 Configuration 对象: 对应 hibernate 的基本配置信息和 对象关系映射信息
23         Configuration configuration = new Configuration().configure();
24 
25         // 4.0 之前这样创建
26         // sessionFactory = configuration.buildSessionFactory();
27 
28         // 2). 创建一个 ServiceRegistry 对象: hibernate 4.x 新添加的对象
29         // hibernate 的任何配置和服务都需要在该对象中注册后才能有效.
30         ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
31 
32         /* ServiceRegistryBuilder已废弃 */
33         /*
34          * ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()) .buildServiceRegistry();
35          */
36 
37         // 3).
38         sessionFactory = configuration.buildSessionFactory(serviceRegistry);
39 
40         // 2. 创建一个 Session 对象
41         Session session = sessionFactory.openSession();
42 
43         // 3. 开启事务
44         Transaction transaction = session.beginTransaction();
45 
46         // 4. 执行保存操作
47         News news = new News("Java12345", "mcs", new Date(new java.util.Date().getTime()));
48         session.save(news);
49         
50         //News news2 = (News) session.get(News.class, 1);
51         //System.out.println(news2);
52 
53         // 5. 提交事务
54         transaction.commit();
55 
56         // 6. 关闭 Session
57         session.close();
58 
59         // 7. 关闭 SessionFactory 对象
60         sessionFactory.close();
61     }
62 
63 }
View Code

建议在Test测试类中如下写法:

 1 private SessionFactory sessionFactory;
 2     private Session session;
 3     private Transaction transaction;
 4     
 5     @Before
 6     public void init() { 
 7         Configuration configuration = new Configuration().configure();
 8         
 9         ServiceRegistry serviceRegistry = 
10                 new StandardServiceRegistryBuilder().applySettings(configuration.getProperties())
11                                                     .build();
12         
13         sessionFactory = configuration.buildSessionFactory(serviceRegistry);
14         session = sessionFactory.openSession();
15         transaction = session.beginTransaction();
16     }
17     
18     @After
19     public void destory() {
20         transaction.commit();
21         session.close();
22         sessionFactory.close();        
23     }
24     
25     @Test
26     public void test() {
27         System.out.println("test...");
28     }
View Code
原文地址:https://www.cnblogs.com/maocs/p/4919423.html