1 IBaseDao.java
package com.hm.eams.basic.common.base;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
public interface IBaseDao<T, PK extends Serializable> {
/**
* 创建一个新的实例对象到数据库
* @param newInstance T 泛型类,即实际应用中的POJO
* @return boolean
*/
public boolean create(T newInstance) throws Exception;
/**
* 创建一个新的实例对象到数据库
* @param newInstance T 泛型类,即实际应用中的POJO
* @return 返回 Object 主键值
* @throws Exception
*/
public Object createObject(T newInstance) throws Exception;
/**
* 将一个集合对象更新到数据库
* @param newInstance T 泛型类,即实际应用中的POJO
* @return boolean
*/
public boolean createAll(Collection<T> newInstance)throws Exception;
/** 保存对象 */
public boolean creatObjcate(Object obj)throws Exception ;
/**
* 更新一个实例对象到数据库
* @param newInstance T 泛型类,即实际应用中的POJO
* @return boolean
*/
public boolean update(T newInstance) throws Exception;
/**
* @param model T 泛型类,代表实际应用中的POJO
* @return boolean 返回布尔类型变量
* @throws Exception
*/
public boolean delete(T model) throws Exception;
/**
* 根据ID和类型从数据库删除数据
* @param id PK 主键
* @param T 泛型类,代表实际应用中的POJO
* @return T
* @throws Exception
*/
public T delete(PK id, Class<T> T) throws Exception;
/**
* 从数据库删除实例
* @param sql String
* @return boolean
*/
public boolean deleteBySQL(String sql) throws Exception;
/**
* 从数据库删除实例
* @param condition String 删除操作的条件
* @return boolean
*/
public boolean delete(String condition) throws Exception;
/**
* 根据主键查找实例对象
* @param id PK 主键
* @return T
*/
public T findById(PK id) throws Exception;
/**
* 根据SQL查找实例对象
* @param sql String
* @return T
*/
public T findBySQL(String sql) throws Exception;
/**
* 查找所有实例对象
* @return List
*/
public List<T> findAll() throws Exception;
/**
* 根据SQL查找对象列表
* @param sql String
* @return List
*/
public List<T> findAllBySQL(String sql) throws Exception;
/**
* 根据SQL查找对象列表
*
* @param SQL sql语句
* @param values 0个或多个参数
* @return
* @throws Exception
*/
public List<T> findAllBySQLAndParameter(String SQL, Object... values) throws Exception;
/**
* 使用HQL查询返回列表
* @param hql HQL语句
* @param Object... values 多个条件参数
* @return
* @throws Exception
*/
public List<T> findListByHQL(String hql, Object... values) throws Exception;
/**
* 使用HQL查询返回列表
* @param hql HQL语句
* @param List<Object> values 多个条件参数
* @return
* @throws Exception
*/
public List<T> findListByHQL(String hql, List<Object> values) throws Exception;
/*
* 使用HQL查询 分页导出
*/
public List<T> findByHqlPage(final String hql, final Integer page,
final Integer pageSize) throws Exception ;
/**
* 查找分页信息,该方法只针对单表操作有效
*
* @param currentPage int 当前页码
* @param pageSize int 每页显示的记录数
* @param condition String 查询条件
* @return PageInfo 分页信息对象
*/
public PageInfo findPageInfo(int currentPage, int pageSize, String condition)
throws Exception;
/**
* 分页显示实例对象信息列表,该方法只针对单表操作有效
*
* @param currentPage int 当前页码
* @param pageSize int 每页显示的记录数
* @param condition String 查询条件
* @return List 实例对象列表
*/
public List<T> findPageList(int currentPage, int pageSize, String condition)
throws Exception;
/**
* 使用hql查找分页信息
*
* @param currentPage int 当前页码
* @param pageSize int 每页显示的记录数
* @param hql String hql查询语句
* @param values Object 条件值对象集合
* @return PageInfo 分页信息对象
*/
public PageInfo findPageInfo(int currentPage, int pageSize, String hql, Object...values) throws Exception;
/**
* 使用hql分页显示实例对象信息列表
*
* @param currentPage int 当前页码
* @param pageSize int 每页显示的记录数
* @param hql String hql查询语句
* @param values Object 条件值对象集合
* @return List 实例对象列表
*/
public List<T> findPageList(int currentPage, int pageSize, String hql, Object...values) throws Exception;
/**
* 查找分页信息,该方法对所有操作有效
*
* @param currentPage int 当前页码
* @param pageSize int 每页显示的记录数
* @param SQL String SQL语句
* @return PageInfo 分页信息对象
*/
public PageInfo findPageInfoBySQL(int currentPage, int pageSize, String SQL, Object...values)
throws Exception;
/**
* 分页显示实例对象信息列表,该方法对所有操作有效
*
* @param currentPage int 当前页码
* @param pageSize int 每页显示的记录数
* @param SQL String SQL语句
* @return List 实例对象列表
*/
public List<T> findPageListBySQL(int currentPage, int pageSize, String SQL, Object...values)
throws Exception;
/**
* 分页显示实例对象信息列表,该方法对所有操作有效
*
* @param currentPage int 当前页码
* @param pageSize int 每页显示的记录数
* @param SQL String SQL语句
* @return List 实例对象列表
*/
public List<T> findPageListBySQLWithOrder(int currentPage, int pageSize, String SQL, Object...values)
throws Exception;
/**
* 获得查询总数
* @param sql
* @return
* @throws Exception
*/
public Integer findDataCount(String sql) throws Exception;
public List<Map> findToMapBySQL(final String sql) ;
public void execInsert(final String insertSql,final Object...params);
}
2 BaseDaoImpl.java
package com.hm.eams.basic.common.base;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.transform.Transformers;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.util.Assert;
import com.hm.basic.repository.BaseHibernateRepository;
import com.hm.util.HibernateUtil;
import com.hm.util.StringUtil;
public abstract class BaseDaoImpl<T, PK extends Serializable> extends BaseHibernateRepository implements IBaseDao<T, PK> {
private Log log = LogFactory.getLog(BaseDaoImpl.class);
/**泛型类,代表实际应用中的POJO*/
private Class<T> type;
public BaseDaoImpl() {
this.type = (Class<T>) ((ParameterizedType)(this.getClass().getGenericSuperclass())).getActualTypeArguments()[0];
}
/**
* 创建一个新的实例对象到数据库
* @param newInstance T 泛型类,即实际应用中的POJO
* @return boolean
*/
public boolean create(T newInstance)throws Exception {
boolean bFlag = false;
getHibernateTemplate().save(newInstance);
bFlag = true;
return bFlag;
}
/**
* 将一个集合对象更新到数据库
* @param newInstance T 泛型类,即实际应用中的POJO
* @return boolean
*/
public boolean createAll(Collection<T> newInstance)throws Exception {
boolean bFlag = false;
getHibernateTemplate().saveOrUpdateAll(newInstance);
bFlag = true;
return bFlag;
}
/** 保存对象的 */
public boolean creatObjcate(Object obj)throws Exception {
boolean bFlag = false;
getHibernateTemplate().saveOrUpdate(obj);
bFlag = true;
return bFlag;
}
/**
*
* Description:创建一个新的实例对象到数据库
* @param newInstance T 泛型类,即实际应用中的POJO
* @return 返回 Object 主键值
* @throws Exception
*/
public Object createObject(T newInstance) throws Exception{
Object t = getHibernateTemplate().save(newInstance);
return t;
}
/**
* 更新一个实例对象到数据库
* @param newInstance T 泛型类,即实际应用中的POJO
* @return boolean
*/
public boolean update(T newInstance)throws Exception {
boolean bFlag = false;
getHibernateTemplate().update(newInstance);
bFlag = true;
return bFlag;
}
/**
* 删除实例
* @param model T 泛型类,代表实际应用中的POJO
* @return boolean 返回布尔类型变量
* @throws Exception
*/
public boolean delete(T model) throws Exception {
boolean bFlag = false;
getHibernateTemplate().delete(model);
bFlag = true;
return bFlag;
}
/**
* 根据ID和类型从数据库删除数据
* @param id PK 主键
* @param T 泛型类,代表实际应用中的POJO
* @return T
* @throws Exception
*/
@SuppressWarnings("unchecked")
public T delete(PK id, Class<T> T) throws Exception {
T obj = null;
obj = (T)getHibernateTemplate().get(T, id);
getHibernateTemplate().delete(obj);
return obj;
}
/**
* 从数据库删除实例
* @param SQL String
* @return boolean
*/
public boolean deleteBySQL(final String SQL)throws Exception {
boolean bFlag = false;
this.getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
session.createSQLQuery(SQL).executeUpdate();
return null;
}
});
bFlag = true;
return bFlag;
}
/**
* 从数据库删除实例
* @param condition String 删除操作的条件
* @return boolean
*/
public boolean delete(String condition)throws Exception {
boolean bFlag = false;
String SQL = "delete from " + this.type.getName() + " " +condition;
this.getHibernateTemplate().bulkUpdate(SQL);
bFlag = true;
return bFlag;
}
/**
* 根据主键查找实例对象
* @param id PK 主键
* @return T
* @throws Exception
*/
@SuppressWarnings("unchecked")
public T findById(PK id) throws Exception {
return (T) getHibernateTemplate().get(type, id);
}
/**
* 根据SQL查找实例对象
* @param SQL String
* @return T
*/
@SuppressWarnings("unchecked")
public T findBySQL(final String SQL) throws Exception{
return (T)this.getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Query query =session.createSQLQuery(SQL).setResultTransformer(
Transformers.ALIAS_TO_ENTITY_MAP);
Iterator iter = query.list().iterator();
Object object = null;
while (iter.hasNext()) {
try {
object = type.newInstance();
HibernateUtil.copyProperty(object, (Map) iter.next());
} catch (java.lang.InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return (T) object;
}
});
}
/**
* 查找所有实例对象
* @return List
*/
@SuppressWarnings("unchecked")
public List<T> findAll() throws Exception {
String HQL = "from " + this.type.getSimpleName();
try {
return (List<T>) getHibernateTemplate().find(HQL);
} catch (DataAccessException ex) {
ex.printStackTrace();
return null;
} catch (Exception ex) {
ex.printStackTrace();
log.error("findAll:"+ex.toString());
return null;
}
}
/**
* 根据SQL查找对象列表
* @param SQL String
* @return List
*/
@SuppressWarnings("unchecked")
public List<T> findAllBySQL(final String SQL) throws Exception{
if(!StringUtil.isNullOrBlank(SQL)){
return (List<T>)this.getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Query query =session.createSQLQuery(SQL).setResultTransformer(
Transformers.ALIAS_TO_ENTITY_MAP);
Iterator iter = query.list().iterator();
List list = new ArrayList();
while (iter.hasNext()) {
Object object=null;
try {
object = type.newInstance();
HibernateUtil.copyProperty(object, (Map) iter.next());
list.add(object);
} catch (java.lang.InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return list;
}
});
}else{
return this.findAll();
}
}
/**
* 根据SQL查找对象列表
*
* @param SQL
* @param values 参数0...*
* @return
* @throws Exception
*/
public List<T> findAllBySQLAndParameter(String SQL, Object... values) throws Exception {
Query query = createSQLQuery(SQL, values).setResultTransformer(
Transformers.ALIAS_TO_ENTITY_MAP);
Iterator iter = query.list().iterator();
List list = new ArrayList();
while (iter.hasNext()) {
Object object = null;
try {
object = type.newInstance();
HibernateUtil.copyProperty(object, (Map) iter.next());
list.add(object);
} catch (java.lang.InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return list;
}
/**
* 使用HQL查询返回列表
* @param hql HQL语句
* @param values 多个条件参数
* @return
* @throws Exception
*/
public List<T> findListByHQL(String hql, Object... values) throws Exception {
if(!StringUtil.isNullOrBlank(hql)){
if(values!=null && values.length>0){
return createQuery(hql,values).list();
}else{
return createQuery(hql).list();
}
}else{
return this.findAll();
}
}
/**
* 使用HQL查询返回列表
* @param hql HQL语句
* @param values 多个条件参数
* @return
* @throws Exception
*/
public List<T> findListByHQL(String hql, List<Object> values) throws Exception {
Object[] objs = null;
List<T> list = new ArrayList();
if(values!=null && values.size()>0){
objs = new Object[values.size()];
for(int i=0;i<values.size();i++){
objs[i] = values.get(i);
}
}
Query query=createQuery(hql,objs);
if(query!=null) {
list = query.list();
}
return list;
}
/**
* 根据查询函数与参数列表创建Query对象,后续可进行更多处理,辅助函数
* @param queryString
* @param values
* @return
*/
protected Query createQuery(String queryString, Object... values) {
Assert.hasText(queryString);
Query queryObject = getSession().createQuery(queryString);
if (values != null) {
for (int i=0; i<values.length; i++) {
queryObject.setParameter(i, values[i]);
}
}
return queryObject;
}
protected Query createSQLQuery(String queryString, Object... values) {
Assert.hasText(queryString);
Query queryObject = getSession().createSQLQuery(queryString);
if (values != null) {
for (int i=0; i<values.length; i++) {
queryObject.setParameter(i, values[i]);
}
}
return queryObject;
}
public List<T> findByHqlPage(final String hql, final Integer page,
final Integer pageSize) throws Exception {
// TODO Auto-generated method stub
return this.getHibernateTemplate().executeFind(new HibernateCallback(){
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
Query query=session.createQuery(hql);
if(page!=null && pageSize!=null)
{
query.setFirstResult((page-1)*pageSize).setMaxResults(pageSize);
}
return ( List<T>) query.list();
}});
}
/**
* 查找分页信息,该方法只针对单表操作有效
* @param currentPage int 当前页码
* @param pageSize int 每页显示的记录数
* @param condition String 查询条件
* @return PageInfo 分页信息对象
*/
public PageInfo findPageInfo(final int currentPage, final int pageSize, final String condition)
throws Exception {
return (PageInfo)this.getHibernateTemplate().execute(new HibernateCallback() {
@SuppressWarnings("unchecked")
public Object doInHibernate(Session session) throws HibernateException, SQLException {
PageInfo pageInfo = new PageInfo();
String SQL = "select count(*) as amount from "+ type.getSimpleName();
if (condition != null)
SQL += condition;
Query query = session.createQuery(SQL);
List<Long> list = (List<Long>) query.list();
pageInfo.setCurrentPage(currentPage);
pageInfo.setPageSize(pageSize);
int count = 0;
Object cv = "0";
if(list!=null && list.size()>0){
cv = list.get(0);
if(cv==null){
cv = "0";
}
count = ((Long) list.get(0)).intValue();
}
pageInfo.setTotalCount(count);
// 总页数
double pagenum = Double.valueOf(cv.toString())/Double.valueOf(String.valueOf(pageSize));
Double dub = new Double(Math.ceil(pagenum));
int totalPage = dub.intValue();
if(totalPage<=1){
pageInfo.setCurrentPage(1);
}else{
pageInfo.setCurrentPage(currentPage);
}
pageInfo.setTotalPage(totalPage);
return pageInfo;
}
});
}
/**
* 分页显示实例对象信息列表,该方法只针对单表操作有效
* @param currentPage int 当前页码
* @param pageSize int 每页显示的记录数
* @param condition String 查询条件
* @return List 实例对象列表
* @throws Exception
*/
@SuppressWarnings("unchecked")
public List<T> findPageList(final int currentPage, final int pageSize, final String condition) throws Exception {
return (List<T>)this.getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
String HQL = " from "+ type.getSimpleName();
if (condition != null)
HQL += condition;
Query query = session.createQuery(HQL);
query.setFirstResult((currentPage - 1) * pageSize);
query.setMaxResults(pageSize);
return (List<T>) query.list();
}
});
}
/**
* 使用hql查找分页信息
*
* @param currentPage int 当前页码
* @param pageSize int 每页显示的记录数
* @param hql String hql查询语句
* @param values Object 条件值对象集合
* @return PageInfo 分页信息对象
*/
public PageInfo findPageInfo(final int currentPage, final int pageSize, final String hql, final Object...values) throws Exception{
return (PageInfo)this.getHibernateTemplate().execute(new HibernateCallback() {
@SuppressWarnings("unchecked")
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Query query = createQuery(hql, values);
List<Long> list = (List<Long>) query.list();
PageInfo pageInfo = new PageInfo();
pageInfo.setCurrentPage(currentPage);
pageInfo.setPageSize(pageSize);
int count = 0 ;
Object cv = "0";
if(list!=null && list.size()>0){
cv = list.get(0);
if(cv==null){
cv = "0";
}
count = ((Long)list.get(0)).intValue();
}
pageInfo.setTotalCount(count);
// 总页数
double pagenum = Double.valueOf(cv.toString())/Double.valueOf(String.valueOf(pageSize));
Double dub = new Double(Math.ceil(pagenum));
int totalPage = dub.intValue();
if(totalPage<=1){
pageInfo.setCurrentPage(1);
}else{
pageInfo.setCurrentPage(currentPage);
}
pageInfo.setTotalPage(totalPage);
return pageInfo;
}
});
}
/**
* 使用hql分页显示实例对象信息列表
*
* @param currentPage int 当前页码
* @param pageSize int 每页显示的记录数
* @param hql String hql查询语句
* @param values Object 条件值对象集合
* @return List 实例对象列表
*/
@SuppressWarnings("unchecked")
public List<T> findPageList(final int currentPage, final int pageSize, final String hql, final Object...values) throws Exception{
return (List<T>)this.getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Query query = createQuery(hql, values);
query.setFirstResult((currentPage - 1) * pageSize);
query.setMaxResults(pageSize);
return (List<T>) query.list();
}
});
}
/**
* 查找分页信息,该方法对所有操作有效
* @param currentPage int 当前页码
* @param pageSize int 每页显示的记录数
* @param sql String SQL语句
* @return PageInfo 分页信息对象
*/
public PageInfo findPageInfoBySQL(final int currentPage, final int pageSize, final String sql, final Object...values)throws Exception {
return (PageInfo)this.getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Query query = createSQLQuery(sql, values);
List list = query.list();
Object cv = "0";
if(list!=null && list.size()>0){
cv = list.get(0);
if(cv==null){
cv = "0";
}
}
PageInfo pageInfo = new PageInfo();
// 总页数
double pagenum = Double.valueOf(cv.toString())/Double.valueOf(String.valueOf(pageSize));
Double dub = new Double(Math.ceil(pagenum));
int totalPage = dub.intValue();
if(totalPage<=1){
pageInfo.setCurrentPage(1);
}else{
pageInfo.setCurrentPage(currentPage);
}
pageInfo.setPageSize(pageSize);
pageInfo.setTotalCount(Integer.valueOf(cv.toString()));
pageInfo.setTotalPage(totalPage);
return pageInfo;
}
});
}
/**
* 分页显示实例对象信息列表,该方法对所有操作有效
* @param currentPage int 当前页码
* @param pageSize int 每页显示的记录数
* @param sql String SQL语句
* @return List 实例对象列表
*/
@SuppressWarnings("unchecked")
public List<T> findPageListBySQL(final int currentPage, final int pageSize, final String sql, final Object...values) throws Exception{
return this.getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Query query = createSQLQuery(sql, values);
query.setMaxResults(pageSize);
query.setFirstResult((currentPage - 1) * pageSize);
query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
Iterator iter = query.list().iterator();
List list = new ArrayList();
while (iter.hasNext()) {
Object object;
try {
object = type.newInstance();
HibernateUtil.copyProperty(object, (Map) iter.next());
list.add(object);
} catch (java.lang.InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return list;
}
});
}
/**
* 分页显示实例对象信息列表,该方法对所有操作有效
* @param currentPage int 当前页码
* @param pageSize int 每页显示的记录数
* @param sql String SQL语句
* @return List 实例对象列表
*/
@SuppressWarnings("unchecked")
public List<T> findPageListBySQLWithOrder(final int currentPage, final int pageSize, final String sql, final Object...values) throws Exception{
return this.getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Query query = createSQLQuery(sql, values);
query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
Iterator iter = query.list().iterator();
List list = new ArrayList();
while (iter.hasNext()) {
Object object;
try {
object = type.newInstance();
HibernateUtil.copyProperty(object, (Map) iter.next());
list.add(object);
} catch (java.lang.InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return list;
}
});
}
/**
* 获得翻页面的SQL语句
*
* @param sql SQL语句
* @param currentPage 当前页
* @param pageNum 页的数量
* @return
*/
private static String makePageSQL(String sql, int currentPage, int pageSize) {
int startPos = (currentPage - 1) * pageSize ;
int endPos = currentPage * pageSize;
// 先按查询条件查询出从0到页未的记录.然后再取出从页开始到页未的记录
StringBuffer sqlBuffer = new StringBuffer();
sqlBuffer.append("select * from (select row_.*, rownum rownum_ from (");
sqlBuffer.append(sql);
sqlBuffer.append(") row_) where rownum_ >"+ startPos +" and rownum_<="+ endPos);
return sqlBuffer.toString();
}
public Integer findDataCount(final String sql) throws Exception {
return (Integer)this.getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Query query = session.createSQLQuery(sql);
List list = query.list();
Object cv = "0";
if(list!=null && list.size()>0){
if(list.get(0)!=null)
cv = list.get(0);
}
return Integer.valueOf(cv.toString());
}
});
}
/**
* @author tcx
* @param sql
* @return
*/
@SuppressWarnings("unchecked")
public List<Map> findToMapBySQL(final String sql) {
return (List<Map>) this.getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException,
SQLException {
Query query = session.createSQLQuery(sql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
return (List<Map>) query.list();
}
});
}
public void execInsert(final String insertSql,final Object...params){
this.getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException,
SQLException {
Query query = session.createSQLQuery(insertSql);
for(int i=0;i<params.length;i++){
query.setParameter(i, params[i]);
}
query.executeUpdate();
return null;
}
});
}
}
3 BaseHibernateRepository.java
package com.hm.basic.repository;
import javax.annotation.Resource;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.dao.support.DaoSupport;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
public abstract class BaseHibernateRepository extends DaoSupport {
private HibernateTemplate hibernateTemplate;
/**
* Set the Hibernate SessionFactory to be used by this DAO. Will
* automatically create a HibernateTemplate for the given SessionFactory.
*
* @see #createHibernateTemplate
* @see #setHibernateTemplate
*/
@Autowired
@Resource(name="sessionFactory")
public final void setSessionFactory(SessionFactory sessionFactory) {
if (this.hibernateTemplate == null
|| sessionFactory != this.hibernateTemplate.getSessionFactory()) {
this.hibernateTemplate = createHibernateTemplate(sessionFactory);
}
}
/**
* Create a HibernateTemplate for the given SessionFactory. Only invoked if
* populating the DAO with a SessionFactory reference!
* <p>
* Can be overridden in subclasses to provide a HibernateTemplate instance
* with different configuration, or a custom HibernateTemplate subclass.
*
* @param sessionFactory
* the Hibernate SessionFactory to create a HibernateTemplate for
* @return the new HibernateTemplate instance
* @see #setSessionFactory
*/
protected HibernateTemplate createHibernateTemplate(
SessionFactory sessionFactory) {
return new HibernateTemplate(sessionFactory);
}
/**
* Return the Hibernate SessionFactory used by this DAO.
*/
public final SessionFactory getSessionFactory() {
return (this.hibernateTemplate != null ? this.hibernateTemplate
.getSessionFactory() : null);
}
/**
* Set the HibernateTemplate for this DAO explicitly, as an alternative to
* specifying a SessionFactory.
*
* @see #setSessionFactory
*/
public final void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
/**
* Return the HibernateTemplate for this DAO, pre-initialized with the
* SessionFactory or set explicitly.
* <p>
* <b>Note: The returned HibernateTemplate is a shared instance.</b> You
* may introspect its configuration, but not modify the configuration (other
* than from within an {@link #initDao} implementation). Consider creating a
* custom HibernateTemplate instance via
* <code>new HibernateTemplate(getSessionFactory())</code>, in which case
* you're allowed to customize the settings on the resulting instance.
*/
public final HibernateTemplate getHibernateTemplate() {
return this.hibernateTemplate;
}
protected final void checkDaoConfig() {
if (this.hibernateTemplate == null) {
throw new IllegalArgumentException(
"'sessionFactory' or 'hibernateTemplate' is required");
}
}
/**
* Obtain a Hibernate Session, either from the current transaction or a new
* one. The latter is only allowed if the
* {@link org.springframework.orm.hibernate3.HibernateTemplate#setAllowCreate "allowCreate"}
* setting of this bean's {@link #setHibernateTemplate HibernateTemplate} is
* "true".
* <p>
* <b>Note that this is not meant to be invoked from HibernateTemplate code
* but rather just in plain Hibernate code.</b> Either rely on a
* thread-bound Session or use it in combination with
* {@link #releaseSession}.
* <p>
* In general, it is recommended to use HibernateTemplate, either with the
* provided convenience operations or with a custom HibernateCallback that
* provides you with a Session to work on. HibernateTemplate will care for
* all resource management and for proper exception conversion.
*
* @return the Hibernate Session
* @throws DataAccessResourceFailureException
* if the Session couldn't be created
* @throws IllegalStateException
* if no thread-bound Session found and allowCreate=false
* @see org.springframework.orm.hibernate3.SessionFactoryUtils#getSession(SessionFactory,
* boolean)
*/
protected final Session getSession()
throws DataAccessResourceFailureException, IllegalStateException {
return getSession(this.hibernateTemplate.isAllowCreate());
}
/**
* Obtain a Hibernate Session, either from the current transaction or a new
* one. The latter is only allowed if "allowCreate" is true.
* <p>
* <b>Note that this is not meant to be invoked from HibernateTemplate code
* but rather just in plain Hibernate code.</b> Either rely on a
* thread-bound Session or use it in combination with
* {@link #releaseSession}.
* <p>
* In general, it is recommended to use
* {@link #getHibernateTemplate() HibernateTemplate}, either with the
* provided convenience operations or with a custom
* {@link org.springframework.orm.hibernate3.HibernateCallback} that
* provides you with a Session to work on. HibernateTemplate will care for
* all resource management and for proper exception conversion.
*
* @param allowCreate
* if a non-transactional Session should be created when no
* transactional Session can be found for the current thread
* @return the Hibernate Session
* @throws DataAccessResourceFailureException
* if the Session couldn't be created
* @throws IllegalStateException
* if no thread-bound Session found and allowCreate=false
* @see org.springframework.orm.hibernate3.SessionFactoryUtils#getSession(SessionFactory,
* boolean)
*/
protected final Session getSession(boolean allowCreate)
throws DataAccessResourceFailureException, IllegalStateException {
return (!allowCreate ? SessionFactoryUtils.getSession(
getSessionFactory(), false) : SessionFactoryUtils.getSession(
getSessionFactory(), this.hibernateTemplate
.getEntityInterceptor(), this.hibernateTemplate
.getJdbcExceptionTranslator()));
}
/**
* Convert the given HibernateException to an appropriate exception from the
* <code>org.springframework.dao</code> hierarchy. Will automatically
* detect wrapped SQLExceptions and convert them accordingly.
* <p>
* Delegates to the
* {@link org.springframework.orm.hibernate3.HibernateTemplate#convertHibernateAccessException}
* method of this DAO's HibernateTemplate.
* <p>
* Typically used in plain Hibernate code, in combination with
* {@link #getSession} and {@link #releaseSession}.
*
* @param ex
* HibernateException that occured
* @return the corresponding DataAccessException instance
* @see org.springframework.orm.hibernate3.SessionFactoryUtils#convertHibernateAccessException
*/
protected final DataAccessException convertHibernateAccessException(
HibernateException ex) {
return this.hibernateTemplate.convertHibernateAccessException(ex);
}
/**
* Close the given Hibernate Session, created via this DAO's SessionFactory,
* if it isn't bound to the thread (i.e. isn't a transactional Session).
* <p>
* Typically used in plain Hibernate code, in combination with
* {@link #getSession} and {@link #convertHibernateAccessException}.
*
* @param session
* the Session to close
* @see org.springframework.orm.hibernate3.SessionFactoryUtils#releaseSession
*/
protected final void releaseSession(Session session) {
SessionFactoryUtils.releaseSession(session, getSessionFactory());
}
}