我的Hibernate入门

  今天忙了一整天,终于搭建好了我的第一个Hibernate程序,中间关于hibernate.cfg.xml的问题搞了半天,不过最后还是搞明白了,下面来讲一讲过程。

  首先在你的eclipse中安装Hibernate Tools插件方便创建cfg.cml与hbm.xml文件。然后创建配置hibernate.cfg.xml文件:

奥添加yi

当然在最前面还要添加hibernate jar包,musql driver等,由于我使用maven管理项目,因此直接在maven的pom文件中添加就可以了。

在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 name="HibernateSessionFactory">
 7         <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
 8         <property name="hibernate.connection.password">admin</property>
 9         <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate?characterEncoding=utf-8</property>
10         <property name="hibernate.connection.username">root</property>
11         <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
12         <!-- 在控制台输出SQL语句 -->
13         <property name="show_sql">true</property>
14         <!-- Hibernate启动时自动创建表结构 -->
15         <property name="hbm2ddl.auto">create</property>
16         <!-- 不加 可能出现异常 -->
17         <property name="current_sesson_context_class">thread</property>
18         <!-- 指定Cat类为Hibernate实体类 -->
19         <mapping resource="config/Cat.hbm.xml"/>
20     </session-factory>
21 </hibernate-configuration>

第九行url后面的 hibernate?characterEncoding=utf-8 是hibernate要操作的数据库名称,需要你自己先创建:

create database hibernate character set 'utf8'

19行Cat类是需要你自己创建的POJO实体类,实体类(Entity)是指与数据库有映射关系的Java类使用@Entity后Cat就被申明为了一个实体类。实体类还需配置对应的表名(@Table),主键(@Id),普通属性(@Column)对应列名等。

  1 package com.lxiao.model;
  2 
  3 
  4 import java.util.Date;
  5 
  6 import javax.persistence.Column;
  7 import javax.persistence.Entity;
  8 import javax.persistence.GeneratedValue;
  9 import javax.persistence.GenerationType;
 10 import javax.persistence.Id;
 11 import javax.persistence.JoinColumn;
 12 import javax.persistence.ManyToOne;
 13 import javax.persistence.Table;
 14 import javax.persistence.Temporal;
 15 import javax.persistence.TemporalType;
 16 
 17 @Entity
 18 @Table(name="tb_cat")
 19 public class Cat {
 20 
 21     @Id
 22     @GeneratedValue(strategy = GenerationType.AUTO)
 23     private Integer Id;
 24     
 25     @Column(name = "name")
 26     private String name;
 27     
 28     @Column(name = "description")
 29     private String description;
 30     
 31     @Column(name = "age")
 32     private Integer age;
 33     
 34     @Column(name="sex")
 35     private String sex;
 36     
 37     @ManyToOne
 38     @JoinColumn(name = "mother_id")
 39     private Cat mother;
 40     
 41     @Temporal(TemporalType.TIMESTAMP)
 42     @Column(name = "createDate")
 43     private Date createDate;
 44 
 45     public Integer getId() {
 46         return Id;
 47     }
 48 
 49     public void setId(Integer id) {
 50         Id = id;
 51     }
 52 
 53     public String getName() {
 54         return name;
 55     }
 56 
 57     public void setName(String name) {
 58         this.name = name;
 59     }
 60 
 61     public String getDescription() {
 62         return description;
 63     }
 64 
 65     public void setDescription(String description) {
 66         this.description = description;
 67     }
 68 
 69     public Integer getAge() {
 70         return age;
 71     }
 72 
 73     public void setAge(Integer age) {
 74         this.age = age;
 75     }
 76 
 77     public String getSex() {
 78         return sex;
 79     }
 80 
 81     public void setSex(String sex) {
 82         this.sex = sex;
 83     }
 84 
 85     public Cat getMother() {
 86         return mother;
 87     }
 88 
 89     public void setMother(Cat mother) {
 90         this.mother = mother;
 91     }
 92 
 93     public Date getCreateDate() {
 94         return createDate;
 95     }
 96 
 97     public void setCreateDate(Date createDate) {
 98         this.createDate = createDate;
 99     }
100 
101 }

值得一提的是,该POJO类在定义玩le私有变量后,可以用eclipse自动生成getter,setter方法,免去了手写的枯燥。

然后创建Cat.hbm.xml文件,添加你的POJO类,我这里就是Cat,使用Hibernate tools工具创建时选择添加类,

然后一路next就可以了,最后就在hibernte.cfg.xml中就可以配置实体类了,用<mapping resource="config/Cat.hbm.xml">,这是针对xml文件配置,如果是@注解配置,使用<maping class="com.lxiao.model.Cat">

然后我们写一个HibernateUtil类来加载config文件hibernate.cfg.xml:

 1 package com.lxiao.hibernate;
 2 
 3 import org.hibernate.SessionFactory;
 4 import org.hibernate.cfg.Configuration;
 5 
 6 public class HibernateUtil {
 7     private static final SessionFactory factory;
 8     
 9     static{
10         try{
11             factory = new Configuration().configure("config/hibernate.cfg.xml").buildSessionFactory();
12         }catch(Throwable e){
13             System.out.println("Initial sesionFactory failed..."+e);
14             throw new ExceptionInInitializerError(e);
15         }
16     }
17     
18     public static SessionFactory getSessionFactory(){
19         return factory;
20     }
21 }

加载xml配置的实体类要使用Configuration加载Hibernate配置。

最后我们要使用一下Cat类,让Hibernate自动为我们创建表,执行相应数据库操作。这整个流程是:Hibernate保存数据是,先通过sesonFactory开启一个session会话(作用相当于JDBC中的Connection),然后开启一个事务(Transaction),然后保存代码,提交事务,关闭session。其它数据库操作也是类似的。下面是我的程序:

 1 package com.lxiao.hibernate;
 2 
 3 import java.awt.Font;
 4 import java.util.Date;
 5 import java.util.List;
 6 
 7 import javax.swing.JOptionPane;
 8 
 9 import org.hibernate.Session;
10 import org.hibernate.Transaction;
11 
12 import com.lxiao.model.Cat;
13 
14 public class CatTest {
15     public static void main(String[] args){
16         Cat motherCat = new Cat();
17         motherCat.setName("Mary White");
18         motherCat.setDescription("The mama cat...");
19         motherCat.setCreateDate(new Date());
20         
21         Cat kitty = new Cat();
22         kitty.setMother(motherCat);
23         kitty.setName("Kitty");
24         kitty.setDescription("Hello Kitty");
25         kitty.setCreateDate(new Date());
26         
27         Cat mimmy = new Cat();
28         mimmy.setMother(motherCat);
29         mimmy.setName("Mimmy");
30         mimmy.setDescription("Kitty's little twn sister");
31         mimmy.setCreateDate(new Date());
32         
33         Session session = HibernateUtil.getSessionFactory().openSession();//开启一个Hibernate对话
34         Transaction transaction = session.beginTransaction();
35         
36         session.persist(motherCat);//将mother保存进数据库
37         session.persist(kitty);
38         session.persist(mimmy);
39         
40         List<Cat> catlist = session.createQuery(" from Cat ").list();
41         
42         StringBuffer resultBuffer = new StringBuffer();
43         resultBuffer.append("All cat in db: 

");
44         
45         for(Cat cat : catlist){
46             resultBuffer.append("Cat: "+cat.getName()+", ");
47             resultBuffer.append("Mothercat: "+(cat.getMother() == null ? "no record" : cat.getMother().getName()));
48             resultBuffer.append("
");
49         }
50         transaction.commit();//提交事务
51         session.close();//关闭数据库
52         
53         JOptionPane.getRootFrame().setFont(new Font("Arial",Font.BOLD,14));
54         JOptionPane.showMessageDialog(null, resultBuffer.toString());
55         
56         
57     }
58 }

运行结果:

我在数据库的查询结果如下:

 在hibernate.cfg.xml配置文件中,我们有:

1 <!-- Hibernate启动时自动创建表结构 -->
2 15         <property name="hbm2ddl.auto">create</property>

每次Hibernate会先删掉表然后再创建表。

最后放上我的项目目录结构:

总之我的第一个Hibernate程序总算是可以运行了,也了解了不少Hiernate这个ORM框架的东西,它给开发中关于数据库操作带来了很多便利,很值得学习,了解。

--程序员的道路漫漫,继续努力。。。

参考书籍:Java Web开发王者归来,刘京华编著。

原文地址:https://www.cnblogs.com/lxiao/p/4339900.html