1. 程式人生 > >Hibernate工具類和主鍵生成策略

Hibernate工具類和主鍵生成策略

建立hibernate的好處
1.方便獲取session繪畫,用來操作資料庫
2.用來檢測所有的對映檔案配置是否準確

package com.two.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class SessionFactoryUtil {
	/**
	 * 1.方便獲取session繪畫,用來操作資料庫
	 * 2.用來檢測所有的對映檔案配置是否準確
	 */
	
	private static SessionFactory sessionFactory;
	static {
		Configuration cfg =new Configuration().configure("hibernate.cof.xml");
		sessionFactory=cfg.buildSessionFactory();
	}
	
	public static Session getSession() {
		Session session =sessionFactory.getCurrentSession();
		if(session==null) {
			session=sessionFactory.openSession();
		}
		return session;
	}
	
	
	public static void closeSession() {
		Session session=sessionFactory.getCurrentSession();
		if(session!=null&&session.isOpen()) {
			session.close();
		}
	}
	
	public static void main(String[] args) {
		Session session = SessionFactoryUtil .getSession();
//		開啟一個事物,否則會報錯
		session.beginTransaction();
		System.out.println(session.isConnected());
		SessionFactoryUtil.closeSession();
		System.out.println(session.isConnected());
		
	}
}

主鍵生成策略
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

  1. 自定義主鍵生成器
    3.1 *.hbm.xml指定主鍵生成器類

3.2 建立主鍵生成器類
實現org.hibernate.id.IdentifierGenerator介面即可,並還可以實現org.hibernate.id.Configurable介面來讀取一些配置資訊
PersistentIdentifierGenerator.TABLE
PersistentIdentifierGenerator.PK

自定義主鍵生成策略

package com.zking.two.id;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;

public class MyIdCreate implements IdentifierGenerator{

public Serializable generate(SharedSessionContractImplementor arg0, Object arg1) throws HibernateException {
	//公司名_模組名_時間撮
	return "zking_order_"+new SimpleDateFormat("yyyy-MM-dd hh:mm:sss").format(new Date());
}

}