在我的项目中,我使用 Hibernate 进行编程事务划分。
每次在我的服务方法中我都会写类似的东西。
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
.. perform operation here
session.getTransaction().commit();
现在我将使用声明性事务管理来重构我的代码。我现在得到的...
<context:component-scan base-package="package.*"/>
<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
</bean>
<tx:annotation-driven transaction-manager="txManager"/>
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="mySessionFactory"/>
</property>
</bean>
服务等级:
@Service
public class TransactionalService {
@Autowired
private SessionFactory factory;
@Transactional
public User performSimpleOperation() {
return (User)factory.getCurrentSession().load(User.class, 1L);
}
}
和简单的测试 -
@Test
public void useDeclarativeDem() {
FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext("spring-config.xml");
TransactionalService b = (TransactionalService)ctx.getBean("transactionalService");
User op = b.performSimpleOperation();
op.getEmail();
当我尝试在事务方法之外获取用户电子邮件时,出现延迟初始化异常,电子邮件是我的情况是一个简单的字符串。 Hibernate 甚至不执行 sql 查询,直到我在 POJO 上调用任何 getter。
-
我在这里做错了什么?
-
这种方法有效吗?
-
您能建议任何在 spring/hibernate 上使用基于注释的配置的开源项目吗?
Update
由于某种原因如果我更换获取当前会话 with 开放会话这段代码工作正常。有人可以解释一下吗?