- hibernate的主鍵生成器:
generator元素:表示了一個主鍵生成器,它用來爲持久化類實例生成唯一的標識 。
1.1 程序員自己控制:assigned
1.2 數據庫控制: identity(標識列/自動增長) sequence
1.3 hibernate控制:increment uuid/uuid.hex
1.4 其它:native
student id int
worker id varchar
2. 主鍵生成器要求
2.1 assigned
數據類型不限、保存前必須賦值
2.2 identity(重點掌握)
數字,無需賦值
2.3 sequence(重點掌握)
數字,無需賦值, 默認使hibernate_sequence這個序列,
也可以通過sequence/sequence_name參數賦值
2.4 increment
數字,無需賦值
2.5 uuid/uuid.hex (是由容器自動生成的一個32位的字符串,.hex代表的是十六進制)
32位的字符串,無需賦值,
2.6 native(重點掌握)
等於identity+sequence
- 自定義主鍵生成器
3.1 *.hbm.xml指定主鍵生成器類
3.2 創建主鍵生成器類
實現org.hibernate.id.IdentifierGenerator接口即可,並還可以實現org.hibernate.id.Configurable接口來讀取一些配置信息
PersistentIdentifierGenerator.TABLE
PersistentIdentifierGenerator.PK
assigned、native、自定義主鍵
1、hibernateutil工具類
2、程序員自己控制:assigned
3、數據庫控制: identity(標識列/自動增長) sequence
4、hibernate控制:increment uuid/uuid.hex
5、其它native
6、自定義主鍵生成器
案例:myincrement/myts
工具類
package com.zking.two.util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
- hibernate工具類
- 未整合框架前使用
- @author Administrator
*/
public class HibernateUtils {
private static SessionFactory sessionFactory;
// 存放當前會話
private static ThreadLocal threadLocal = new ThreadLocal();
static {
Configuration cfg = new Configuration();
Configuration configure = cfg.configure(“hibernate.cfg.xml”);
sessionFactory = configure.buildSessionFactory();
}
public static Session openSession() {
Session session = threadLocal.get();
if (null == session) {
session = sessionFactory.openSession();
threadLocal.set(session);
}
return session;
}
public static void closeSession() {
Session session = threadLocal.get();
if (null != session) {
if (session.isOpen()) {
session.close();
}
threadLocal.set(null);
}
}
public static void main(String[] args) {
Session session = openSession();
System.out.println(session.isConnected());
closeSession();
}
}
送你一個測試數據庫
create table t_hibernate_worker
(
wid varchar(32) primary key,
wname varchar(50) not null
);
select * from t_hibernate_worker;
delete from t_hibernate_worker;
create table t_hibernate_student
(
sid int primary key NULL AUTO_Increment,
sname varchar(50) not null
);
select * from t_hibernate_student;
delete from t_hibernate_student;