您的位置:首页 > 其它

Hibernate开发底层公共接口

2017-07-07 18:19 197 查看
最近阅读到一个案例,觉得封装的特别好!

package com.jxhkst.school.dao;

import java.io.Serializable;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;

import com.jxhkst.school.util.PageInfo;

/**
*      公共的接口
* @author 浪丶荡
*
*/
public interface ICommonDao<T> {
/**
*      公共查询方法
* @param entity
*/
public void save(T entity);
/**
*      公共更新方法
* @param entity
*/
void update(T entity);
/**
*      公共根据编号查找对象方法<br>
*      绝在不管什么类型的编号都能复用(String/Integer)
* @param entity
*/
T findObjectByID(Serializable id);
/**
*      编号定点删除
* @param ids
*/
void deleteObjectByIDs(Serializable ... ids);
/**
*      批量删除
* @param entities
*/
void deleteObjectByCollection(Collection<T> entities);
}


以上接口的实现(基于Hibernate):

package com.jxhkst.school.daoimpl;

import java.io.Serializable;
import java.util.Collection;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import com.jxhkst.school.dao.ICommonDao;
import com.jxhkst.school.util.GenericSuperClass;
/**
*
* @author 浪丶荡
*
* @param <T>
*/
public class CommonDaoImpl<T> extends HibernateDaoSupport implements ICommonDao<T> {

//范型转换
@SuppressWarnings("unchecked")
private Class entity = (Class)GenericSuperClass.getClass(this.getClass());
//需要操作数据库,要用到Hibernate模板,需要继承HibernateDaoSupport
public void save(T entity) {
//使用Hibernate模板保存数据
this.getHibernateTemplate().save(entity);
}
//注入sessionFactory
@Resource(name="sessionFactory")
public final void setSessionFactoryDi(SessionFactory sessionFactory) {
super.setSessionFactory(sessionFactory);
}
@Override
public void update(T entity) {
this.getHibernateTemplate().update(entity);

}
@SuppressWarnings("unchecked")
@Override
public T findObjectByID(Serializable id) {
return (T)this.getHibernateTemplate().get(entity, id);
}
@Override
public void deleteObjectByIDs(Serializable... ids) {
for(int i=0;ids!=null && i<ids.length;i++){
Serializable id = ids[i];
Object object = (Object)this.getHibernateTemplate().get(entity, id);
this.getHibernateTemplate().delete(object);
}

}
@Override
public void deleteObjectByCollection(Collection<T> entities) {
this.getHibernateTemplate().deleteAll(entities);

}

}


泛型转换工具

public static Class getClass(Class tClass) {
ParameterizedType pt = (ParameterizedType) tClass.getGenericSuperclass();
Class entity = (Class)pt.getActualTypeArguments()[0];
return entity;
}


底层接口开发好了后,其他的业务接口只需要继承公共接口就可以。

而业务接口的实现类需要实现业务接口并继续公共接口的实现类

@Repository(ISchoolTestBeanDao.SERVICE_NAME)
public class SchoolTestBeanDaoImpl extends CommonDaoImpl<SchoolTestBean> implements ISchoolTestBeanDao {

}


这里面的泛型和序列化对象用的我水土都不服就服它!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  hibernate 阅读