我无法打开 Hibernate 事务。
这是配置:
<context:annotation-config />
<context:component-scan base-package="com.cinebot" />
<mvc:annotation-driven />
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>com.cinebot.db.entity</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven />
这是错误的代码:
@Transactional
public static <T> T get(Class<T> classe, Serializable id) throws Exception {
if(id==null) return null;
T obj = (T) HibernateUtil.getSessionFactory().getCurrentSession().get(classe, id);
return obj;
}
这是一个例外:
org.hibernate.HibernateException: get is not valid without active transaction
这是一个示例实体:
package com.cinebot.db.entity;
// Generated 3-lug-2012 10.31.04 by Hibernate Tools 3.4.0.CR1
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Dettagli generated by hbm2java
*/
@Entity
@Table(name = "dettagli", catalog = "cinebot")
public class Dettagli implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private String nome;
private String valore;
public Dettagli() {
}
public Dettagli(String nome) {
this.nome = nome;
}
public Dettagli(String nome, String valore) {
this.nome = nome;
this.valore = valore;
}
@Id
@Column(name = "nome", unique = true, nullable = false, length = 32)
public String getNome() {
return this.nome;
}
public void setNome(String nome) {
this.nome = nome;
}
@Column(name = "valore", length = 65535)
public String getValore() {
return this.valore;
}
public void setValore(String valore) {
this.valore = valore;
}
}
我不明白为什么 @Transactional 注释不足以自动打开事务。我错过了什么?
谢谢