
本站地址:http://www.bajiao123.com

Hibernate 上手篇
Column | Type | Modifiers
--------+-----------------------+-----------
cat_id | character(32) | not null
name | character varying(16) | not null
sex | character(1) |
weight | real |
Indexes: cat_pkey primary key btree (cat_id)
你现在可以在你的数据库中手工创建这个表了,如果你需要使用hbm2ddl工具把这个步骤自动化,请参阅第 21 章 工具箱指南。这个工具能够创建完整的SQL DDL,包括表定义,自定义的字段类型约束,惟一约束和索引。
1.4. 与Cat同乐
我们现在可以开始Hibernate的Session了。它是一个持久化管理器,我们通过它来从数据库中存取Cat。首先,我们要从SessionFactory中获取一个Session(Hibernate的工作单元)。
SessionFactory sessionFactory =
new Configuration().configure().buildSessionFactory();
通过对configure()的调用来装载hibernate.cfg.xml配置文件,并初始化成一个Configuration实例。 在创建 SessionFactory之前(它是不可变的),你可以访问Configuration来设置其他属性(甚至修改映射的元数据)。我们应该在哪儿创建SessionFactory,在我们的程序中又如何访问它呢? SessionFactory通常只是被初始化一次,比如说通过一个load-on-startup servlet的来初始化。这意味着你不应该在serlvet中把它作为一个实例变量来持有,而应该放在其他地方。进一步的说,我们需要使用单例(Singleton)模式,我们才能更容易的在程序中访问SessionFactory。下面的方法就同时解决了两个问题:对SessionFactory的初始配置与便捷使用。
我们实现一个HibernateUtil辅助类:
import org.hibernate.*;
import org.hibernate.cfg.*;
public class HibernateUtil {
private static Log log = LogFactory.getLog(HibernateUtil.class);
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
log.error("Initial SessionFactory creation failed.", ex);
throw new ExceptionInInitializerError(ex);
}
}
public static final ThreadLocal session = new ThreadLocal();
public static Session currentSession() {
Session s = (Session) session.get();
// Open a new Session, if this Thread has none yet
if (s == null) {
上一页 [1] [2] [3] [4] [5] [6] [7] 下一页
本站地址:http://www.bajiao123.com

