方法中的常见参数传递

时间:2016-06-16 07:26:51

标签: java hibernate methods

我的DAO类中有一个名为makePersistent的方法。 我们在所有dao类中都有这个方法,我需要做的是将此方法转换为通用格式。那有什么办法吗?

UserDao类中的方法

public void makePersistent(User model) throws InfrastructureException {
        try {
            getSession().saveOrUpdate(model);
            getSession().flush();
            getSession().clear();
        } catch (org.hibernate.StaleObjectStateException ex) {
            throw new InfrastructureException(Labels.getString("com.tran.msg.objectDeletedOrUpdated"));
        } catch (HibernateException ex) {
            throw new InfrastructureException(ex);
        }
    }

HolidayDao类中的方法

public void makePersistent(Holiday model) throws InfrastructureException {
        try {
            getSession().saveOrUpdate(model);
            getSession().flush();
            getSession().clear();
        } catch (org.hibernate.StaleObjectStateException ex) {
            throw new InfrastructureException(Labels.getString("com.tran.msg.objectDeletedOrUpdated"));
        } catch (HibernateException ex) {
            throw new InfrastructureException(ex);
        }
    }

请帮我摆脱这种冗余编码。 谢谢。

2 个答案:

答案 0 :(得分:2)

Just use Object the hibernate will persist it.


public void makePersistent(Object model) throws InfrastructureException {
         try {
            getSession().saveOrUpdate(model);
            getSession().flush();
            getSession().clear();
        } catch (org.hibernate.StaleObjectStateException ex) {
            throw new InfrastructureException(Labels.getString("com.tran.msg.objectDeletedOrUpdaed"));
        } catch (HibernateException ex) {
            throw new InfrastructureException(ex);
        }
    }

答案 1 :(得分:1)

使用类型参数为DAO创建超类,并使DAO类使用适当的类型参数扩展该超类。例如:

public class BaseDao<T> {

    public void makePersistent(T model) throws InfrastructureException {
        try {
            getSession().saveOrUpdate(model);
            getSession().flush();
            getSession().clear();
        } catch (org.hibernate.StaleObjectStateException ex) {
            throw new InfrastructureException(Labels.getString("com.tran.msg.objectDeletedOrUpdated"));
        } catch (HibernateException ex) {
            throw new InfrastructureException(ex);
        }
    }
}

public class UserDao extends BaseDao<User> {
    // ...
}

public class HolidayDao extends BaseDao<Holiday> {
    // ...
}

UserDaoHolidayDao继承了makePersistent中的BaseDao方法,因此您无需在每个DAO类中再次实现它。