一.Hibernate(開放源代碼的對象關系映射框架)簡介:
Hibernate是一個開放源代碼的對象關系映射框架,它對JDBC進行了非常輕量級的對象封裝,它將POJO與數據庫表建立映射關系,是一個全自動的orm框架,hibernate可以自動生成SQL語句,自動執行,使得Java程序員可以隨心所欲的使用對象編程思維來操縱數據庫。 Hibernate可以應用在任何使用JDBC的場合,既可以在Java的客戶端程序使用,也可以在Servlet/JSP的Web應用中使用,最具革命意義的是,Hibernate可以在應用EJB的J2EE架構中取代CMP,完成數據持久化的重任。
四.hibernate入門Demo
該項目使用到的jar包

1.我使用的是mysql關系型數據庫,先建立一個數據庫,並且創建一個customer(客戶信息)表


2.創建一個Customer實體類(持久化類)
持久化類是應用程序中的業務實體類,這里的持久化是指類的對象能夠被持久化保存到數據庫中.
Hibernate 使用普通的JAVA對象(POJO),即POJO的編程模式來進行持久化.
該類中包含的是與數據庫表相對應的各個屬性,這些屬性通過getter/setter方法來訪問,對外部隱藏了內部的實現細節.
通常持久化類的編寫應嘎遵循一些規則:
1).持久化類中必須提供無參數public構造器(如果沒有提供任何構造方法,虛擬機會自動提供默認構造方法,但是如果提供了其他有參數的構造方法的話
虛擬機不再提供默認構造方法,必須手動編寫無參構造方法).
2).持久化類中所有屬性使用private修飾,提供public的setter/getter方法
3).必須提供標識屬性OID,與數據庫表中逐漸對應,例如下面Customer類id屬性
4).持久化類屬性應盡量使用基本數據類型的包裝類型,例如int換成Integer,long換成Long,目的是為了與數據庫表的字段默認值null一致。(例如int是區分不開null跟0的,不賦值的int類型默認值為0)
5).持久化類不要用final修飾,使用final修飾將無法生成代理對象進行優化.
public class Customer {
private Integer id; //主鍵id
private String name; //客戶姓名
private Integer age; //客戶年齡
private String sex; //客戶性別
private String city; //客戶地址
/**
* @return the id
*/
public Integer getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Integer id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the age
*/
public Integer getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(Integer age) {
this.age = age;
}
/**
* @return the sex
*/
public String getSex() {
return sex;
}
/**
* @param sex the sex to set
*/
public void setSex(String sex) {
this.sex = sex;
}
/**
* @return the city
*/
public String getCity() {
return city;
}
/**
* @param city the city to set
*/
public void setCity(String city) {
this.city = city;
}
//重寫toString()方法
@Override
public String toString() {
return "Customer [id=" + id + ", name=" + name + ", age=" + age + ", sex=" + sex + ", city=" + city + "]";
}
}
3.編寫映射文件Customer.hbm.xml
實體類Customer目前還不具備持久化操作的能力,而Hibernate需要知道實體類Customer映射到數據庫 Hibernate中的哪個表,以及類中的哪個屬性
對應數據庫表中的哪一個字段,這些都需要在映射文件中配置.
在實體類Customer所在的包中,創建一個名稱為Customer.hbm.xml的映射文件,在該文件中定義了實體類Customer的屬性是如何映射到customer表的列上的
開始編寫xml文件,該文件頭部信息可以通過下面的步驟找到:


<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <!-- name代表的是實體類名,table代表的是表名 --> <class name="com.hck.entity.Customer" table="customer"> <!-- name=id代表的是customer類中屬性 column=id代表的是table表中的字段 --> <id name="id" column="id"> <!-- 主鍵生成策略 --> <generator class="native"/> </id> <!-- 其他屬性使用property標簽來映射 --> <property name="name" column="name" type="string"/> <property name="age" column="age" type="integer"/> <property name="sex" column="sex" type="string"/> <property name="city" column="city" type="string"/> </class> </hibernate-mapping>
4.編寫核心配置文件hibernate.cfg.xml
Hibernate的映射文件反映了持久化類和數據庫表的映射信息,
而Hibernate的配置文件則主要用來配置數據庫連接以及Hibernate運行時所需要的各個屬性的值.
在項目的src目錄下創建一個名稱為hibernate.cfg.xml的文件
xml的頭部編寫可以按下圖所以查找復制


編寫hibernate.cfg.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<!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>
<!--指定方言 -->
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<!-- 數據庫驅動 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 連接數據庫的url -->
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/tb_test</property>
<!-- 數據庫用戶名 -->
<property name="hibernate.connection.username">root</property>
<!-- 數據庫密碼 -->
<property name="hibernate.connection.password">123456</property>
<!-- 其他配置 -->
<!-- 格式化sql -->
<property name="format_sql">true</property>
<!-- 用來關聯hbm配置文件 -->
<mapping resource="com/hck/entity/Customer.hbm.xml"/>
</session-factory>
</hibernate-configuration>
5.編寫單元測試類代碼如下:
1).解釋一下
config=new Configuration().configure();是如何讀取src目錄下的hibernate.cfg.xml
跟蹤代碼可以看到:

默認讀取src目錄下的hibernate.cfg.xml文件,所以hibernate.cfg.xml文件放在src是基於約定優於配置原理的
public class HibernateTestDemo {
//定義變量
Configuration config;
SessionFactory sessionFactory;
Session session;
Transaction transaction;
//before表示在方法執行前執行
@Before
public void setUp()
{
//1.加載hibernate.cfg.xml配置
config=new Configuration().configure();
//2.獲取SessionFactory
sessionFactory=config.buildSessionFactory();
//3.獲得一個session
session=sessionFactory.openSession();
//4.開始事務
transaction=session.beginTransaction();
}
//添加操作
@Test
public void insert()
{
//5.操作
Customer customer=new Customer();
customer.setId(1);
customer.setName("zhangsan");
customer.setAge(20);
customer.setSex("m");
customer.setCity("guangzhou");
session.save(customer);
}
//刪除操作
@Test
public void delete()
{
//先查詢
Customer customer=(Customer)session.get(Customer.class, 1);
//再刪除
session.delete(customer);
}
//查詢操作
@Test
public void select()
{
Customer customer=(Customer)session.get(Customer.class, 1);
System.out.println(customer);
}
//更新操作
@Test
public void update()
{
Customer customer=new Customer();
customer.setId(1);
customer.setName("zhangsan");
customer.setAge(20);
customer.setSex("m");
//修改地址為beijing
customer.setCity("beijing");
//存在就更新,不存在就執行插入操作
session.saveOrUpdate(customer);
}
//After表示在方法執行結束后執行
@After
public void closeTransaction()
{
//6.提交事務
transaction.commit();
//7.關閉資源
session.close();
sessionFactory.close();
}
}
1)執行插入操作后,打開mysql使用select * from customer;得到的結果:

2)執行查詢操作(查看控制台輸出)

3.執行更新操作

4.刪除操作

五.總結
超級完整版hibernate入門demo完成了,如有不懂或者問題請留言~
