Hibernate5 版本 SessionFactory

Hibernate4 版本中创建 SessionFactory

1
2
3
4
5
6
7
//Configuration 就是代表着 hibernate 的那个 xml 配置文件对象,如果 configure 方法中没有参数的话,默认是就是hibernate.cfg.xml。
Configuration conf = new Configuration().configure();
//服务注册,这是使用创建者模式,根据配置文件中的配置字段来构建注册服务(这应该是 hibernate 架构中注册服务的通用流程)
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().
applySettings(conf.getProperties()).build();
//使用实例化好了的注册服务,使用Configuration中的工厂模式实例化了SessionFactory.
SessionFactory sf = conf.buildSessionFactory(serviceRegistry);

Hibernate5版本中创建 SessionFactory

1
2
3
4
5
6
7
//V5版本不再需要 configure 对象了,直接使用创建者模式构建出了标准服务注册对象
StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().configure().build();
//这个对象 metadata 对象应该扮演了一个万金油的角色,使用以上的注册对象作为入参构建这个对象
Metadata metadata = new MetadataSources(standardRegistry).getMetadataBuilder()
.applyImplicitNamingStrategy(ImplicitNamingStrategyComponentPathImpl.INSTANCE).build();
//最后由这个 metadata 使用构建出 sessionFactory
SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build();

范例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
public class HibernateSessionFactory
{
private static final ThreadLocal<Session> sessionThreadLocal = new ThreadLocal<>();
private static SessionFactory sessionFactory;

static
{
StandardServiceRegistry standardServiceRegistry = new StandardServiceRegistryBuilder().configure().build();
Metadata metadata = new MetadataSources(standardServiceRegistry).getMetadataBuilder().applyImplicitNamingStrategy(ImplicitNamingStrategyComponentPathImpl.INSTANCE).build();
sessionFactory = metadata.getSessionFactoryBuilder().build();
}

public static SessionFactory getSessionFactory()
{
return sessionFactory;
}

//重建SessionFactory
private static void rebuildSessionFactory()
{
synchronized (sessionFactory)
{
StandardServiceRegistry standardServiceRegistry = new StandardServiceRegistryBuilder().configure().build();
Metadata metadata = new MetadataSources(standardServiceRegistry).getMetadataBuilder().applyImplicitNamingStrategy(ImplicitNamingStrategyComponentPathImpl.INSTANCE).build();
sessionFactory = metadata.getSessionFactoryBuilder().build();
}
}

//获得Session对象
public static Session getSession()
{
Session session = sessionThreadLocal.get();
if (session == null || !session.isOpen())
{
if (sessionFactory == null)
{
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession() : null;
sessionThreadLocal.set(session);
}
return session;
}

//关闭Session对象
public static void closeSession()
{
Session session = sessionThreadLocal.get();
sessionThreadLocal.set(null);
if (session != null && session.isOpen())
{
session.close();
}
}

}