今天忙了一整天,終于搭建好了我的第一個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: /r/n/r/n");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("/r/n");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開發王者歸來,劉京華編著。
新聞熱點
疑難解答