4
我使用Hiberante 5和Spring 4.2.3。我沒有找到將EventListener添加到SessionFactory範圍的方法。我只需要在hibernate持久化一個對象之前設置一個日期。我已經在SessionFactory的spring.xmlEventListener休眠5
<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);
謝謝!
您是否嘗試過用攔截器? http://docs.jboss.org/hibernate/core/3.3/reference/en/html/events.html –
@ MarcoA.Hernandez我在eventListener之前嘗試這種可能性,但我沒有找到添加攔截器的方法SessionFactory通過xml。我知道使用代碼就像'new Configuration()。setInterceptor(new AuditInterceptor())'一樣簡單。但我已經在xml中定義了我的sessionFactory。 – angeldev
從來沒有嘗試過,但我想你可以創建一個擴展org.springframework.orm.hibernate5.LocalSessionFactoryBean的類,在構造函數中添加Configuration().setInterceptor(...),然後在xml配置文件中使用它。 –