hibernate學習之簡單入門程式
1. 建立專案,匯入jar包,建立Java專案即可。
(1)在hibernate-release-5.2.12.Final\lib\required中的所有jar包,和lib\jpa-metamodel-generator在的jar包
(2)mysql的驅動包:mysql-connector-java-5.1.38-bin.jar
(3)日誌包:log4j-1.2.17.jar,slf4j-api-1.7.5.jar,slf4j-log4j12-1.7.5.jar
(4)在專案下面新建lib包(Folder),將上面的jar複製進去,然後選中jar包,右鍵選擇Bulid path->Add to bulid path
2. 建立實體類
public class User { //hibernate要求實體類有一個屬性是唯一的 private int uId; private String uName; private String uPassword; private String uAddress; public int getuId() { return uId; } public void setuId(int uId) { this.uId = uId; } public String getuName() { return uName; } public void setuName(String uName) { this.uName = uName; } public String getuPassword() { return uPassword; } public void setuPassword(String uPassword) { this.uPassword = uPassword; } public String getuAddress() { return uAddress; } public void setuAddress(String uAddress) { this.uAddress = uAddress; } }
注:使用hibernate時,不需要手動建立表,hibernate可以幫我們建立表
3. 配置實體類和資料庫表一一對應關係(對映關係,使用配置檔案實現對映關係)
(1)建立xml格式的配置檔案,檔案的名稱和位置沒有固定的要求(一般建議在實體類所在的包裡面建立,實體類名稱.hbm.xml)。如在這個專案中要建立User.hbm.xml。
(2)在xml檔案(User.hbm.xml)中引入xml約束(如dtd、schema),在hibernate裡面需要引進dtd約束。
尋找方法:在hibernate-release-5.2.12.Final中搜索hbm.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">
(3)配置對映關係
<hibernate-mapping>
<!-- 1. 配置類和表 -->
<class name="com.zzc.entity.User" table="user">
<!-- 2.配置實體類id和表id對應 -->
<id name="uId" column="uId">
<!-- 3. 設定資料庫表id增長策略(自動增長:native)-->
<generator class="native"></generator>
</id>
<!-- 設定其他屬性和表字段型別 -->
<property name="userName" column="userName"></property>
<property name="password" column="password"></property>
<property name="address" column="address"></property>
</class>
</hibernate-mapping>
4. 建立hibernate核心配置檔案
(1)hibernate核心配置檔案為xml格式,但它的名稱和位置是固定的。
- 名稱:必須為hibernate.cfg.xml
- 位置:必須在src下面
(2)引入dtd約束
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
(3)hibernate操作過程中,只會載入核心配置檔案,其他配置檔案不會載入,所以要在核心配置檔案中配置。
第一部分:配置資料庫資訊(必須的)
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:jdbc:mysql://localhost:3306/資料庫名?characterEncoding=utf-8</property>
<property name="hibernate.connection.username">資料庫的使用者名稱</property>
<property name="hibernate.connection.password">資料庫的密碼</property>
第二部分:配置hibernate資訊 (可選的)
<!-- 輸出底層SQL語句 -->
<property name="hibernate.show_sql">true</property>
<!-- 輸出底層SQL語句 格式 -->
<property name="hibernate.format_sql">true</property>
<!-- hibernate建立表(需要配置)
update:如果有表->更新,如果沒有->建立
-->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 配置資料庫方言:讓hibernate框架識別不同資料庫特有的語句
在MySQL中實現分頁:使用limit關鍵字(只能在mysql中使用),
在oracle中實現分頁:使用rownum
-->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
第三部分:把對映檔案放到核心配置檔案中(必須的)
<mapping resource="com/***/***/entity/User.hbm.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.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate?characterEncoding=utf-8</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123</property>
<!-- 第二部分:配置hibernate資訊 -->
<!-- 輸出底層SQL語句 -->
<property name="hibernate.show_sql">true</property>
<!-- 輸出底層SQL語句 格式 -->
<property name="hibernate.format_sql">true</property>
<!-- hibernate建立表(需要配置)
update:如果有表->更新,如果沒有->建立
-->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 配置資料庫方言:讓hibernate框架識別不同資料庫特有的語句
在MySQL中實現分頁:使用limit關鍵字(只能在mysql中使用),
在oracle中實現分頁:使用rownum
-->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 第三部分:把對映檔案放到核心配置檔案中 必須的 -->
<mapping resource="com/zzc/hibernate/entity/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
5. 實現增刪查改功能
第一步:載入hibernate的核心配置檔案
Configuration cfg = new Configuration();
cfg.configure();
第二步:建立SessionFactory物件
SessionFactory sessionFactory = cfg.buildSessionFactory();
第三步:使用SessionFactory建立session物件
Session session = sessionFactory.openSession();
第四步:開啟事務
Transaction ts = session.beginTransaction();
第五步:寫具體邏輯crud操作(新增功能)
User user = new User();
user.setUserName("王小明");
user.setPassword("1234");
user.setAddress("北京市");
//呼叫session方法實現新增功能
session.save(user);
第六步:提交事務
ts.commit();
第七步:關閉資源
session.close();
sessionFactory.close();
完整的程式碼:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.zzc.hibernate.entity.User;
public class HibernateTestDemo {
public static void testAdd() {
Configuration cfg = new Configuration();
cfg.configure();
SessionFactory sessionFactory = cfg.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction ts = session.beginTransaction();
User user = new User();
user.setUserName("王小明");
user.setPassword("1234");
user.setAddress("北京市");
session.save(user);
ts.commit();
session.close();
sessionFactory.close();
}
public static void main(String[] args) {
testAdd();
}
}
6. 測試結果
(1)起初出現了問題,報錯:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'hibernate.user’...
解決辦法:將hibernate.cfg.xml中配置方言的部分程式碼改為:
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
(2)之後報錯Incorrect string value: '\xE7\x8E\x8B\xE5\xB0\x8F...' for column 'userName' at row 1。產生
這個錯誤的原因是,在建立
資料庫
的的時候編碼格式為latin1,只要將編碼改為UTF-8即可。
改完資料庫後,在進行測試,成功建立user表,並將資料匯入。
console輸出:
Hibernate:
create table user (
uId integer not null auto_increment,
userName varchar(255),
password varchar(255),
address varchar(255),
primary key (uId)
) engine=InnoDB
Hibernate:
insert
into
user
(userName, password, address)
values
(?, ?, ?)
注:如果資料庫方言配置為:
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
也可正常執行,console輸出為:
Hibernate:
create table user (
uId integer not null auto_increment,
userName varchar(255),
password varchar(255),
address varchar(255),
primary key (uId)
) engine=MyISAM
Hibernate:
insert
into
user
(userName, password, address)
values
(?, ?, ?)
由此可見:
MySQL5Dialect效果和MySQLMyISAMDialect效果是一致的,如果想要使用InnoDB,請一定配置org.hibernate.dialect.MySQL5InnoDBDialect。
各資料庫對應的方言(Dialect):
資料庫 |
方言(Dialect) |
DB2 |
org.hibernate.dialect.DB2Dialect |
DB2 AS/400 |
org.hibernate.dialect.DB2400Dialect |
DB2 OS390 |
org.hibernate.dialect.DB2390Dialect |
PostgreSQL |
org.hibernate.dialect.PostgreSQLDialect |
MySQL5 |
org.hibernate.dialect.MySQL5Dialect |
MySQL5 with InnoDB |
org.hibernate.dialect.MySQL5InnoDBDialect |
MySQL with MyISAM |
org.hibernate.dialect.MySQLMyISAMDialect |
Oracle(any version) |
org.hibernate.dialect.OracleDialect |
Oracle 9i |
org.hibernate.dialect.Oracle9iDialect |
Oracle 10g |
org.hibernate.dialect.Oracle10gDialect |
Oracle 11g |
org.hibernate.dialect.Oracle10gDialect |
Sybase |
org.hibernate.dialect.SybaseASE15Dialect |
Sybase Anywhere |
org.hibernate.dialect.SybaseAnywhereDialect |
Microsoft SQL Server 2000 |
org.hibernate.dialect.SQLServerDialect |
Microsoft SQL Server 2005 |
org.hibernate.dialect.SQLServer2005Dialect |
Microsoft SQL Server 2008 |
org.hibernate.dialect.SQLServer2008Dialect |
SAP DB |
org.hibernate.dialect.SAPDBDialect |
Informix |
org.hibernate.dialect.InformixDialect |
HypersonicSQL |
org.hibernate.dialect.HSQLDialect |
H2 Database |
org.hibernate.dialect.H2Dialect |
Ingres |
org.hibernate.dialect.IngresDialect |
Progress |
org.hibernate.dialect.ProgressDialect |
Mckoi SQL |
org.hibernate.dialect.MckoiDialect |
Interbase |
org.hibernate.dialect.InterbaseDialect |
Pointbase |
org.hibernate.dialect.PointbaseDialect |
FrontBase |
org.hibernate.dialect.FrontbaseDialect |
Firebird |
org.hibernate.dialect.FirebirdDialect |