一,hibernate的介紹
hibernate是一款基于ORM的數(shù)據(jù)庫開源框架,所謂的ORM即Object Realational Mapping(對象關(guān)系映射),簡單的說就是可以讓使用該框架的人通過面向?qū)ο蟮恼Z言去操控關(guān)系型數(shù)據(jù)庫。與傳統(tǒng)的通過JDBC來完成數(shù)據(jù)庫的操作相比,使用該框架可以大大降低開發(fā)者的工作量,使其從關(guān)系型數(shù)據(jù)庫的各種操作中脫離出來(加載驅(qū)動,創(chuàng)建連接等)。JAVA中一個POJO的類是通過hibernate中的SQlSessionFactory維護(hù),然后映射到數(shù)據(jù)庫中相應(yīng)的表。常用的ORM框架還有Mybatis等。
二,hibernate的使用
hibernate有兩種使用方式,一種是通過配置相應(yīng)的xml文件,然后進(jìn)行各種初始化工作;另一種便是通過注解的方式。
2.1 項目的搭建
(1)通過Eclipse創(chuàng)建一個maven項目
(2)修改pom.xml文件引入hibernate所需要的一些jar包
本項目maven使用了3.5.4的版本,jdk使用了1.8,hibernate的版本是3.5.4-Final,pom文件內(nèi)容如下:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
? xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
? <modelVersion>4.0.0</modelVersion>
? <groupId>com.mytest</groupId>
? <artifactId>Hibernatetest</artifactId>
? <packaging>war</packaging>
? <version>0.0.1-SNAPSHOT</version>
? <name>Hibernatetest Maven Webapp</name>
? <url>http://maven.apache.org</url>
? <dependencies>
? ? <dependency>
? ? ? <groupId>junit</groupId>
? ? ? <artifactId>junit</artifactId>
? ? ? <version>3.8.1</version>
? ? ? <scope>test</scope>
? ? </dependency>
? ? <!-- 添加hibernate的依賴 開始-->
? ? <dependency>
? ? ? ? <groupId>dom4j</groupId>
? ? ? ? <artifactId>dom4j</artifactId>
? ? ? ? <version>1.6.1</version>
? ? </dependency>
? ? <dependency>
? ? ? ? <groupId>commons-logging</groupId>
? ? ? ? <artifactId>commons-logging</artifactId>
? ? ? ? <version>1.1.1</version>
? ? </dependency>
? ? <!-- https://mvnrepository.com/artifact/log4j/log4j -->
? ? <dependency>
? ? ? <groupId>log4j</groupId>
? ? ? <artifactId>log4j</artifactId>
? ? ? <version>1.2.17</version>
? ? </dependency>
? ? <dependency>
? ? ? ? <groupId>commons-collections</groupId>
? ? ? ? <artifactId>commons-collections</artifactId>
? ? ? ? <version>3.2.1</version>
? ? </dependency>
? ? <dependency>
? ? ? ? <groupId>cglib</groupId>
? ? ? ? <artifactId>cglib-nodep</artifactId>
? ? ? ? <version>3.1</version>
? ? </dependency>
? ? <!-- Hibernate library dependecy end -->
? ? <dependency>
? ? ? ? <groupId>javax.transaction</groupId>
? ? ? ? <artifactId>jta</artifactId>
? ? ? ? <version>1.1</version>
? ? </dependency>?
? ? <!-- 添加hibernate的依賴 結(jié)束-->
? ? <!-- mysql數(shù)據(jù)庫的驅(qū)動包 -->
? ? <dependency>
? ? ? ? ? ? <groupId>mysql</groupId>
? ? ? ? ? ? <artifactId>mysql-connector-java</artifactId>
? ? ? ? ? ? <version>5.1.6</version>
? ? ? </dependency>
? ? ? <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-annotations -->
? ? ? <!-- 添加maven的注解功能 -->
? ? <dependency>
? ? ? <groupId>org.hibernate</groupId>
? ? ? <artifactId>hibernate-annotations</artifactId>
? ? ? <version>3.5.4-Final</version>
? ? </dependency>
? <!-- https://mvnrepository.com/artifact/org.javassist/javassist -->
<dependency>
? ? <groupId>org.javassist</groupId>
? ? <artifactId>javassist</artifactId>
? ? <version>3.24.0-GA</version>
</dependency>
<!--? ? https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
? ? <dependency>
? ? ? <groupId>org.slf4j</groupId>
? ? ? <artifactId>slf4j-log4j12</artifactId>
? ? ? <version>1.7.25</version>
? ? ? <scope>test</scope>
? ? </dependency>
<!--? ? https://mvnrepository.com/artifact/org.slf4j/slf4j-nop -->
? <dependency>
? ? <groupId>org.slf4j</groupId>
? ? <artifactId>slf4j-nop</artifactId>
? ? <version>1.7.2</version>
? </dependency>
? <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api-->
? <dependency>
? ? <groupId>org.slf4j</groupId>
? ? <artifactId>slf4j-api</artifactId>
? ? <version>1.7.25</version>
</dependency>
? </dependencies>
? <build>
? ? <finalName>Hibernatetest</finalName>
? ? <plugins>
<!-- define the project compile level -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
? </build>
</project>
注意:在最后運行的時候要是報某某class文件找不到的錯誤,那就是說明引入的jar包少了,在網(wǎng)上搜一下報錯信息找到缺少的jar包,然后引入相應(yīng)的jar包依賴即可,我在剛開始用的時候也是前前后后添加了好幾個依賴...以上pom文件在我的機器上是不存在問題的。
2.2 使用
創(chuàng)建項目相應(yīng)的文件,最后整個項目的主要文件結(jié)構(gòu)如下:
其中domain包下放JavaBean,test包下放相應(yīng)的測試?yán)?,mapping路徑下放映射文件,hibernate.cfg.xml是hibernate的配置文件,里面配置有數(shù)據(jù)庫連接屬性等內(nèi)容,hibernate就是通過該文件進(jìn)行初始化的。
(1)在domain包下建一個Student類,內(nèi)容如下:
package com.domain;
public class Student {
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
該類將與數(shù)據(jù)庫中的表進(jìn)行映射,類中的屬性便為數(shù)據(jù)庫中的字段。
(2)在數(shù)據(jù)庫中進(jìn)行建表操作
create table tb_student(
? id int(10) primary key auto_increment,?
? name varchar(20),
? age int(3)
);
(3)修改hibernate.cfg.xml文件,其實使用properties文件一樣可以,但是我比較習(xí)慣使用xml文件。具體內(nèi)容如下:
<?xml version="1.0" encoding="utf-8"?>
<!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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
? ? ? ? <property name="hibernate.connection.password">root</property>
? ? ? ? <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mytest</property>
? ? ? ? <property name="hibernate.connection.username">root</property>
? ? ? ? <!-- 方言設(shè)置,不同的數(shù)據(jù)庫有不同的方言信息,以下為mysql的 -->
? ? ? ? <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
? ? ? ? <!--2.2.顯示Hibernate在運行的時候執(zhí)行的sql語句-->
? ? ? ? <property name="hibernate.show_sql">true</property>
? ? ? ? <!--2.3.格式化sql-->
? ? ? ? <property name="hibernate.format_sql">true</property>
? ? ? ? <!--2.4.自動建表-->
? ? ? ? <!-- 使用了該配置要是相應(yīng)的表還沒有被創(chuàng)建,那么在運行時hibernate會自動新建一個相應(yīng)的表 -->
? ? ? ? <property name="hibernate.hbm2ddl.auto">update</property>
? ? ? ? <mapping resource="mapping/StudentMapping.hbm.xml"></mapping>
? ? </session-factory>
</hibernate-configuration>
//注意上面的mapping resource節(jié)點指明了映射文件所在路徑
(4)在mapping文件夾新建一個StudentMapping.hbm.xml文件,該文件配置了映射類的信息,具體內(nèi)容如下:
<?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="com.domain.Student" table="tb_student">
? ? ? ? <!-- id字段表示數(shù)據(jù)庫主鍵生成策略
? ? ? ? native 使 Hibernate 可以使用 identity, sequence 或 hilo 算法根據(jù)底層數(shù)據(jù)庫的情況來創(chuàng)建主鍵。
? ? ? ? -->
? ? ? ? <id name="id" column="id" type="int">
? ? ? ? ? ? <generator class="native"/>
? ? ? ? </id>
? ? ? ? <!-- type屬性會將Java類型轉(zhuǎn)換為sql數(shù)據(jù)類型,name指實體類中的屬性名稱,column指在數(shù)據(jù)庫中的列名 -->
? ? ? ? <property name="name" column="name"? type="java.lang.String" length="20"/>
? ? ? ? <property name="age" column="age" type="int"></property>
? ? </class>
</hibernate-mapping>
(5)在com.test包下新建一個測試類,具體內(nèi)容如下:
package com.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.domain.Student;
public class HibernateTest {
public static void main(String[] args) {
Configuration config = new Configuration().configure("hibernate.cfg.xml");
//開啟會話工廠
SessionFactory sessionFactory = config.buildSessionFactory();
//開啟會話
Session session = sessionFactory.openSession();
//開啟事務(wù)
Transaction tr = session.beginTransaction();
try {
Student stu = new Student();
stu.setName("隔壁老王");
stu.setAge(17);
//保存數(shù)據(jù)
session.save(stu);
//記得要提交事務(wù),不然不會保存的呀
tr.commit();
}catch(Exception e) {
e.printStackTrace();
tr.rollback();
? ?}
?}
}
運行,若控制臺打印如下信息則表示執(zhí)行成功:
查找tb_student表,看看數(shù)據(jù)是否被保存:
此處由于我們使用了mysql的主鍵自增,所以在進(jìn)行保存的時候不用在顯式的指明id的值。
常見的錯誤:
(1)保證自己的mysql在本地是可以被訪問的
(2)hibernate.cfg.xml中關(guān)于數(shù)據(jù)庫的配置信息要替換成自己的
(3)如何插入中文報錯,說明數(shù)據(jù)庫的默認(rèn)編碼方式不對,需要設(shè)置為utf-8。
下一節(jié)將記錄hibernate注解的使用。