休眠中的PreInsert和PreUpdate事件侦听器 [英] PreInsert and PreUpdate Event Listener in hibernate

查看:98
本文介绍了休眠中的PreInsert和PreUpdate事件侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已使用PreInsertEventListenerPreUpdateEventListener事件监听器在表中插入创建日期和更新日期.
我面临的问题是,当我将实体保存在数据库中的创建日期无法与在更新记录时插入更新日期相同的表中插入时,它也不会插入更新日期.

I have used PreInsertEventListener and PreUpdateEventListener Event Listener to insert created date and updated date in table.
The problem i am facing is that when i save entity in database created date could not be inserted in table same as with insert updated date at the time of update record it will not insert updated date also.

我的代码示例如下所示:

My code sample is show as below :

侦听器类:

public class PreInsertListener implements PreInsertEventListener,  
                                          PreUpdateEventListener 
{
    @Override
    public boolean onPreInsert(PreInsertEvent arg0) {
        City.class.cast(arg0.getEntity()).setCreated_date(new Date());
        return false;
    }

    @Override
    public boolean onPreUpdate(PreUpdateEvent arg0) {
        System.out.println("Update event......");
        City.class.cast(arg0.getEntity()).setUpdated_date(new Date());
        return false;
    }
}

休眠连接类:

public class HibernateUtil 
{

    private static final SessionFactory sessionFactory;

    static {
        try {
            AnnotationConfiguration config = new AnnotationConfiguration();
            config.setListener("pre-insert", new PreInsertListener());
            config.setListener("pre-update", new PreInsertListener());
            sessionFactory = config.configure().buildSessionFactory();;

        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

DAO中的实体保存和更新方法:

Entity save and Update method in DAO :

public Long saveCity(String cityName)
{
    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction transaction = null;
    Long cityId = null;
    try {
        transaction = session.beginTransaction();
        City city = new City();
        city.setName(cityName);
        cityId = (Long) session.save(city);
        //session.flush();
        transaction.commit();
    } catch (HibernateException e) {
        transaction.rollback();
        e.printStackTrace();
    } finally {
        session.close();
    }
    return cityId;
}

public void updateCity(Long cityId, String cityName)
{
    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction transaction = null;
    try {
        transaction = session.beginTransaction();
        City city = (City) session.get(City.class, cityId);
        city.setName(cityName);
        session.update(city);
        //session.flush();
        transaction.commit();
    } catch (HibernateException e) {
        transaction.rollback();
        e.printStackTrace();
    } finally {
        session.close();
    }
}

我的测试班:

public class Main 
{
    public static void main(String[] args) {

        CityDAO cityDAO = new CityDAO();

        long cityId1 = cityDAO.saveCity("New York");

        cityDAO.updateCity(cityId1, "Paris");
    }
 }

如果我使用session.flush(),它将插入创建和更新的日期,但是每次我调用flush方法时都会执行更新的查询.目前,我已注释代码以调用session.flush()方法,如代码所示.

If i used session.flush() than it will insert both date created and updated but updated query is executed every time i call flush method. currently i commented code to call session.flush() method as show in code.

该问题的解决方案是什么?

What is the solution to this problem ?

推荐答案

我创建了Interceptor,并使用Hibernate EmptyInterceptor对其进行了扩展.
覆盖方法onSave(),该方法将在您保存对象时调用,该对象尚未保存到数据库中,而onFlushDirty()在更新对象时被调用,该对象尚未更新到数据库中. 在此功能中,我已通过其名称检查方法,其中必须在创建或更新时设置日期.
这是onFlushDirty()方法的示例代码.

I had created Interceptor extend it with Hibernate EmptyInterceptor.
Override method onSave() which will be Called when you save an object, the object is not save into database yet and onFlushDirty() Called when you update an object, the object is not update into database yet.
In this function i have check my method by its name in which i have to set date at the time of created or updated.
Here is sample code of onFlushDirty() method.

public boolean onFlushDirty(Object entity,Serializable id,Object[] currentState, 
                  Object[] previousState,String[] propertyNames, Type[] types) 
{

    if ( entity instanceof City ) {

        for ( int i=0; i < propertyNames.length; i++ ) {
            if ( "lastUpdatedOn".equals( propertyNames[i] ) ) {
                currentState[i] = new Date();
                return true;
            }
        }
    }
    return false;
}  

这里lastUpdatedOn是我的方法名称,用于设置更新的记录日期.

Here lastUpdatedOn is my method name which set updated date of record.

onSave()方法:

onSave() method :

public boolean onSave(Object entity, Serializable id, Object[] state,   
                     String[] propertyNames, Type[] types)   
{
    if ( entity instanceof City) {

        for ( int i=0; i<propertyNames.length; i++ ) {
            if ( "createdOn".equals( propertyNames[i] ) ) {
                state[i] = new Date();
                return true;
            }
        }
    }
    return false;
}

此处createdOn是设置记录创建日期的方法.

Here createdOn is method to set created date for record.

使用该拦截器类扩展您的POJO类.

Extend your POJO class with this interceptor class.

这篇关于休眠中的PreInsert和PreUpdate事件侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆