Hibernate學習(2)單例模式實現SessionFactory

先做個補充:將上次的id手動添加改爲自增

<?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">
<hibernate-mapping>

    <class name="com.entity.TUserEntity" table="t_user" schema="test1">
        <id name="uid">
            <column name="uid" sql-type="int(10)"/>
            <generator class="identity"/>
        </id>
        <property name="username">
            <column name="username" sql-type="varchar(30)" length="30" not-null="true"/>
        </property>
        <property name="password">
            <column name="password" sql-type="varchar(30)" length="30" not-null="true"/>
        </property>
        <property name="age">
            <column name="age" sql-type="int(3)" not-null="true"/>
        </property>
    </class>
</hibernate-mapping>

這裏使用identity方法(不適用於Oracle數據庫)
將實體的映射添加

什麼是單例模式

單例模式,是一種常用的軟件設計模式。在它的核心結構中只包含一個被稱爲單例的特殊類。通過單例模式可以保證系統中,應用該模式的類一個類只有一個實例。即一個類只有一個對象實例


單例模式有多種實現方式,這裏使用一種簡單的方式:
由於SessionFactory是線程安全的不需要去考慮線程我們直接用餓漢式
先創建一個utils文件夾並創建工具類
這裏寫圖片描述
SessionFactoryUtil類:
package utils;

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

public class SessionFactoryUtil {
private static final Configuration cfg;
private static final SessionFactory sf;
static {
cfg = new Configuration().configure();
sf = cfg.buildSessionFactory();
}
public static SessionFactory getSession(){
return sf;
}

}
利用靜態代碼塊在一開始就實例化他
測試類:
package test;
import com.entity.TUserEntity;
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
import org.junit.*;
import utils.SessionFactoryUtil;

public class majorTest {

@Test
public void test(){
    System.out.println("test....");



    //單例模式創建會話工廠對象
        SessionFactory sessionFactory = SessionFactoryUtil.getSession();
    //會話對象
    Session session = sessionFactory.openSession();
    //開啓事務
    Transaction transaction = session.beginTransaction();
    TUserEntity tUserEntity = new TUserEntity();
    tUserEntity.setUsername("王琛昱");
    tUserEntity.setPassword("123456");
    tUserEntity.setAge(1);
    session.save(tUserEntity);
    //提交事務
    transaction.commit();
    //關閉事務
    session.close();

    sessionFactory.close();

}

}
測試類執行:
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章