创建一个可以处理所有类型的CRUD操作的类。每次我需要做CRUD时都不需要创建SessionFactory或Session对象

时间:2016-02-12 10:54:36

标签: java hibernate enums

我想在java中创建一个可以与Hibernate配置交互的方法,并将某些操作识别为ENUM(例如:读取,更新,添加,删除等)

方法参数应该是(枚举操作,类DTO,NamedQuery namedquery,DTOObject Object_to_persist,param(任何额外参数))。

方法应该是方便的,我可以随时通过传递实际参数(Operation.read,USERDTO.class,namedquery,USERDTO obj_UserDTO,HashMap hmapData)来调用它。

  /* Enum Defined Operation done to the database.
   */ 
     public enum Operations {READ,UPDATE,ADD,DELETE};

      /*Centralized Method Defination for Basic CRUD Operation */
public T<?> DatabaseCRUDOperations((Operation.READ,USERDTO.class , namedquery , USERDTO obj_UserDTO , HashMap<String, String> hmapid){
     switch(Operation opts){
             case Operation.Read : //Call Read Method
               break;

             case Operation.UPDATE: //call Update Method
               break;
                ......
                ......
              default://call any Error Method or set error
        }
   }

基本上我想定义一个自定义类(一种项目的内部框架),其中所有基本的CRUD操作都应该只通过这个类完成。无需创建SessionFactory或Session Object创建我需要的每个地方。 请通过一些code-snipt建议。

1 个答案:

答案 0 :(得分:2)

Java Generics to the rescue! Prepare to be amazed.

Your abstract entity (useful if you want to define methods to use in things like, for example, generic controller classes):

appearence

Create the generic DAO interface:

public abstract class AbstractEntity<ID extends Serializable> implements Serializable {

    public abstract ID getPrimaryKey();//I simply put this here as an example
}

Then, define your abstract generic DAO:

public interface IGenericDAO<T extends AbstractEntity<ID>, ID extends Serializable> {
    T findByPrimaryKey(ID id);

    T save(T entity);

    void delete(T entity);

    List<T> saveAll(List<T> entities);
    .
    .
    .
}

DAO interface for entity (For this example, I'm using Integer as the primary key):

public abstract class AbstractHibernateDAO<T extends AbstractEntity<ID>, ID extends Serializable> implements IGenericDAO<T, ID> {
    protected Class<T> persistentClass;

    protected AbstractHibernateDAO(){}
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public AbstractHibernateDAO(Class c) {
        persistentClass = c;
    }

    @Override
    @SuppressWarnings("unchecked")
    public T findByPrimaryKey(ID id){
        return (T) HibernateUtil.getSession().get(persistentClass, id);
    }


    @Override
    public T save(T entity){
        HibernateUtil.getSession().saveOrUpdate(entity);
        return entity;
    }

    @Override
    public List<T> saveAll(List<T> entities){
        for(int i = 0; i < entities.size(); i++){
            HibernateUtil.getSession().saveOrUpdate(entities.get(i));
        }
        return entities;
    }

    @Override
    public void delete(T entity){
        HibernateUtil.getSession().delete(entity);
    }
    .
    .
    .
}

Now (drum roll), you are ready to lay some concrete (classes)...

DAO:

public interface IMyEntityDAO extends IGenericDAO<MyEntity, Integer> {
}

MyEntity:

public class MyEntityDAO extends AbstractHibernateDAO<MyEntity, Integer> implements IMyEntityDAO {
    public MyEntityDAO() {
        super(MyEntity.class);
    }
}

Boom. (Mic drop)

Let me know if you need further explanation!

I can't rightfully post this without giving credit to Cameron McKenzie and his amazing book here . Which opened my eyes to a whole new world realizing the power of generics.