據說Hibernate已經好久了,可是直到最近纔開始和它近距離的接觸。很早以前在湘計就看到過一份培訓的PPT,裏面說到Hibernate應用於持久層,而且Hibernate和持久化彷佛形影相隨,老是成雙成對的出現。那麼Hibernate究竟是作什麼用的,它有什麼優勢呢?關於Hibernate的一些概念諸如ORM、持久化就不贅述了,咱們直接開始構建咱們的一個Hibernate應用(一般咱們的應用都是Web應用,這裏我仍是建一個Web工程,可是運行的時候我用Java Application的方式運行,這樣比較容易理解,由於在Web應用中Hibernate都會和Spring等框架一塊兒使用)。java
構建一個Hibernate應用咱們須要準備什麼東西呢?首先固然是去官網上下一個Hibernate的發佈包咯,我下的是3.0。接下來咱們按照以下步驟來進行mysql
1.準備一個配置文件hibernate.cfg.xml,它裏面定義了一些基本的屬性,如數據庫鏈接的相關參數、映射文件的地址等等,這個文件是必須的,Hibernate會首先解析並加載這個xml文件並存放在緩存中,個人hibernate.cfg.xml內容以下:
<?xml version="1.0" encoding="UTF-8"?>sql
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd" >
<hibernate-configuration>
<session-factory>
<property name="connection.url">
jdbc:mysql://localhost:3306/test
</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.username">root</property>
<property name="connection.password">111111</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="show_sql">true</property>
<mapping resource="cn/edu/hust/cm/mypack/Customer.hbm.xml" />數據庫
</session-factory>
</hibernate-configuration>緩存
2.我用的是Mysql數據庫,不一樣的DBMS有些地方會不一樣。假設我如今數據庫中有一張表存放顧客基本信息,我建立了一個Customer表,Schema以下所示:session
CREATE TABLE `customer` (
`id` bigint(11) NOT NULL DEFAULT '0',
`name` varchar(40) NOT NULL DEFAULT '',
`email` varchar(128) CHARACTER SET latin1 NOT NULL DEFAULT '',
`password` varchar(8) NOT NULL DEFAULT '',
`phone` int(11) DEFAULT '0',
`address` varchar(255) DEFAULT NULL,
`sex` char(1) CHARACTER SET latin1 DEFAULT NULL,
`is_married` bit(1) DEFAULT NULL,
`description` text,
`p_w_picpath` blob,
`birthday` date DEFAULT NULL,
`registered_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP)app
3.建立一個Customer.java文件(這就是咱們所說的持久化類)
- package cn.edu.hust.cm.mypack;
- import java.io.Serializable;
- import java.sql.Date;
- import java.sql.Timestamp;
- /**
- * @author zhukai
- *
- */
- public class Customer implements Serializable {
- private Long id;
- private String name;
- private String email;
- private String password;
- private int phone;
- private boolean married;
- private String address;
- private char sex;
- private String description;
- //private byte[] p_w_picpath;
- private Date birthday;
- private Timestamp registeredTime;
- /**
- * hibernate要求持久化類必須提供一個不帶參數的默認構造方法
- */
- public Customer() {
- // TODO Auto-generated constructor stub
- }
- public String getAddress() {
- return address;
- }
- public void setAddress(String address) {
- this.address = address;
- }
- public String getDescription() {
- return description;
- }
- public void setDescription(String description) {
- this.description = description;
- }
- public Date getBirthday() {
- return birthday;
- }
- public void setBirthday(Date birthday) {
- this.birthday = birthday;
- }
- public String getEmail() {
- return email;
- }
- public void setEmail(String email) {
- this.email = email;
- }
- public Long getId() {
- return id;
- }
- public void setId(Long id) {
- this.id = id;
- }
- public boolean isMarried() {
- return married;
- }
- public void setMarried(boolean married) {
- this.married = married;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public int getPhone() {
- return phone;
- }
- public void setPhone(int phone) {
- this.phone = phone;
- }
- public Timestamp getRegisteredTime() {
- return registeredTime;
- }
- public void setRegisteredTime(Timestamp registeredTime) {
- this.registeredTime = registeredTime;
- }
- public char getSex() {
- return sex;
- }
- public void setSex(char sex) {
- this.sex = sex;
- }
- }
注意,這個類採用的是標準JavaBean形式,一般咱們都要按照這個標準來構建咱們的持久化類。
4.配置映射文件
通常映射文件採用約定俗成的命名規則:類名.hbm.xml,和這個類的class文件放在一個目錄下面,個人Customer.hbm.xml文件以下所示:
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping
- DTD 3.0//EN" "http://hibernate.sourceforge.net/
- hibernate-mapping-3.0.dtd" >
- <hibernate-mapping>
- <class name="cn.edu.hust.cm.mypack.Customer" table="CUSTOMER">
- <id name="id" type="long">
- <column name="ID"></column>
- <generator class="increment"></generator>
- </id>
- <property name="name" type="string">
- <column name="NAME" not-null="true"></column>
- </property>
- <property name="email" type="string">
- <column name="EMAIL" not-null="true"></column>
- </property>
- <property name="password" type="string">
- <column name="PASSWORD" not-null="true"></column>
- </property>
- <property name="phone" type="integer">
- <column name="PHONE" not-null="true"></column>
- </property>
- <property name="address" type="string">
- <column name="ADDRESS"></column>
- </property>
- <property name="sex" type="character">
- <column name="SEX"></column>
- </property>
- <property name="married" type="boolean">
- <column name="IS_MARRIED"></column>
- </property>
- <property name="description" type="string"></property>
- <property name="birthday" type="date">
- <column name="BIRTHDAY"></column>
- </property>
- <property name="registeredTime" type="timestamp">
- <column name="REGISTERED_TIME"></column>
- </property>
- </class>
- </hibernate-mapping>
注意,這個文件是很是關鍵的,它聯繫了咱們的持久化類以及其在數據庫中對應的表,具體的關係以下圖所示:
映射文件就像一個字典同樣,Hibernate向數據庫插入數據時經過「查詢」它能夠知道屬性對應於數據庫中哪一個列,從數據庫中把數據讀出賦給持久化類時則經過「查詢」知道列對應於持久化類的哪一個屬性。這個比喻不是很恰當,由於並非持久化類的全部屬性都直接和表的字段匹配。
OK,如今準備工做都已經作好了,能夠編寫一個程序來使用Hibernate了,個人運行主程序以下所示:
- package cn.edu.hust.cm.mypack;
- import javax.servlet.*;
- import org.hibernate.*;
- import org.hibernate.cfg.Configuration;
- import java.io.*;
- import java.sql.Date;
- import java.sql.Timestamp;
- import java.util.Iterator;
- import java.util.List;
- public class BusinessService {
- public static SessionFactory sessionFactory;
- /*靜態塊,類加載時即執行,用來初始化Hibernate,建立SessionFatory實例*/
- static{
- try{
- Configuration configuration=new Configuration();
- sessionFactory=configuration.configure().buildSessionFactory();
- }
- catch(Exception e){
- e.printStackTrace();
- }
- finally{
- }
- }
- /*默認的構造方法*/
- public BusinessService() {
- }
- public static SessionFactory getSessionFactory() {
- return sessionFactory;
- }
- /**
- * 該方法是測試入口,對各個方法進行測試
- */
- public void test(){
- Customer customer=new Customer();
- customer.setName("朱楷");
- customer.setEmail("xiaozhu87487705@163.com");
- customer.setPassword("19840827");
- customer.setPhone(1234);
- customer.setAddress("湖北省武漢市珞瑜路1037號");
- customer.setSex('M');
- customer.setMarried(false);
- customer.setDescription("芒果網員工");
- customer.setBirthday(new Date(14*365*24*3600*1000));
- customer.setRegisteredTime(new Timestamp(36*365*24*3600*10000));
- saveCustomer(customer);
- findAllCustomers();
- loadAndUpdateCustomer(customer.getId());
- deleteAllCustomers(customer);
- }
- /**
- * 把一個Customer對象保存在數據庫中
- */
- public void saveCustomer(Customer customer){
- Session session=sessionFactory.openSession();
- Transaction tx = null;//局部變量必須賦予初始值
- try{
- tx=session.beginTransaction();
- //事務開始
- session.save(customer);
- tx.commit();
- }
- catch(Exception e){
- if(tx!=null) tx.rollback();
- e.printStackTrace();
- }
- finally{
- session.close();
- }
- }
- /**
- * 查詢出數據中全部的持久化對象,並顯示它們的基本信息
- */
- public void findAllCustomers(){
- Session session=sessionFactory.openSession();
- Transaction tx=null;
- try{
- tx=session.beginTransaction();
- //事務開始
- Iterator customers=session.createQuery("from Customer")
- .list().iterator();
- while(customers.hasNext()){
- Customer cs=(Customer)customers.next();
- System.out.println("姓名:"+cs.getName());
- System.out.println("性別:"+cs.getSex());
- System.out.println("電子郵箱:"+cs.getEmail());
- System.out.println("婚否:"+cs.isMarried());
- }
- tx.commit();
- }
- catch(Exception e){
- if(tx!=null) tx.rollback();
- e.printStackTrace();
- }
- finally{
- session.close();
- }
- }
- /**
- * 加載指定的持久化對象並對其進行修改
- * @param id 對象標識符OID
- */
- public void loadAndUpdateCustomer(long id){
- Session session=sessionFactory.openSession();
- Transaction tx=null;
- try{
- tx=session.beginTransaction();
- //事務開始
- Customer cs=(Customer)session.load(Customer.class, id);
- cs.setAddress("廣東省深圳市");
- tx.commit();
- }
- catch(Exception e){
- if(tx!=null) tx.rollback();
- e.printStackTrace();
- }
- finally{
- session.close();
- }
- }
- public void deleteAllCustomers(Customer c){
- Session session=sessionFactory.openSession();
- Transaction tx=null;
- try{
- tx=session.beginTransaction();
- //事務開始
- session.delete(c);
- //Query query=session.createQuery("delete from Customer");
- //query.executeUpdate();
- tx.commit();
- }
- catch(Exception e){
- if(tx!=null) tx.rollback();
- e.printStackTrace();
- }
- finally{
- session.close();
- }
- }
- /**
- * @param args
- */
- public static void main(String[] args) {
- BusinessService bs=new BusinessService();
- bs.test();
- sessionFactory.close();
- }
- }
這樣,咱們的第一個Hibernate應用程序就大功告成了,至於Hibernate中的各個類以及接口如Session、SessionFactory接口是幹什麼用的,在之後的學習中再陸續介紹,主要是由於我尚未好好的學習這幾個類,^_^。