1.11 hibernate的核心借口(configuration,sessionFactory,edc)

public class HibernateCoreAPITest {
private static SessionFactory sessionFactory;

@BeforeClass
public static void beforeClass() {
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
}
@AfterClass
public static void afterClass() {
sessionFactory.close();
}



@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);


}

解析:

1.new AnnotationConfiguration().configure()是用来读hibernate.cfg.xml文件配置信息的。如果没有找到hibernate.cfg.xml文件,就会报错。

2.sessionfactory是用来生成连接的

sessionFactory.openSession();是用来生成新的连接的

sessionFactory.getCurrentSession();是用来打开当前连接的,在当前session没有提交之前,无论拿多少session,都是同一个session;如果当前没有连接,就新打开一个连接。

currentsession最大用处:例如保存一个user,同时保存事务日志,这两件事必须在同一个事物里面,在事务没有提交前,保持同一个session,才能确保这两件事在同一个事务里面。

3.hibernate配置文件中有一个条

<property name="current_session_context_class">thread</property>

current_session_context_class属性的取值有jta,thread,managed,custom class

该属性定义currentsession查找的范围,thread是在线程里面找;managed和custom class用的很少;jta等学了分布式处理后再了解。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值