第三章 对象的状态

 current_session_context_class的作用
Hibernate官方原文如下:
The hibernate.current_session_context_class configuration parameter defines which
org.hibernate.context.CurrentSessionContext implementation should be used. Note that for backwards
compatibility, if this config param is not set but a org.hibernate.transaction.TransactionManagerLookup
is configured, Hibernate will use the org.hibernate.context.JTASessionContext. Typically, the value of this
parameter would just name the implementation class to use; for the two out-of-the-box implementations,
however, there are two corresponding short names, "jta" and "thread".
此设置的作用如下:
What does sessionFactory.getCurrentSession() do? First, you can call it
as many times and anywhere you
like, once you get hold of your SessionFactory (easy thanks to
HibernateUtil). The getCurrentSession()
method always returns the "current" unit of work. Remember that we
switched the configuration option for this
mechanism to "thread" in hibernate.cfg.xml? Hence, the scope of the
current unit of work is the current Java
thread that executes our application. However, this is not the full
truth. A Session begins when it is first
needed, when the first call to getCurrentSession() is made. It is then
bound by Hibernate to the current
thread. When the transaction ends, either committed or rolled back,
Hibernate also unbinds the Session from
the thread and closes it for you. If you call getCurrentSession() again,
you get a new Session and can start a
new unit of work. This thread-bound programming model is the most
popular way of using Hibernate.

Hibernate配置:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 设置使用数据库的语言 -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 确定以何种方式产生session-->
<property name="current_session_context_class">thread</property>
<!-- 关闭缓存-->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- 是否自动创建对应的数据库表-->
<!-- property name="hbm2ddl.auto">create</property -->
<!-- 设置是否显示执行的语言 -->
<property name="show_sql">true</property>
<!-- 数据库连接属性设置 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="connection.username">root</property>
<property name="connection.password">wdpc</property>
<!-- 设置 c3p0连接池的属性-->
<property name="connection.useUnicode">true</property>
<property name="hibernate.c3p0.max_statements">100</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<property name="hibernate.c3p0.acquire_increment">2</property>
<property name="hibernate.c3p0.timeout">5000</property>
<property name="hibernate.connection.provider_class">
org.hibernate.connection.C3P0ConnectionProvider
</property>
<property name="hibernate.c3p0.validate">true</property>
<property name="hibernate.c3p0.max_size">3</property>
<property name="hibernate.c3p0.min_size">1</property>

<!-- 加载映射文件-->
<mapping resource="chapter2/model/Student.hbm.xml" />
</session-factory>
</hibernate-configuration>

-------------------------------------------------
sessionFactory.getCurrentSession()可以完成一系列的工作,当调用时,
hibernate将session绑定到当前线程,事务结束后,hibernate
将session从当前线程中释放,并且关闭session。当再次调用getCurrentSession
()时,将得到一个新的session,并重新开始这一系列工作。
这样调用方法如下:

Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Event theEvent = new Event();
theEvent.setTitle(title);
theEvent.setDate(theDate);
session.save(theEvent);
session.getTransaction().commit();
不需要close session了。

以前的老版本中以及一些视频中是怎么样获取session的呢?
请看下面MyEclipse生成的代码中:
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession(): null;
threadLocal.set(session);
}
return session;
}
可以看到是通过sessionFactory.openSession()方法来生成的session对象,那么这两种有什么区别呢?

 getCurrentSession和openSession的区别
1 getCurrentSession创建的session会和绑定到当前线程,而openSession不会。
2 getCurrentSession创建的线程会在事务回滚或事物提交后自动关闭,而openSession必须手动关闭
3 sessionFactory.getCurrentSession()方法取得的session,在做数据库操作时必须在事务中做,包括只读的查询,否则会报错。

 对象的三种状态
瞬时:刚new 出来的对象, 与session没有关系
持久: 在session事务开始与事务提交之间的对象,在这之间对象的属性做任何动作,Hibernate都会检测到,从而影响数据库中的结果.
脱管:事务提交之后的对象, 对属性做任何动作, Hibernate不会检测到.
public void insertStudent(Student student) {
Session session = HibernateUtil.getSession();
try {
session.beginTransaction();
session.save(student);
student.setName("看这里"); //事务提交之前改变了对象的属性
session.getTransaction().commit();
} catch (Exception e) {
session.getTransaction().rollback();
}
}
public static void main(String[] args) throws ParseException {
StudentDao sd = new StudentDao();
// 方式一:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse("1988-10-22");
Student student1 = new Student("张三", 22, new java.sql.Date(date
.getTime()));
sd.insertStudent(student1);

// 方式二:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 1988);
calendar.set(Calendar.MONTH, 0);
calendar.set(Calendar.DAY_OF_MONTH, 21);
Student student2 = new Student("李四", 22, new java.sql.Date(calendar
.getTimeInMillis()));

sd.insertStudent(student2);
}
可以看到数据库中执行了四条SQL语句,两条insert, 两条update,可以看到数据库中最后入库是”看这里”

Hibernate Dao层的抽取.
在HibernateUitl类中添加静态方法的方式,可以将工具类变的功能更强大:
public static void insert(Object obj) {
Session session = HibernateUtil.getSession();
try {
session.beginTransaction();
session.save(obj);
session.getTransaction().commit();
} catch (Exception e) {
session.getTransaction().rollback();
}
}

public static void delete(Object obj) {
Session session = HibernateUtil.getSession();
try {
session.beginTransaction();
session.delete(obj);
session.getTransaction().commit();
} catch (Exception e) {
session.getTransaction().rollback();
}
}

public static void update(Object obj) {
Session session = HibernateUtil.getSession();
try {
session.beginTransaction();
session.update(obj);
session.getTransaction().commit();
} catch (Exception e) {
session.getTransaction().rollback();
}
}

public static <T> Object findById(Class<T> entityClass, Serializable id) {
Session session = HibernateUtil.getSession();
Object obj = null;
try {
session.beginTransaction();
obj = session.get(entityClass,id);
session.getTransaction().commit();
} catch (Exception e) {
session.getTransaction().rollback();
}
return obj;
}
应用:
public static void main(String[] args) throws ParseException {
Student s = null;
s = (Student) HibernateUtil.findById(Student.class,
"40285c812789efdb012789efdcd20001");
System.out.println(s.getName());
s.setName("露芽");
HibernateUtil.update(s);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值