相關基礎概念請從其它教材簡單了解,這裡僅記錄下第一個Hibernate程序的實現步驟。
環境說明:
java開發工具:eclipse MARS.2 Release(4.5.2)
hibernate版本:hibernate-release-4.3.6.Final
Web 容器:Tomcat v8.0
數據庫:MySQL 5.6.19-enterprise-commercial-advanced
jdbc驅動:mysql-connector-java-commercial-5.1.30-bin.jar
1.下載hibernate。
2.下載jdbc驅動文件。
3.在eclipse中新建web project,命名為firsthibernate。
4.拷貝hibernate/lib/required文件夾下的所有jar文件、以及jdbc驅動文件(此文件另外下載)到項目的WEB-INF/lib文件夾下,拷貝hibernate/project/etc下的hibernate.cfg.xml文件到項目的src目錄下。
5.新建實體類Cat,Hibernate中配置實體類有兩種方法:XML文件配置和@注解配置,本例采用@注解配置,相關注解代表的含義在代碼中都有注明如下:
package com.levice.firsthibernate.bean; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; @Entity //注解Entity表示該類能被Hibernate持久化 @Table(name = "tb_cat") //指定該Entity對應的數據表名 public class Cat { @Id //指定該列為主鍵。主鍵類型最好不要使用int等原始類型 @GeneratedValue(strategy = GenerationType.AUTO) //主鍵類型auto表示該主鍵為自增長型 private Integer id; @Column(name = "name") //指定該屬性對應的數據庫表的列為name,列名與屬性名一樣時這句注解可省略 private String name; @Column(name = "description") private String description; @ManyToOne //指定實體類之間的關系,本例表示多對一關系 @JoinColumn(name = "mother_id") private Cat mother; @Temporal(TemporalType.TIMESTAMP)//日期類型(DATE,TIME或TIMESTEMP) @Column(name = "birthday") private Date birthday; //getters and setters public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Cat getMother() { return mother; } public void setMother(Cat mother) { this.mother = mother; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } }
6.修改配置文件hibernate.cfg.xml,內容及注釋如下:
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- 配置JDBC --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property> <property name="connection.username">root</property> <property name="connection.password">123456</property> <!-- 指定使用MySQL數據庫格式的SQL語句 --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- 指定在控制台打印生成的SQL語句 --> <property name="show_sql">true</property> <!-- 指定Hibernate啟動時自動創建表結構 --> <property name="hbm2ddl.auto">create</property> <!-- 加上這一句以防止未知錯誤 --> <property name="current_session_context_class">thread</property> <!-- 指定Cat類為Hibernate實體類 --> <mapping class="com.levice.firsthibernate.bean.Cat"/> </session-factory> </hibernate-configuration>
7.初始化數據庫,在MySQL中創建數據庫hibernate,SQL代碼如下:
create database hibernate;
8.配置HibernateUtil,就是修改HibernateUtil.java文件,這個文件在下載的hibernate文件中有,但我Copy過來的時候,一直沒調試成功,於是采用了一個版本比較老的HibernateUtil。這個文件的作用是獲取SessionFactory從而獲取Session,不同版本的hiberate中獲取SessionFactory的方法都不同,這裡可以新建一個HibernateUtil.java文件,然後把下面的代碼copy進去。
package com.levice.firsthibernate.util; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; @SuppressWarnings("deprecation") public class HibernateUtil { private static final SessionFactory sessionFactory; static{ try{ sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); }catch(Throwable ex){ System.err.println("Initial SessionFactory creation failed."); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory(){ return sessionFactory; } }
9.執行Hibernate程序,創建一個包含主函數main的類CatTest,代碼及注釋如下:
package com.levice.firsthibernate.test; import java.awt.Font; import java.util.Date; import java.util.List; import javax.swing.JOptionPane; import org.hibernate.Session; import org.hibernate.Transaction; import com.levice.firsthibernate.bean.Cat; import com.levice.firsthibernate.util.HibernateUtil; public class CatTest { public static void main(String[] args) { // TODO Auto-generated method stub /*初始化幾只Cat的信息*/ Cat mother = new Cat(); mother.setName("Mother White"); mother.setDescription("This is mother cat"); mother.setBirthday(new Date()); Cat kitty = new Cat(); kitty.setMother(mother); kitty.setName("Kitty"); kitty.setDescription("This is Kitty"); kitty.setBirthday(new Date()); Cat tom = new Cat(); tom.setMother(mother); tom.setName("Tom"); tom.setDescription("This is Tom"); tom.setBirthday(new Date()); @SuppressWarnings("static-access") Session session = new HibernateUtil().getSessionFactory().openSession(); //獲取session並open,開啟一個Hibernate會話 Transaction trans = session.beginTransaction(); //開啟一個事務 session.persist(mother); //將mother保存到數據庫 session.persist(kitty); session.persist(tom); @SuppressWarnings("all") List<Cat> catList = session.createQuery(" from Cat ").list(); //查詢數據庫中所有的貓 StringBuffer result = new StringBuffer(); result.append("all cats: \r\n\r\n"); for (Cat cc : catList) { result.append("name:" + cc.getName() + "\n"); result.append("mother:" + (cc.getMother() == null ? "null" : cc.getMother().getName()) + "\n"); result.append("description:" + cc.getDescription() + "\r\n\r\n"); } trans.commit(); //提交事務 session.close(); //關閉Hibernate會話 //用Swing顯示查詢結果 JOptionPane.getRootFrame().setFont(new Font("Arial", Font.BOLD, 14)); JOptionPane.showMessageDialog(null, result.toString()); } }
10.運行CatTest,可以看到如下輸出:
控制台輸出的SQL語句如下:
Hibernate: alter table tb_cat drop foreign key FK_dix3h50rxo8ahrcu5roir75n1 Hibernate: drop table if exists tb_cat Hibernate: create table tb_cat (id integer not null auto_increment, birthday datetime, description varchar(255), name varchar(255), mother_id integer, primary key (id)) Hibernate: alter table tb_cat add constraint FK_dix3h50rxo8ahrcu5roir75n1 foreign key (mother_id) references tb_cat (id) Hibernate: insert into tb_cat (birthday, description, mother_id, name) values (?, ?, ?, ?) Hibernate: insert into tb_cat (birthday, description, mother_id, name) values (?, ?, ?, ?) Hibernate: insert into tb_cat (birthday, description, mother_id, name) values (?, ?, ?, ?) Hibernate: select cat0_.id as id1_0_, cat0_.birthday as birthday2_0_, cat0_.description as descript3_0_, cat0_.mother_id as mother_i5_0_, cat0_.name as name4_0_ from tb_cat cat0_