具体不说了,看上一篇。
开发框架spring4.2.9-springmvc-hibernate4.3.11Final,需要包的可以在我的资源里找。
由于这些类都要封装进dao基类中,所以就不交给spring管理了,注解都去掉。
方便大家参考依赖,保留import,看别人的代码不贴上依赖,那么多同名的包,谁知道要用哪个。
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import …….util.localcache.LocalCacheUtil;
/**
* 主键生成基类
* @author 疯狂的蚯蚓
*
*/
public class IdGenerator
{
/**
* AtomicInteger是一个提供原子操作的Integer类,通过线程安全的方式操作加减。
*/
protected AtomicInteger value;
protected String time;
/**
* 读写锁
*/
protected ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
public String getSplitString()
{
return "";
}
public int getInitial()
{
return 0;
}
public String getPrefix()
{
String result = null;
try
{
//查询服务器的配置文件
result = (String)LocalCacheUtil.query(PropertiesFileIOUtil.MECHINE_CODE_KEY);
if(result==null)
{
Map<String, String> map = PropertiesFileIOUtil.loadProps();
if(map==null || !map.containsKey(PropertiesFileIOUtil.MECHINE_CODE_KEY))
{
return "";
}
//服务器号
result = map.get(PropertiesFileIOUtil.MECHINE_CODE_KEY);
//加入本地缓存
LocalCacheUtil.put(PropertiesFileIOUtil.MECHINE_CODE_KEY, result);
}
}
catch (Exception e)
{
e.printStackTrace();
throw new RuntimeException("获取主键前缀失败");
}
return result;
}
public int getRollingInterval()
{
return 1;
}
}
/**
* Id生成器配置接口
* @author 疯狂的蚯蚓
*
*/
public interface IdGeneratorConfig {
/**
* 获取分隔符
* @return
*/
String getSplitString();
/**
* 获取初始值
* @return
*/
int getInitial();
/**
* 获取ID前缀
* @return
*/
String getPrefix();
/**
* 获取滚动间隔, 单位: 秒
* @return
*/
int getRollingInterval();
}
import java.util.Map;
import …….util.localcache.LocalCacheUtil;
/**
* 主键生成配置实现类
* @author 疯狂的蚯蚓
*
*/
public class DefaultIdGeneratorConfig implements IdGeneratorConfig
{
@Override
public String getSplitString()
{
return "";
}
@Override
public int getInitial()
{
return 1;
}
@Override
public String getPrefix()
{
String result = null;
try
{
//查询服务器的配置文件
result = (String)LocalCacheUtil.query(PropertiesFileIOUtil.MECHINE_CODE_KEY);
if(result==null)
{
Map<String, String> map = PropertiesFileIOUtil.loadProps();
if(map==null || !map.containsKey(PropertiesFileIOUtil.MECHINE_CODE_KEY))
{
return "";
}
//服务器号
result = map.get(PropertiesFileIOUtil.MECHINE_CODE_KEY);
//加入本地缓存
LocalCacheUtil.put(PropertiesFileIOUtil.MECHINE_CODE_KEY, result);
}
}
catch (Exception e)
{
e.printStackTrace();
throw new RuntimeException("获取主键前缀失败");
}
return result;
}
@Override
public int getRollingInterval()
{
return 1;
}
}
缓存啥的就自己去研究了,很简单,没几行代码,以下是配置文件的读取,当然其他方法都行,不一定要存文件
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* 读取配置文件工具类
* @author 疯狂的蚯蚓
*
*/
public class PropertiesFileIOUtil
{
/**
* 机器号代码
*/
public static final String MECHINE_CODE_KEY = "MechineCode";
public static Properties props;
public static Map<String, String> loadProps()
{
Map<String, String> result = new HashMap<String, String>();
props = new Properties();
InputStream in = null;
try
{
//第一种,通过类加载器进行获取properties文件流
//in = PropertyUtil.class.getClassLoader().getResourceAsStream("sysConfig.properties");
//第二种,通过类进行获取properties文件流
in = PropertiesFileIOUtil.class.getClassLoader().getResourceAsStream("config/mechineCode.properties");
props.load(in);
String mechineCode = props.getProperty(MECHINE_CODE_KEY);
// System.out.println("mechineCode="+mechineCode);
result.put(MECHINE_CODE_KEY, mechineCode);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
//logger.error("sysConfig.properties文件未找到");
}
catch (IOException e)
{
e.printStackTrace();
//logger.error("出现IOException");
}
finally
{
try
{
if(null != in)
{
in.close();
}
}
catch (IOException e)
{
//logger.error("sysConfig.properties文件流关闭出现异常");
}
}
//logger.info("加载properties文件内容完成...........");
//logger.info("properties文件内容:" + props);
return result;
}
public String getProperty(String key)
{
if(null == props)
{
loadProps();
}
return props.getProperty(key);
}
public String getProperty(String key, String defaultValue)
{
if(null == props)
{
loadProps();
}
return props.getProperty(key, defaultValue);
}
}
以下是dao基类接口
import java.io.Serializable;
import java.util.List;
import …….vo.ComboBox;
import …….vo.Pagination;
/**
* 通用Dao接口
*
* @param <T> 实体对象类
* @param <PK> 主键
*/
public interface GenericDao<T, PK extends Serializable> {
/**
* 根据主键获得一个实体对象
*
* @param id
* @return
*/
public T findById(PK id);
/**
* 获得表中的所有实体对象
*
* @return
*/
public List<T> findAll();
/**
* 新增一个实体对象
*
* @param entity
* @return
*/
public T save(T entity);
/**
* 更新一个实体对象
*
* @param entity
*/
public void update(T entity);
/**
* 删除一个实体对象
*
* @param entity
*/
public void delete(T entity);
/**
* 根据HQL语句和查询条件,获得具体数量
*
* @param hql 不需要也不能写select count(*),直接从from开始写
* @param params
* @return
*/
public Long countByHQL(String hql, Object[] params);
/**
* 根据HQL语句和查询条件,获得一个实体对象
*
* @param hql
* @param params
* @return
*/
public T getEntityByHQL(String hql, Object[] params);
/**
* 根据HQL语句和查询条件,获得多个实体对象
*
* @param hql
* @param params
* @return
*/
public List<T> listEntityByHQL(String hql, Object[] params);
/**
* 根据HQL语句和查询条件,获得多个实体对象,分页显示,可排序
*
* @param hql
* 必须是查询整个model类的信息,不能只查询部分字段 正确写法:from 类名 where 条件 order by
* 错误写法:select 表名(字段名) from 类名 where 条件
* @param params
* @param pageSize
* 每页显示记录数
* @param pageNumber
* 当前第几页
* @return
*/
public Pagination listEntityByHQL(String hql, Object[] params,Integer pageSize, Integer pageNumber);
public Pagination listEntityByHQL1(String hql, Object[] params,
Integer pageSize, Integer pageNumber);
public Pagination listEntityByHQLbox(String hql, Object[] params,
Integer pageSize, Integer pageNumber);
/**
* 根据SQL语句和查询条件,获得多个实体对象,分页显示,可排序
*
* @param sql
* @param params
* @param pageSize
* 每页显示记录数
* @param pageNumber
* 当前第几页
* @return
*/
public Pagination listEntityBySQL(String sql, Object[] params,Integer pageSize, Integer pageNumber);
/**
* 执行删除或者更新的HQL语句
*
* @param hql
* @param params
* @return
*/
public Integer updateByHQL(String hql, Object[] params);
/**
* 执行删除或者更新的SQL语句
*
* @param sql
* @param params
* @return
*/
public Integer updateBySQL(String sql, Object[] params);
/**
* 根据任意的select语句,获得对应列的对象数组
* @param hql
* @param params
* @return
*/
public List<Object[]> listEntityBySelect(String hql, Object[] params);
/**
* 根据HQL语句和查询条件,获得实体对象中一个字段的所有值的集合
* @param hql
* @param params
* @return easyui-combobox格式的vo类
*/
public List<ComboBox> listFieldByHQL(String hql, Object[] params);
/**
* 通过sql语句,查询结果映射成实体
* @param sql
* @param c 结果要映射的实体对象
* @return
*/
@SuppressWarnings("rawtypes")
List listEntityBySql(String sql,Class c);
/**
* 获取下一个主键,默认是从1开始递增,如果有特殊需求需要在dao实现中重写该方法
* @return
*/
public String next();
}
主键生成方法在该类的最底部,还有不完善的大家直接去修修补补,优化提升
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.Resource;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.orm.hibernate4.HibernateCallback;
import org.springframework.orm.hibernate4.HibernateTemplate;
import …….dao.GenericDao;
import …….idgenerator.IdGenerator;
import …….vo.ComboBox;
import …….vo.Pagination;
public class GenericDaoHibernate<T, PK extends Serializable> extends IdGenerator
implements GenericDao<T, PK> ,Runnable
{
private final Class<T> clazz;
protected HibernateTemplate hibernateTemplate;
@SuppressWarnings("unchecked")
public GenericDaoHibernate() {
clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
value = new AtomicInteger(getInitial());
}
public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}
@Resource()
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
@Override
public T findById(PK id) {
return this.hibernateTemplate.get(clazz, id);
}
@SuppressWarnings("unchecked")
@Override
public List<T> findAll() {
return (List<T>) this.hibernateTemplate.find("from " + clazz.getName());
}
@Override
public T save(T entity) {
this.hibernateTemplate.persist(entity);
return entity;
}
@Override
public void update(T entity) {
this.hibernateTemplate.merge(entity);
}
@Override
public void delete(T entity) {
this.hibernateTemplate.delete(entity);
}
/**
* 根据HQL语句和查询条件,获得一个对象
* 例:分页时查询出总的记录数
*
* @param hql
* @param params
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private Object queryObjectByHQL(final String hql, final Object[] params) {
Object obj = this.hibernateTemplate.execute(new HibernateCallback() {
@Override
public Object doInHibernate(Session session) throws HibernateException {
Query query = session.createQuery(hql);
if (params != null) {
for (int i = 0; i < params.length; i++) {
query.setParameter(i, params[i]);
}
}
return query.uniqueResult();
}
});
return obj;
}
/**
* 根据SQL语句和查询条件,获得一个对象
* 例:分页时查询出总的记录数
*
* @param hql
* @param params
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private Object queryObjectBySQL(final String sql, final Object[] params) {
Object obj = this.hibernateTemplate.execute(new HibernateCallback() {
@Override
public Object doInHibernate(Session session) throws HibernateException {
Query query = session.createSQLQuery(sql);
if (params != null) {
for (int i = 0; i < params.length; i++) {
query.setParameter(i, params[i]);
}
}
return query.uniqueResult();
}
});
return obj;
}
@Override
public Long countByHQL(String hql, Object[] params) {
// 拼接成新的hql字符串,用于查询总共多少条数据, 如果有order by要截取掉,因为有的数据库不支持
String nhql = "select count(*) " + hql.split(" order by")[0];
return (Long) this.queryObjectByHQL(nhql, params); // 获得总的记录数
}
public Long countBySQL(String sql, Object[] params) {
// 拼接成新的hql字符串,用于查询总共多少条数据, 如果有order by要截取掉,因为有的数据库不支持
String nhql = "select count(*) from (" + sql.split(" order by")[0] + ")";
/*
* 获得总的记录数
* Hibernate 执行SQL语句的count函数返回类型
* oracle :BigDecimal
* db2 : Integer
*/
Object obj = this.queryObjectBySQL(nhql, params);
String objName = obj.getClass().getName();
if("java.math.BigDecimal".equals(objName)) {
BigDecimal bq = (BigDecimal) obj;
return bq.longValue();
}else if("java.lang.Integer".equals(objName)){
Integer bq = (Integer) this.queryObjectBySQL(nhql, params);
return bq.longValue();
}else {
return 0L;
}
}
@Override
public T getEntityByHQL(String hql, Object[] params)
{
@SuppressWarnings("unchecked")
List<T> list = (List<T>) this.hibernateTemplate.find(hql, params);
if (list != null && list.size() > 0)
{
return list.get(0);
}
else
{
return null;
}
}
@SuppressWarnings("unchecked")
@Override
public List<T> listEntityByHQL(String hql, Object[] params)
{
return (List<T>) this.hibernateTemplate.find(hql, params);
}
/**
* 分页查询
*
* @param hql
* @param params
* @param pageSize
* @param pageNumber
* @param totalCount
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private Pagination getPaginationByHQL(final String hql, final Object[] params, final Integer pageSize,
final Integer pageNumber, final Long totalCount) {
return (Pagination) this.hibernateTemplate.execute(new HibernateCallback() {
@Override
public Object doInHibernate(Session session) throws HibernateException {
Pagination pagination = new Pagination(pageSize, pageNumber, totalCount);
Query query = session.createQuery(hql);
if (params != null) {
for (int i = 0; i < params.length; i++) {
query.setParameter(i, params[i]);
}
}
query.setFirstResult(pageSize * (pageNumber - 1));
query.setMaxResults(pageSize);
pagination.setList(query.list());
return pagination;
}
});
}
/**
* 分页查询
*
* @param sql
* @param params
* @param pageSize
* @param pageNumber
* @param totalCount
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private Pagination getPaginationBySQL(final String sql, final Object[] params, final Integer pageSize,
final Integer pageNumber, final Long totalCount) {
return (Pagination) this.hibernateTemplate.execute(new HibernateCallback() {
@Override
public Object doInHibernate(Session session) throws HibernateException {
Pagination pagination = new Pagination(pageSize, pageNumber, totalCount);
Query query = session.createSQLQuery(sql);
if (params != null) {
for (int i = 0; i < params.length; i++) {
query.setParameter(i, params[i]);
}
}
query.setFirstResult(pageSize * (pageNumber - 1));
query.setMaxResults(pageSize);
pagination.setList(query.list());
return pagination;
}
});
}
@Override
public Pagination listEntityByHQL(String hql, Object[] params, Integer pageSize, Integer pageNumber) {
long totalCount = this.countByHQL(hql, params);
return this.getPaginationByHQL(hql, params, pageSize, pageNumber, totalCount);
}
@Override
public Pagination listEntityBySQL(String hql, Object[] params, Integer pageSize, Integer pageNumber) {
long totalCount = this.countBySQL(hql, params);
return this.getPaginationBySQL(hql, params, pageSize, pageNumber, totalCount);
}
@Override
public Pagination listEntityByHQL1(String hql, Object[] params, Integer pageSize, Integer pageNumber) {
String nhql = "select count(*) from (select distinct ij.docserialnum,ir.docname,ir.scanuser,ir.orgcode,ir.cartonno,ir.boxno,to_char(ir.scantime, 'yyyy-mm-dd hh24:mi:ss'),count(ir.docname) " + hql.substring((hql.split("from")[0].length()-1)<0?0:(hql.split("from")[0].length()-1), hql.length()-1).split(" order by")[0]+")";
Integer totalCount = Integer.parseInt(this.queryObject1(nhql, params).toString());
return this.getPagination1(hql, params, pageSize, pageNumber, totalCount);
}
@Override
public Pagination listEntityByHQLbox(String hql, Object[] params, Integer pageSize, Integer pageNumber) {
String nhql = "select count(*) from (select distinct ij.docserialnum,to_char(ij.creationtime, 'yyyy-mm-dd hh24:mi:ss'),ij.maindocname,ir.scanuser,ir.orgcode,ir.cartonno,ir.boxno,count(ir.docname) " + hql.substring((hql.split("from")[0].length()-1)<0?0:(hql.split("from")[0].length()-1), hql.length()-1).split(" order by")[0]+")";
Integer totalCount = Integer.parseInt(this.queryObject1(nhql, params).toString());
return this.getPagination1(hql, params, pageSize, pageNumber, totalCount);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public Object queryObject1(final String hql, final Object[] params) {
Object obj = this.hibernateTemplate.execute(new HibernateCallback() {
@Override
public Object doInHibernate(Session session) throws HibernateException {
Query query = session.createSQLQuery(hql);
if (params != null) {
for (int i = 0; i < params.length; i++) {
query.setParameter(i, params[i]);
}
}
return query.uniqueResult();
}
});
return obj;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public Pagination getPagination1(final String hql, final Object[] params, final Integer pageSize, final Integer pageNumber, final Integer totalCount) {
return (Pagination) this.hibernateTemplate.execute(new HibernateCallback() {
@Override
public Object doInHibernate(Session session) throws HibernateException {
Pagination pagination = new Pagination(pageSize, pageNumber, totalCount);
Query query = session.createSQLQuery(hql);
if (params != null) {
for (int i = 0; i < params.length; i++) {
query.setParameter(i, params[i]);
}
}
query.setFirstResult(pageSize * (pageNumber - 1));
query.setMaxResults(pageSize);
pagination.setList(query.list());
return pagination;
}
});
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private Integer updateEntity(final String hql, final Object[] params) {
Integer i = (Integer) this.hibernateTemplate.execute(new HibernateCallback() {
@Override
public Object doInHibernate(Session session) throws HibernateException {
Query query = session.createQuery(hql);
if (params != null) {
for (int i = 0; i < params.length; i++) {
query.setParameter(i, params[i]);
}
}
Integer count = query.executeUpdate();
return count;
}
});
return i;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private Integer updateEntityBySQL(final String sql, final Object[] params) {
Integer i = (Integer) this.hibernateTemplate.execute(new HibernateCallback() {
@Override
public Object doInHibernate(Session session) throws HibernateException {
Query query = session.createSQLQuery(sql);
if (params != null) {
for (int i = 0; i < params.length; i++) {
query.setParameter(i, params[i]);
}
}
Integer count = query.executeUpdate();
return count;
}
});
return i;
}
@Override
public Integer updateByHQL(String hql, Object[] params) {
return updateEntity(hql, params);
}
@Override
public Integer updateBySQL(String sql, Object[] params) {
return updateEntityBySQL(sql, params);
}
@SuppressWarnings("unchecked")
@Override
public List<Object[]> listEntityBySelect(String hql, Object[] params) {
return (List<Object[]>) this.hibernateTemplate.find(hql, params);
}
@Override
public List<ComboBox> listFieldByHQL(String hql, Object[] params) {
@SuppressWarnings("unchecked")
List<String> objects = (List<String>) hibernateTemplate.find(hql, params);
List<ComboBox> lists = new ArrayList<ComboBox>();
for (String obj: objects) {
ComboBox cb = new ComboBox();
cb.setText(obj);
cb.setValue(obj);
lists.add(cb);
}
return lists;
}
@SuppressWarnings("rawtypes")
@Override
public List listEntityBySql(String sql, Class c) {
SQLQuery query=hibernateTemplate.getSessionFactory().getCurrentSession().createSQLQuery(sql).addEntity(c);
return query.list();
}
@Override
public void run()
{
while (true)
{
try
{
Thread.sleep(1000 * getRollingInterval());
}
catch (InterruptedException e)
{
e.printStackTrace();
}
String now = new SimpleDateFormat("yyyyMMddHHmm").format(new Date());
if (!now.equals(time)){
lock.writeLock().lock();
time = now;
value.set(getInitial());
lock.writeLock().unlock();
}
}
}
@Override
public String next()
{
lock.readLock().lock();
int index = value.getAndIncrement();
if(index==999999999)
{
value.set(0);
}
String num = String.valueOf(index);
time = String.valueOf(System.currentTimeMillis());
StringBuilder number = new StringBuilder();
int maxLength = 9;
if(num.length()<maxLength)
{
for(int i=0;i<(maxLength-num.length());i++)
{
number.append("0");
}
}
number.append(num);
StringBuffer sb = new StringBuffer(getPrefix()).append(getSplitString()).append(time).append(getSplitString()).append(number.toString());
lock.readLock().unlock();
return sb.toString();
}
}
每个dao大体情况:
@Repository("XXXDao")
public class XXXDaoHibernate extends GenericDaoHibernate<XXX(这个是实体), String> implements
XXXDao {
//这里有需要就重写next(),没需要直接在service层用XXXDao.next()调用拿到主键
}