Lasitha Benaragama
Lasitha Benaragama

Reputation: 2209

Common Argument Pass in Method

I have a method called makePersistent in my DAO class. Currntly we have this method in all dao classes and what i need to do is convert this method to common format. So is there any way to do it?

Method in UserDao Class

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

Method in HolidayDao Class

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

Please help me to get rid of this redundant coding. Thank you.

Upvotes: 3

Views: 51

Answers (2)

inesh hettiarachchi
inesh hettiarachchi

Reputation: 64

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

Upvotes: 2

Jesper
Jesper

Reputation: 206786

Create a superclass for your DAOs with a type parameter and make your DAO classes extend that superclass with the appropriate type argument. For example:

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> {
    // ...
}

UserDao and HolidayDao inherit the makePersistent method from BaseDao, so you don't have to implement it again in every DAO class.

Upvotes: 1

Related Questions