博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Hibernate] - Generic Dao
阅读量:4322 次
发布时间:2019-06-06

本文共 7901 字,大约阅读时间需要 26 分钟。

使用泛型写了一个通用的Hibernate DAO类。

 


GenericDao接口

package com.my.dao;import java.io.Serializable;import java.util.List;/** * Generic DAO interface * @author Robin * * @param 
* @param
*/public interface GenericDao
{ /** * Create entity * @param entity */ void create(T entity); /** * Update entity * @param entity */ void update(T entity); /** * Create or Update entity * @param entity POJO */ void saveOrUpdate(T entity); /** * Delete entity * @param entity */ void delete(T entity); /** * Find entity by id * @param id ID * @return Entity */ T find(PK id); /** * Find all entities * @return */ List
findAll(); /** * Find all entities by paging * @param pageNumber * @param pageSize * @return */ List
findList(int pageNumber, int pageSize); /** * All row count * @return */ Long count();}

 

GenericDaoSupport主类:

package com.my.dao;import javax.annotation.Resource;import org.hibernate.Session;import org.hibernate.SessionFactory;/** * Generic Dao Base Class * @author Robin * */public abstract class GenericDaoSupport {    @Resource    protected SessionFactory sessionFactory;        /**     * Get Hibernate Session     * @return     */    public Session getSession() {        return this.sessionFactory.getCurrentSession();    }}

 

通用DAO类实现:

package com.my.dao.impl;import java.io.Serializable;import java.lang.reflect.ParameterizedType;import java.lang.reflect.Type;import java.util.List;import org.hibernate.criterion.Projections;import com.my.dao.GenericDao;import com.my.dao.GenericDaoSupport;/** * Generic DAO class * @author Robin * * @param 
* @param
*/@SuppressWarnings("all")public class GenericDaoImpl
extends GenericDaoSupport implements GenericDao
{ // Entity class private Class
entityClass; /** * Constructor */ public GenericDaoImpl() { // 通过反射获取T的类型信息实例 this.entityClass = (Class
) ((ParameterizedType) this.getClass() .getGenericSuperclass()).getActualTypeArguments()[0]; } /** * Create entity * @param entity */ @Override public void create(T entity) { getSession().save(entity); } /** * Update entity * @param entity */ @Override public void update(T entity) { getSession().update(entity); } /** * Create or Update entity * @param entity */ @Override public void saveOrUpdate(T entity) { getSession().saveOrUpdate(entity); } /** * Delete entity * @param entity */ public void delete(T entity){ getSession().delete(entity); } /** * Find entity by id * @param id * @return Entity */ @Override public T find(PK id) { return (T) getSession().get(entityClass, id); } /** * Find all entities * @return */ @Override public List
findAll() { return getSession().createCriteria(entityClass).list(); } /** * Find all entities by paging * @param pageNumber * @param pageSize * @return */ public List
findList(int pageNumber, int pageSize) { return getSession().createCriteria(entityClass) .setFirstResult((pageNumber - 1) * pageSize) .setMaxResults(pageSize) .list(); } /** * All row count * @return */ public Long count() { Long count = (Long)getSession().createCriteria(entityClass) .setProjection(Projections.rowCount()) .uniqueResult(); if(count == null) { return (long)0; } else { return count; } }}

 

Hibernate实体:

package com.my.entity;import java.io.Serializable;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.Table;@SuppressWarnings("serial")@Entity@Table(name = "account")public class Account implements Serializable {    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    @Column(name = "id")    private long id;    @Column(name = "name", length = 200)    private String name;    public long getId() {        return id;    }    public void setId(long id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }}

实体类必需继承Serializable接口。


 

使用方法例子:

写一个AccountDao接口

package com.my.dao;import org.springframework.stereotype.Repository;import com.my.entity.Account;@Repositorypublic interface AccountDao extends GenericDao
{}

AccountDao接口的实现:

package com.my.dao.impl;import org.springframework.stereotype.Repository;import com.my.dao.AccountDao;import com.my.entity.Account;@Repository(value = "accountDao")public class AccountDaoImpl extends GenericDaoImpl
implements AccountDao {}

 

Service的实现和使用:

package com.my.service;import java.util.List;import com.my.entity.Account;public abstract class AccountService {    /**     * Add new account     * @param account Account     */    public abstract void add(Account account);        /**     * Find entity by id     * @param id     * @return     */    public abstract Account find(long id);        /**     * Find all entities     * @return     */    public abstract List
findAll(); /** * Find all entities by paging * @param pageNumber * @param pageSize * @return */ public abstract List
findList(int pageNumber, int pageSize); /** * All row count * @return */ public abstract long count();}
package com.my.service.impl;import java.util.List;import javax.annotation.Resource;import org.springframework.stereotype.Service;import com.my.dao.AccountDao;import com.my.entity.Account;import com.my.service.AccountService;@Service(value = "accountService")public class AccountServiceImpl extends AccountService {    @Resource(name = "accountDao")    private AccountDao accountDao;        public void add(Account account) {        accountDao.saveOrUpdate(account);    }    @Override    public Account find(long id) {        return accountDao.find(id);    }        @Override    public List
findAll(){ return accountDao.findAll(); } @Override public List
findList(int pageNumber, int pageSize) { return accountDao.findList(pageNumber, pageSize); } @Override public long count() { return accountDao.count(); }}

 

可以看到上面Service的调用对应的AccountDao中,不需要再写其它方法。因为在通用DAO中已经实现了。AccountDao只需要加入其它额外的方法即可,比如说特例的查询。

当然可以把通用DAO封装得更加“完美”,比如把查询条件都写上。

网上有一些通用的DAO写法,会把HQL写在Service层,这种破坏了BLL和DAO的分离。

 

附上Spring的xml配置:

com.my.entity
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect hibernate.hbm2ddl.auto=update hibernate.show_sql=true hibernate.format_sql=false hibernate.cache.use_second_level_cache=true hibernate.cache.use_query_cache=false hibernate.cache.provider_class=org.hibernate.cache.internal.NoCacheProvider hibernate.current_session_context_class= org.springframework.orm.hibernate4.SpringSessionContext

 

转载于:https://www.cnblogs.com/HD/p/3975250.html

你可能感兴趣的文章
CF414BMashmokh and ACMDP
查看>>
Notepad++ 通过g++编译
查看>>
JAVA基础2——类初始化相关执行顺序
查看>>
转:Zend Framework 重定向方法(render, forward, redirect)
查看>>
Linux下查看磁盘与目录的容量——df、du
查看>>
关于日记app的思考
查看>>
使用sencha的cmd创建项目时提示找不到\Sencha\Cmd\repo\.sencha\codegen.json
查看>>
如何快速启动一个Java Web编程框架
查看>>
MSP430单片机存储器结构总结
查看>>
文本框过滤特殊符号
查看>>
教育行业安全无线网络解决方案
查看>>
7个杀手级的开源监测工具
查看>>
软件架构学习小结
查看>>
C语言实现UrlEncode编码/UrlDecode解码
查看>>
返回用户提交的图像工具类
查看>>
树链剖分 BZOJ3589 动态树
查看>>
挑战程序设计竞赛 P131 区间DP
查看>>
【例9.9】最长公共子序列
查看>>
NSFileManager打印目录下的文件的函数
查看>>
Selenium自动化-调用Mysql数据库
查看>>