我正在使用Hiberante 5和Spring 4.2.3。我找不到将eventListener添加到SessionFactory范围的方法。我只需要在hibernate持久化对象之前设置一个日期。我在spring.xml中定义了sessionFactory
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>com/hibernate/mapping/User.hbm.xml</value>
<value>com/hibernate/mapping/PublicKey.hbm.xml</value>
<value>com/hibernate/mapping/File.hbm.xml</value>
<value>com/hibernate/mapping/Url.hbm.xml</value>
<value>com/hibernate/mapping/Role.hbm.xml</value>
<value>com/hibernate/mapping/Operation.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">validate</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>
<prop key="hibernate.c3p0.min_size">5</prop>
<prop key="hibernate.c3p0.max_size">50</prop>
<prop key="hibernate.c3p0.timeout">100</prop>
<prop key="hibernate.c3p0.max_statements">50</prop>
<prop key="hibernate.c3p0.idle_test_period">3000</prop>
<prop key="hibernate.c3p0.validate">true</prop>
</props>
</property>
</bean>
我有我的GenericDAOImpl来获取这个sessionFactory:
public abstract class GenericDAOImpl <T, PK extends Serializable> implements GenericDAO<T, PK> {
private SessionFactory sessionFactory;
/** Domain class the DAO instance will be responsible for */
protected Class<T> type;
@SuppressWarnings("unchecked")
public GenericDAOImpl() {
Type t = getClass().getGenericSuperclass();
ParameterizedType pt = (ParameterizedType) t;
type = (Class<T>) pt.getActualTypeArguments()[0];
}
@SuppressWarnings("unchecked")
public PK create(T o) {
return (PK) getSession().save(o);
}
public T read(PK id) {
return (T) getSession().get(type, id);
}
public void update(T o) {
getSession().update(o);
}
public void delete(T o) {
getSession().delete(o);
}
@SuppressWarnings("unchecked")
public List<T> getAll() {
return getSession().createCriteria(type).list();
}
protected Session getSession() {
return sessionFactory.getCurrentSession();
}
// getters and setters
}
我已经看到了几种方法,但其中一些方法不适用于Hiberante 5(如Integrator
)。而且我找不到通过xml添加这个eventListener的方法,或者只是在sessionFactory范围中添加代码。我找到了如何使用sessionFactory.withOptions().eventListeners(listeners);
谢谢!
答案 0 :(得分:1)
最后,它很容易,我找到了一种方法来添加通过xml拦截器,只需添加:
<property name="entityInterceptor">
<bean class="com.xxx.xxx.className"></bean>
</property>
我在帖子中发现了这个: Hibernate Interceptor Not Working