Hibernate-day01-helloworld

一、准备Hibernate环境

Hibernate必须的jar包在D:\develop\OpenSource\Hibernate\hibernate-release-4.2.4.Final\lib\required目录下

二、开发步骤

1.创建Hibernate配置文件

2.创建持久化类(在这里是一个JavaBean)

3.创建对象-关系映射文件

在Hibernate配置文件中加上:

4.通过HibernateAPI访问数据库的代码

步骤:

  1)创建一个SessionFactory对象

  2)创建一个Session对象

  3)开启事务

  4)执行保存操作

  5)提交事务

  6)关闭Session

  7)关闭SessionFactory

@Test
public void test() {

// 1.创建一个SessionFactory对象
SessionFactory sessionFactory = null;
// 1)创建一个Configuration对象:对应Hibernate的基本配置信息和对象关系映射信息
Configuration configuration = new Configuration().configure();

注:关于configure()方法

// 4.0之前这样做
// sessionFactory = configuration.buildSessionFactory();

// 2)创建一个ServiceRegistry对象:4.x新添加的对象
// hibernate的任何配置和服务都需要在该对象中注册后才有效
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
.applySettings(configuration.getProperties()).buildServiceRegistry();

sessionFactory = configuration.buildSessionFactory(serviceRegistry);

// 2.创建一个Session对象
Session session = sessionFactory.openSession();

// 3.开启事务
Transaction transaction = session.beginTransaction();

// 4.执行保存操作
NEWS news = new NEWS("java", "hackerxiehao", new Date(new java.util.Date().getTime()));
session.save(news);

// 5.提交事务
transaction.commit();

// 6.关闭Session
session.close();

// 7.关闭SessionFactory对象
sessionFactory.close();

}

 

posted @ 2017-09-20 23:20  HackerXieHao  阅读(82)  评论(0编辑  收藏  举报