Hibernate:CRUD Generic DAO

时间:2012-03-15 14:05:22

标签: java spring hibernate generics dao

我的网络应用程序有很多服务表/实体,例如payment_methodstax_codesprovince_codes等。

每次添加新实体时,我都要写一个DAO。问题是,基本上,它们都是一样的,但唯一的区别是实体类本身

我知道Hibernate工具可以自动生成代码但我现在不能使用它们(不要问为什么)所以我想的是 Generic DAO 。有很多关于这方面的文献,但我不能把它们放在一起,使它与Spring一起工作。

我认为这是关于泛型的,它将有四种基本方法:

  • listAll
  • saveOrUpdate
  • deleteById
  • getById

就是这样。


问题:

没有重新发明轮子的最佳实践是什么?是不是有东西可以使用呢?

5 个答案:

答案 0 :(得分:41)

这是我的

@Component
public class Dao{

    @Resource(name = "sessionFactory")
    private SessionFactory sessionFactory;

    public <T> T save(final T o){
      return (T) sessionFactory.getCurrentSession().save(o);
    }


    public void delete(final Object object){
      sessionFactory.getCurrentSession().delete(object);
    }

    /***/
    public <T> T get(final Class<T> type, final Long id){
      return (T) sessionFactory.getCurrentSession().get(type, id);
    }

    /***/
    public <T> T merge(final T o)   {
      return (T) sessionFactory.getCurrentSession().merge(o);
    }

    /***/
    public <T> void saveOrUpdate(final T o){
      sessionFactory.getCurrentSession().saveOrUpdate(o);
    }

    public <T> List<T> getAll(final Class<T> type) {
      final Session session = sessionFactory.getCurrentSession();
      final Criteria crit = session.createCriteria(type);
  return crit.list();
    }
// and so on, you shoudl get the idea

然后您可以在服务层中进行访问:

 @Autowired
    private Dao dao;

   @Transactional(readOnly = true)
    public List<MyEntity> getAll() {
      return dao.getAll(MyEntity.class);
    }

答案 1 :(得分:25)

Spring Data JPA是一个很棒的项目,可以为您生成DAO等等!您只需要创建一个接口(没有任何实现):

interface PaymentMethodsDao extends JpaRepository<PaymentMethods, Integer> {}

此界面(通过继承的JpaRepository)将自动为您提供:

PaymentMethod save(PaymentMethod entity);
Iterable<PaymentMethod> save(Iterable<? extends PaymentMethod> entities);
PaymentMethod findOne(Integer id);
boolean exists(Integer id);
Iterable<PaymentMethod> findAll();
long count();
void delete(Integer id);
void delete(PaymentMethod entity);
void delete(Iterable<? extends PaymentMethod> entities);
void deleteAll();
Iterable<PaymentMethod> findAll(Sort sort);
Page<PaymentMethod> findAll(Pageable pageable);
List<PaymentMethod> findAll();
List<PaymentMethod> findAll(Sort sort);
List<PaymentMethod> save(Iterable<? extends PaymentMethods> entities);
void flush();
PaymentMethod saveAndFlush(PaymentMethods entity);
void deleteInBatch(Iterable<PaymentMethods> entities);

界面是强类型(泛型)并自动为您实现。对于每个实体,您所要做的就是创建一个扩展JpaRepository<T,Integer extends Serializable>的接口。

但等等,还有更多!假设您的PaymentMethodnamevalidSince个持久字段。如果您将以下方法添加到您的界面:

interface PaymentMethodsDao extends JpaRepository<PaymentMethods, Integer> {

  Page<PaymentMethod> findByNameLikeAndValidSinceGreaterThan(
    String name, Date validSince, Pageable page
  );

}

框架将解析方法名称:

findBy名称之类)And ValidSince 大于)

创建JPA QL查询,应用分页和排序(Pageable page)并为您运行它。无需实施:

paymentMethodsDao.findByNameLikeAndValidSinceGreaterThan(
  "abc%",
  new Date(),
  new PageRequest(0, 20, Sort.Direction.DESC, "name"
);

结果查询:

SELECT *  //or COUNT, framework also returns the total number of records
FROM PaymentMethods
WHERE name LIKE "abc%"
  AND validSince > ...

并应用了分页。

唯一的缺点是该项目相当新,并且相对容易击中但是(但它非常积极地开发)。

答案 2 :(得分:4)

不要为每个实体编写特定的dao。您可以实现一个通用DAO,它可以为您需要的所有实体执行90%的工作。如果您想要特定处理某些实体,可以扩展它。

在我目前正在开发的项目中,我们有这样的DAO,它包含Hibernate会话,提供类似于你描述的方法。此外,我们正在使用ISearch API - 一个托管在Google代码中的开源项目,为Hibernate和JPA提供了非常方便的标准构建接口。

答案 3 :(得分:4)

您可以使用Generic DAO作为其他Domain特定DAO类的杠杆。假设您有一个Employee Domain类:

  @Entity
  @Table(name="employee")
  public class Employee {

    @Id
    @Column(name="id")
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;

    @Column(name="emp_name")
    private String empName;

    @Column(name="emp_designation")
    private String empDesignation;

    @Column(name="emp_salary")
    private Float empSalary;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getEmpName() {
        return empName;
    }

    public void setEmpName(String empName) {
        this.empName = empName;
    }

    public String getEmpDesignation() {
        return empDesignation;
    }

    public void setEmpDesignation(String empDesignation) {
        this.empDesignation = empDesignation;
    }

    public Float getEmpSalary() {
        return empSalary;
    }

    public void setEmpSalary(Float empSalary) {
        this.empSalary = empSalary;
    }


}

然后所需的通用DAO看起来像这样:

通用DAO接口:

 public interface GenericRepositoryInterface<T> {

    public T save(T emp);
    public Boolean delete(T emp);
    public T edit(T emp);
    public T find(Long empId);
}

通用DAO实施:

@Repository
public class GenericRepositoryImplementation<T> implements GenericRepositoryInterface<T> {

protected EntityManager entityManager;
private Class<T> type;

public GenericRepositoryImplementation() {
    // TODO Auto-generated constructor stub

}

public GenericRepositoryImplementation(Class<T> type) {
    // TODO Auto-generated constructor stub

    this.type = type;
}

public EntityManager getEntityManager() {
    return entityManager;
}

@PersistenceContext
public void setEntityManager(EntityManager entityManager) {
    this.entityManager = entityManager;
}
@Override
public T save(T emp) {
    // TODO Auto-generated method stub
    entityManager.persist(emp);
    entityManager.flush();
    return emp;
}

@Override
public Boolean delete(T emp) {
    // TODO Auto-generated method stub
    try {
         entityManager.remove(emp);
    } catch (Exception ex) {
        return false;
    }
    return true;
}

@Override
public T edit(T emp) {
    // TODO Auto-generated method stub
    try{
       return entityManager.merge(emp);
    } catch(Exception ex) {
        return null;
    }
}

@Override
public T find(Long empId) {
    // TODO Auto-generated method stub
    return (T) entityManager.find(Employee.class, empId);
}
} 

然后,需要通过每个特定于域的DAO类来扩展此通用DAO类。特定于域的DAO类甚至可以为通常不常见的操作实现另一个接口。并且更喜欢使用构造函数发送类型信息。

答案 4 :(得分:1)

您可以创建baseDAO接口和baseDAO实现类。 当您需要具有不同类类型的特定用例时,您可以创建该类的DAO,该DAO继承baseDAO类并实现具有该类特定需求的额外接口,如此

<强> IBaseDAO

 public interface IBaseDAO<T> {

/**
 * @Purpose :Save object of type T
 * @param transientInstance
 */
public Object persist(final T transientInstance);

/**
 * @Purpose :Delete object of type T
 * @param persistentInstance
 */
public void remove(final T persistentInstance);

/**
 * @Purpose :Update Object of type T
 * @param detachedInstance
 * @return
 */
public T merge(final T detachedInstance);

/**
 * @Purpose :Find object by 'id' of type T
 * @param identifier
 * @return
 */
public T findById(final Long identifier, Class<?> persistClass);
}

BaseDAO类

public class BaseDAO<T> implements IBaseDAO<T> {

@Autowired
private SessionFactory sessionFactory;

public Object persist(T entity) {
    return this.getSession().save(entity);
}

@Override
public void remove(T persistentInstance) {
    this.getSession().delete(persistentInstance);
}

@SuppressWarnings("unchecked")
@Override
public T merge(T detachedInstance) {
    return (T) this.getSession().merge(detachedInstance);
}

@SuppressWarnings("unchecked")
@Override
public T findById(Long identifier, Class<?> persistClass) {
    return (T) this.getSession().get(persistClass, identifier);
}

public SessionFactory getSessionFactory() {
    return sessionFactory;
}

public Session getSession() {
    return getSessionFactory().getCurrentSession();
}

}

和特定界面

public interface IUserDAO extends IBaseDAO<User> {

   public User getUserById(long userId);

   public User findUserByUsername(String username);

}

和这样的课程

@Repository("userDAO")
public class UserDAO extends BaseDAO<User> implements IUserDAO {

public User getUserById(long userId) {
    return findById(userId, User.class);
}

@Override
    public User findUserByUsername(String username) {
        Criteria criteria = getSession().createCriteria(User.class);
        criteria.add(Restrictions.eq("username", username));
        return (User) criteria.uniqueResult();
    }

}
相关问题