java中hibernate获取Session实例写法

作者:袖梨 2022-11-14

以前的SessionFactory sf = conf.buildSessionFactory();被IDE建议不要继续使用,现在hibernate获取session的方法最好是使用:

代码如下 复制代码

package org.Rudiment.hibernate;

import org.Rudiment.hibernate.News;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class NewsManager
{
public static void main(String[] args)
{
//获取配置
Configuration conf = new Configuration().configure();
//获取ServiceRegistry
ServiceRegistry sr = new ServiceRegistryBuilder()
.applySettings(conf.getProperties())
.buildServiceRegistry();
//配置我们的SessionFactory
SessionFactory sf = conf.buildSessionFactory(sr);
//获取我们的Session
Session sess = sf.openSession();
//开始我们的事务
Transaction tx = sess.beginTransaction();

News n = new News();
n.setTitle("ITkezhan");
n.setContent("IT客栈");

//保存持久化对象
sess.save(n);
//提交事务
tx.commit();
//关闭Session
sess.close();
//关闭SessionFactory
sf.close();
}
}

相关文章

精彩推荐