Hibernate入门----核心API

hibernate 核心API
Configuration
Configuration : 封装Hibernate系统配置信息的对象
使用hibernate.cfg.xml加载配置:

/**
 * Configuration().configure(); ,默认读取classpath下hibernate.cfg.xml文件 
 * Configuration().configure(“配置文件名”); 不常用  /config/ hibernate.cfg.xml  加载
 */
Configuration conf = new Configuration().configure();

资源文件配置方式:
添加配置文件(常用)

<mapping resource="包名/UserModel.hbm.xml"/>

添加持久化类.(需要基于注解)

<mapping class="包名.UserModel"/>

2.使用hibernate.properties加载配置, 这种方法无法自动加载配置资源文件(现在几乎不用,老版本使用)

Configuration conf = new Configuration ();

资源文件添加方式:

添加配置文件

conf. addResource(“XXX/UserModel.hbm.xml”);

添加持久化类

自动读取类所在目录下同名配置文件UserModel.hbm.xml,配置文件命名要保持两个文件名一致

conf.addClass(UserModel.class);

SessionFactory
SessionFactory对象根据Configuration对象加载的配置信息创建得到,其中封装了配置信息中有关数据库的信息、所有的映射关系及预定义SQL语句.

Configuration conf = new Configuration().configure();
SessionFactory sf = conf.buildSessionFactory();

由于SessionFactory对象的创建需要基于所有的配置信息,因此创建此对象需要消耗大量的资源,通常一个应用程序中只初始化一个SessionFactory对象

Session
Session对象是Hibernate与应用程序进行交互的桥梁,应用程序与Hibernate之间通过Session进行数据交互,其功能相当于JDBC中的Connection.

Configuration conf = new Configuration().configure();
 SessionFactory sf = conf.buildSessionFactory();
 Session s = sf.openSession();
 ... 逻辑代码
 s.colse();

Transaction
开启事务

Transaction t = s.beginTransaction();

提交事务

t.commit();

回滚事务

t.rollback();

形如:

try {
t.commit();
} catch (Exception e) { // 抛异常则回滚
t.rollback();
} finally { // 关闭session
session.close();
}

猜你喜欢

转载自blog.51cto.com/13587708/2117366
今日推荐