在初次开发持久类时,通常是需要如下步骤:
1、开发持久化类,由PO(Persistent Object)=POJO(Plain Ordinary Java Object)+持久化类注解组成
2、获取Configuration实例
Configuration conf=new COnfiguration().configure();
//无参configure()方法默认加载hibernate.cfg.xml文件
3、获取SessionFactory,是数据库编译后的内存镜像
ServiceRegistry serviceRegistry=new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build();
SessionFactory sf=conf.buildSessionFactory(serviceRegistry);
registry:注册、登记
4、获取Session,打开事务
Session sess=sf.openSession();
Transaction tx=sess.beginTransaction();//开始事务
5、用面向对象的方式操作数据库
News n=new News()//创建消息对象
...
sess.save(n);//保存消息
tx.commit();//提交事务
6、关闭事务,关闭Session
sess.close();sf.close();
但以上获取SessionFactory只适用于Hibernate5.x版本以前,对于Hibernate5.x版本,获取方式更为简单
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.configure().build();
SessionFactory sf=new MetadataSources(serviceRegistry).
buildMetadata().buildSessionFactory();
Session sess=sf.openSession();
Transaction tx=sess.beginTransaction();
News n=new News();
sess.save(n);
tx.commit();
sess.close();
sf.close();
所以还是要了解最新的信息,不能只顾视频、教材中的知识呀!