hibernate的session判断-openSession和getCurrentSession

简介:

1.openSession永远打开新的session(打开新的)

2.getCurrentSession,如果当前环境已经有session则用当前session(可能打开新的也可能用以前已经存在的


代码判断:

@Test
	public void testTeacherSave() {
	
		Teacher t = new Teacher();
		
		t.setName("t1");
		t.setTitle("middle");
		t.setBirthDate(new Date());
		
		Session session = sessionFactory.openSession();
		
		session.beginTransaction();
		session.save(t);
        session.getTransaction().commit();
		session.close();
		
		Session session2 = sessionFactory.openSession();
		System.out.println(session == session2);
	}
		

输出:

false


再如:

@Test
	public void testTeacherSave() {
	
		Teacher t = new Teacher();
		
		t.setName("t1");
		t.setTitle("middle");
		t.setBirthDate(new Date());
		
		//Session session = sessionFactory.openSession();
		Session session = sessionFactory.getCurrentSession();
		
		session.beginTransaction();
		session.save(t);
		
		Session session2 = sessionFactory.getCurrentSession();
		
		System.out.println(session == session2);
		
		session.getTransaction().commit();
		
		Session session3 = sessionFactory.getCurrentSession();
		
		System.out.println(session == session3);
		
		
	}

输出:

true
false


一个关于openSession和getCurrentSession的分析:


DAO: DATA ACESS OBJECT


如上图所示:userDAO和logDAO都会调用hibernate的sessionsave()方法


问题:这两个操作能否放在同一事务里?

事务:要么这两个操作同时完成,要么一个都不完成。事务的英文:transaction

userDAO和logDAO需要放在同一事务里,所以同时使用opensession()有问题。

事务边界应该放在addUser()里,所以需要用getCurrentSession。



openSession和getCurrentSession不能混用!这两种方法获得的session不是同一个!





目录
相关文章
|
1月前
|
缓存 安全 Java
|
1月前
|
缓存 安全 Java
Hibernate 中的 Session 是线程安全的吗?
【8月更文挑战第21天】
22 0
|
1月前
|
缓存 安全 Java
Hibernate 中的 Session 是什么?
【8月更文挑战第21天】
12 0
|
4月前
|
SQL 缓存 Java
Hibernate - Session管理与批量数据处理详解
Hibernate - Session管理与批量数据处理详解
68 0
|
4月前
|
存储 缓存 Java
Hibernate - Session方法与持久化对象详解
Hibernate - Session方法与持久化对象详解
117 0
|
4月前
|
SQL 缓存 Java
Hibernate - SessionFactory和Session详解
Hibernate - SessionFactory和Session详解
88 0
|
SQL Java 数据库连接
Hibernate中的Session对象
Hibernate中的Session对象
72 0
|
关系型数据库 MySQL Java
Could not open Hibernate Session for transaction; nested exception is org.hibernate.TransactionExcep linux下mysql修改连接超时wait_timeout修改后就ok了
Could not open Hibernate Session for transaction; nested exception is org.hibernate.TransactionExcep linux下mysql修改连接超时wait_timeout修改后就ok了
168 1
|
XML 存储 SQL
问:hibernate的sessionfactory是干嘛的?session又是干嘛的呢?
问:hibernate的sessionfactory是干嘛的?session又是干嘛的呢?
92 1
hibernate4 could not initialize proxy - no Session
hibernate4 could not initialize proxy - no Session