繁体   English   中英

方法中的常见参数传递

[英]Common Argument Pass in Method

我的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);
        }
    }

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

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);
        }
    }

使用类型参数为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> {
    // ...
}

UserDaoHolidayDaoBaseDao继承makePersistent方法,因此您不必在每个DAO类中再次实现它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM