【Java 新建项目】使用程序对新项目的各个实体 创建Dao、DaoImpl、Service、ServiceImpl层的文件

时间:2020-12-15 20:05:55

优化之后的步骤:

1.第一步 生成各层文件夹,并且创建GenericDao.java等基础dao【基础dao中涉及到的包名等自行更改】

2.第二步 生成各个实体对应的Dao等层文件

首先给出基本Dao层代码:【将这些类保存为文件,放在固定的位置】

GenericDao.java

 package com.agen.dao;

 import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map; import org.hibernate.Criteria;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria; import com.github.pagehelper.PageInfo; public interface GenericDao<T, PK extends Serializable> {
/**
* 查询全部,可以排序
* @param orderBy
* @param isAsc
* @return List<T>
*/
public List<T> list(Criteria criteria); /**
* 查询全部,可以排序
* @param orderBy
* @param isAsc
* @return List<T>
*/
public List<T> list(String orderBy, boolean isAsc); /**
* 离线查询
* @param criteria
* @return List<T>
*/
public List<T> list(DetachedCriteria criteria); /**
* 根据Criteria查询条件,获取总数
* @param criteria
* @return int
* @throws SecurityException
* @throws NoSuchFieldException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public int countAll(Criteria criteria); /**
* 获取总数(默认为entityClass) 即查询总条数
* @return int
*/
public int countAll(); /**
* 根据I判断是否存在
* @param id
* @return boolean
*/
public boolean exists(PK id); /**
* 保存实体
* @param t 实体参数
*/
public void save(T t); /**
* 保存或者更新实体
* @param t 实体
*/
public void saveOrUpdate(T t); /**
* 加载实体的通过load方法
* @param id 实体的id
* @return 查询出来的实体
*/
public T load(PK id); /**
* 合并实体
* @param entity
*/
public void merge(T entity); /**
* 查找全部
*/
public List<T> findAll(); /**
* 通过get方法加载实体的
* @param id 实体的id
* @return 查询出来的实体
*/
public T get(PK id); /**
* contains
* @param t 实体
* @return 是否包含
*/
public boolean contains(T t); /**
* delete
* @param t
* 删除实体
*/
public void delete(T t); /**
* 根据ID删除数据
* @param Id 实体id
* @return 是否删除成功
*/
public boolean deleteById(PK Id); /**
* 删除所有
* @param entities 实体的Collection集合
*/
public void deleteAll(Collection<T> entities); /**
* 执行Hql语句 要求 hql中参数顺序与可变参数 中参数顺序相一致
* @param hqlString hql
* @param values 不定参数数组
*/
public void queryHql(String hqlString, Object... values); /**
* 执行Sql语句(不建议用,影响扩展)
* @param sqlString sql
* @param values 不定参数数组
*/
public void querySql(String sqlString, Object... values); /**
* 根据HQL语句查找唯一实体
*
* @param hqlString HQL语句
* @param values 不定参数的Object数组
* @return 查询实体
*/
public T getByHQL(String hqlString, Object... values); /**
* 根据SQL语句查找唯一实体(不建议用,影响扩展)
* @param sqlString SQL语句
* @param values 不定参数的Object数组
* @return 查询实体
*/ /**
* 根据HQL语句,得到对应的list
* @param hqlString HQL语句
* @param values 不定参数的Object数组
* @return 查询多个实体的List集合
*/
public List<T> getListByHQL(String hqlString, Object... values); /**
* 根据SQL语句,得到对应的list(不建议用,影响扩展)
* @param sqlString HQL语句
* @param values 不定参数的Object数组
* @return 查询多个实体的List集合
*/
public List<T> getListBySQL(String sqlString, Object... values); /**
* refresh 刷新实体,强制与数据库两步 refresh方法应该是数据库的数据更新到本地的person实体中,而不是本地person更新数据到数据库中 也就是执行refresh方法是更新了java代码中变量的数据值
* @param t 实体
*/
public void refresh(T t); /**
* update
* @param t
* 更新的是数据库中的数据
*/
public void update(T t); /**
* 根据HQL得到记录数
* @param hql HQL语句
* @param values 不定参数的Object数组
* @return 记录总数
*/
public Long countByHql(String hql, Object... values); /**
* HQL分页查询
*
* @param hql HQL语句
* @param countHql 查询记录条数的HQL语句
* @param pageNo 下一页
* @param pageSize 一页总条数
* @param values 不定Object数组参数
* @return PageResults的封装类,里面包含了页码的信息以及查询的数据List集合
*/
public PageInfo<T> findPageByHql(String hql, String countHql, int pageNo, int pageSize, Object... values); /**
* 按属性查找对象列表,匹配方式为相等
* @param propertyName
* @param value
* @return List<T>
*/
public List<T> list(String propertyName, Object value); /**
* 根据criterion查询条件获取数据列表
* @param criterion
* @return List<T>
*/
public List<T> list(Criterion criterion); /**
* 按Criteria查询对象列表
* @param criterions
* @return List<T>
*/
public List<T> list(Criterion... criterions); /**
* 按属性查找唯一对象,匹配方式为相等
* @param propertyName
* @param value
* @return T
*/
public T uniqueResult(String propertyName, Object value); /**
* 按Criteria查询唯一对象
* @param criterions
* @return T
*/
public T uniqueResult(Criterion... criterions); /**
* 按Criteria查询唯一对象
* @param criteria
* @return T
*/
public T uniqueResult(Criteria criteria); /**
* 按criteria查询某个Integer类型的字段
* @param criteria
* @return
*/
public Integer uniqueResultInt(Criteria criteria); /**
* 为Criteria添加distinct transformer
* @param criteria
* @return Criteria
*/
public Criteria distinct(Criteria criteria); /**
* 刷新session
*/
public void flush(); /**
* 清空session
*/
public void clear(); /**
* 创建Criteria实例
*/
public Criteria createCriteria(); /**
* 根据Criterion条件创建Criteria
* @param criterions
* @return Criteria
*/
public Criteria createCriteria(Criterion... criterions); /**
* 分页查询Criteria
* @param criteria
* @param pageNo 下页页码
* @param pageSize 页面数据量
* @return List<T>
*/
public List<T> findPage(Criteria criteria, int pageNo, int pageSize); /**
* 分页查询Criteria
* @param criteria
* @param pageNo
* @param pageSize
* @return PageInfo<T>
* @throws SecurityException
* @throws NoSuchFieldException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public PageInfo<T> findQuery(Criteria criteria, int pageNo, int pageSize); /**
*
* @param hql
* @param pageNo
* @param pageSize
* @param map
* @return List<T>
*/
public List<T> findQuery(String hql, int pageNo, int pageSize, Map<?, ?> map);
}

GenericDaoImpl.java

 package com.agen.dao.impl;

 import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry; import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.QueryException;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.internal.CriteriaImpl;
import org.hibernate.internal.CriteriaImpl.Subcriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert; import java.lang.reflect.ParameterizedType; import com.agen.dao.GenericDao;
import com.github.pagehelper.PageInfo; public class GenericDaoImpl<T, PK extends Serializable> implements GenericDao<T, PK> {
/**
* 不建议直接使用
*/
@Autowired
private SessionFactory sessionFactory; public Session getSession() {
// 需要开启事物,才能得到CurrentSession
return sessionFactory.getCurrentSession();
} protected Class<T> entityClass; protected Class getEntityClass() {
if (entityClass == null) {
if(((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments().length > 0) {
entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
}
return entityClass;
} public SessionFactory getSessionFactory() {
return sessionFactory;
} public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
} @Override
public Criteria createCriteria() {
return getSession().createCriteria(getEntityClass());
} @Override
public void save(T t) {
this.getSession().save(t);
} @Override
public void saveOrUpdate(T t) {
Assert.notNull(t);
this.getSession().saveOrUpdate(t);
} @Override
public T load(PK id) {
Assert.notNull(id);
T load = (T) this.getSession().load(getEntityClass(), id);
return load;
} @Override
public T get(PK id) {
Assert.notNull(id);
T load = (T) this.getSession().get(getEntityClass(), id);
return load;
} @Override
public boolean contains(T t) {
Assert.notNull(t);
return this.getSession().contains(t);
} @Override
public void delete(T t) {
Assert.notNull(t);
this.getSession().delete(t);
} @Override
public boolean deleteById(PK Id) {
Assert.notNull(Id);
T t = get(Id);
if (t == null) return false;
delete(t);
return true;
} @Override
public void deleteAll(Collection<T> entities) {
Assert.notNull(entities);
for (Object entity : entities) {
this.getSession().delete(entity);
}
} @Override
public void queryHql(String hqlString, Object... values) {
Query query = this.getSession().createQuery(hqlString);
if (values != null) {
for (int i = 0; i < values.length; i++) {
query.setParameter(i, values[i]);
}
}
query.executeUpdate();
} /**
* 根据hql 和 map集合中的数据 进行相对应的 insert update delete操作
* @param hqlString
* @param paras
*/
public void queryHql(String hqlString, Map<String, Object> paras) {
Query query = this.getSession().createQuery(hqlString);
if (paras != null) {
for (Entry<String, Object> en : paras.entrySet()) {
query.setParameter(en.getKey(), en.getValue());
}
}
query.executeUpdate();
} @Override
public void querySql(String sqlString, Object... values) {
Query query = this.getSession().createSQLQuery(sqlString);
if (values != null) {
for (int i = 0; i < values.length; i++) {
query.setParameter(i, values[i]);
}
}
query.executeUpdate();
} @Override
public T getByHQL(String hqlString, Object... values) {
Query query = this.getSession().createQuery(hqlString);
if (values != null) {
for (int i = 0; i < values.length; i++) {
query.setParameter(i, values[i]);
}
}
return (T) query.uniqueResult();
} @Override
public List<T> getListByHQL(String hqlString, Object... values) {
Query query = this.getSession().createQuery(hqlString);
if (values != null) {
for (int i = 0; i < values.length; i++) {
query.setParameter(i, values[i]);
}
}
return query.list();
} @Override
public List<T> getListBySQL(String sqlString, Object... values) {
Query query = this.getSession().createSQLQuery(sqlString);
if (values != null) {
for (int i = 0; i < values.length; i++) {
query.setParameter(i, values[i]);
}
}
return query.list();
} @Override
public void refresh(T t) {
this.getSession().refresh(t);
} @Override
public void update(T t) {
this.getSession().update(t);
} @Override
public Long countByHql(String hql, Object... values) {
Query query = this.getSession().createQuery(hql);
if (values != null) {
for (int i = 0; i < values.length; i++) {
query.setParameter(i, values[i]);
}
}
return (Long) query.uniqueResult();
} @Override
public PageInfo<T> findPageByHql(String hql, String countHql, int pageNo, int pageSize, Object... values) {
PageInfo<T> retValue = new PageInfo<T>();
Query query = this.getSession().createQuery(hql);
if (values != null) {
for (int i = 0; i < values.length; i++) {
query.setParameter(i, values[i]);
}
}
int currentPage = pageNo > 1 ? pageNo : 1;
retValue.setPages(currentPage);
retValue.setPageSize(pageSize);
if (countHql == null) {
ScrollableResults results = query.scroll();
results.last();
retValue.setTotal(results.getRowNumber() + 1);
} else {
Long count = countByHql(countHql, values);
retValue.setTotal(count.intValue());
}
List<T> itemList = query.setFirstResult((currentPage - 1) * pageSize).setMaxResults(pageSize).list();
if (itemList == null) {
itemList = new ArrayList<T>();
}
retValue.setList(itemList);
return retValue;
} @Override
public void merge(T entity) {
// TODO Auto-generated method stub
getSession().merge(entity);
} @Override
public boolean exists(PK id) {
return null != get(id);
} @Override
public int countAll() {
Criteria criteria = createCriteria();
return Integer.valueOf(criteria.setProjection(Projections.rowCount()).uniqueResult().toString());
} @Override
public int countAll(Criteria criteria) {
criteria.setProjection(null);
return Integer.valueOf(criteria.setProjection(Projections.rowCount()).uniqueResult().toString());
} @Override
public List<T> list(Criteria criteria) {
return criteria.list();
} @Override
public List<T> list(DetachedCriteria criteria) {
return (List<T>) list(criteria.getExecutableCriteria(getSession()));
} @Override
public List<T> list(String orderBy, boolean isAsc) {
Criteria criteria = createCriteria();
if (isAsc) {
criteria.addOrder(Order.asc(orderBy));
} else {
criteria.addOrder(Order.desc(orderBy));
}
return criteria.list();
} @Override
public List<T> list(String propertyName, Object value) {
Criterion criterion = Restrictions.like(propertyName, "%"+ value +"%");
return list(criterion);
} @Override
public List<T> list(Criterion criterion) {
Criteria criteria = createCriteria();
criteria.add(criterion);
return criteria.list();
} @Override
public List<T> list(Criterion... criterions) {
return createCriteria(criterions).list();
} @Override
public T uniqueResult(String propertyName, Object value) {
Criterion criterion = Restrictions.eq(propertyName, value);
return (T) createCriteria(criterion).uniqueResult();
} @Override
public T uniqueResult(Criterion... criterions) {
Criteria criteria = createCriteria(criterions);
return uniqueResult(criteria);
} @Override
public T uniqueResult(Criteria criteria) {
return (T) criteria.uniqueResult();
} @Override
public Integer uniqueResultInt(Criteria criteria) {
return (Integer) criteria.uniqueResult();
} @Override
public Criteria distinct(Criteria criteria) {
criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
return criteria;
} @Override
public void flush() {
getSession().flush();
} @Override
public void clear() {
getSession().clear();
} @Override
public Criteria createCriteria(Criterion... criterions) {
Criteria criteria = createCriteria();
for (Criterion c : criterions) {
criteria.add(c);
}
return criteria;
} @Override
public List<T> findPage(Criteria criteria, int pageNo, int pageSize) {
criteria.setFirstResult((pageNo - 1) * pageSize);
criteria.setMaxResults(pageSize);
return list(criteria);
} @Override
public PageInfo<T> findQuery(Criteria criteria, int pageNo, int pageSize) {
try {
Assert.isTrue(pageNo >= 1, "pageNO should start from 1");
while(criteria instanceof Subcriteria){
criteria = ((Subcriteria)criteria).getParent();
}
//拆分order by子句
while(criteria instanceof Subcriteria){
criteria = ((Subcriteria)criteria).getParent();
}
Field field = CriteriaImpl.class.getDeclaredField("orderEntries");
field.setAccessible(true);
List<?> orderEntrys = (List<?>) field.get(criteria);
field.set(criteria, new ArrayList());
//统计总数
long totalCount = countAll(criteria);
criteria.setProjection(null);
//统计完了再把order by子句加上 这样保证了sql语句不会出错
field.set(criteria, orderEntrys);
List<T> list = findPage(criteria, pageNo, pageSize);
if (totalCount < 1) {
return new PageInfo<T>();
}
PageInfo<T> page = new PageInfo<T>();
page.setPageNum(pageNo);
page.setTotal(totalCount);
page.setPages((int) (totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1));
page.setPageSize(pageSize);
page.setList(list);
return page;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
throw new QueryException("查询出错!");
} } @Override
public List<T> findQuery(String hql, int pageNo, int pageSize, Map<?, ?> map) {
// TODO Auto-generated method stub
if(null == hql) return null;
Query query = getSession().createQuery(hql);
for (Entry<?, ?> en : map.entrySet()) {
query.setParameter(en.getKey().toString(), en.getValue());
}
if(pageNo > 0) query.setFirstResult(pageNo);
if(pageSize > 0) query.setFirstResult(pageSize);
return query.list();
} @Override
public List<T> findAll() {
// TODO Auto-generated method stub
return createCriteria().list();
}
}

GenericService.java

 package com.agen.service;

 import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map; import org.hibernate.Criteria;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria; import com.github.pagehelper.PageInfo; public interface GenericService<T, PK extends Serializable> {
/**
* 查询全部,可以排序
* @param orderBy
* @param isAsc
* @return List<T>
*/
public List<T> list(Criteria criteria); /**
* 查询全部,可以排序
* @param orderBy
* @param isAsc
* @return List<T>
*/
public List<T> list(String orderBy, boolean isAsc); /**
* 离线查询
* @param criteria
* @return List<T>
*/
public List<T> list(DetachedCriteria criteria); /**
* 根据Criteria查询条件,获取总数
* @param criteria
* @return int
* @throws SecurityException
* @throws NoSuchFieldException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public int countAll(Criteria criteria); /**
* 获取总数(默认为entityClass) 即查询总条数
* @return int
*/
public int countAll(); /**
* 根据I判断是否存在
* @param id
* @return boolean
*/
public boolean exists(PK id); /**
* 保存实体
* @param t 实体参数
*/
public void save(T t); /**
* 保存或者更新实体
* @param t 实体
*/
public void saveOrUpdate(T t); /**
* 加载实体的通过load方法
* @param id 实体的id
* @return 查询出来的实体
*/
public T load(PK id); /**
* 合并实体
* @param entity
*/
public void merge(T entity); /**
* 查找全部
*/
public List<T> findAll(); /**
* 通过get方法加载实体的
* @param id 实体的id
* @return 查询出来的实体
*/
public T get(PK id); /**
* contains
* @param t 实体
* @return 是否包含
*/
public boolean contains(T t); /**
* delete
* @param t
* 删除实体
*/
public void delete(T t); /**
* 根据ID删除数据
* @param Id 实体id
* @return 是否删除成功
*/
public boolean deleteById(PK Id); /**
* 删除所有
* @param entities 实体的Collection集合
*/
public void deleteAll(Collection<T> entities); /**
* 执行Hql语句 要求 hql中参数顺序与可变参数 中参数顺序相一致
* @param hqlString hql
* @param values 不定参数数组
*/
public void queryHql(String hqlString, Object... values); /**
* 执行Sql语句(不建议用,影响扩展)
* @param sqlString sql
* @param values 不定参数数组
*/
public void querySql(String sqlString, Object... values); /**
* 根据HQL语句查找唯一实体
*
* @param hqlString HQL语句
* @param values 不定参数的Object数组
* @return 查询实体
*/
public T getByHQL(String hqlString, Object... values); /**
* 根据SQL语句查找唯一实体(不建议用,影响扩展)
* @param sqlString SQL语句
* @param values 不定参数的Object数组
* @return 查询实体
*/ /**
* 根据HQL语句,得到对应的list
* @param hqlString HQL语句
* @param values 不定参数的Object数组
* @return 查询多个实体的List集合
*/
public List<T> getListByHQL(String hqlString, Object... values); /**
* 根据SQL语句,得到对应的list(不建议用,影响扩展)
* @param sqlString HQL语句
* @param values 不定参数的Object数组
* @return 查询多个实体的List集合
*/
public List<T> getListBySQL(String sqlString, Object... values); /**
* refresh 刷新实体,强制与数据库两步 refresh方法应该是数据库的数据更新到本地的person实体中,而不是本地person更新数据到数据库中 也就是执行refresh方法是更新了java代码中变量的数据值
* @param t 实体
*/
public void refresh(T t); /**
* update
* @param t
* 更新的是数据库中的数据
*/
public void update(T t); /**
* 根据HQL得到记录数
* @param hql HQL语句
* @param values 不定参数的Object数组
* @return 记录总数
*/
public Long countByHql(String hql, Object... values); /**
* HQL分页查询
*
* @param hql HQL语句
* @param countHql 查询记录条数的HQL语句
* @param pageNo 下一页
* @param pageSize 一页总条数
* @param values 不定Object数组参数
* @return PageResults的封装类,里面包含了页码的信息以及查询的数据List集合
*/
public PageInfo<T> findPageByHql(String hql, String countHql, int pageNo, int pageSize, Object... values); /**
* 按属性查找对象列表,匹配方式为相等
* @param propertyName
* @param value
* @return List<T>
*/
public List<T> list(String propertyName, Object value); /**
* 根据criterion查询条件获取数据列表
* @param criterion
* @return List<T>
*/
public List<T> list(Criterion criterion); /**
* 按Criteria查询对象列表
* @param criterions
* @return List<T>
*/
public List<T> list(Criterion... criterions); /**
* 按属性查找唯一对象,匹配方式为相等
* @param propertyName
* @param value
* @return T
*/
public T uniqueResult(String propertyName, Object value); /**
* 按Criteria查询唯一对象
* @param criterions
* @return T
*/
public T uniqueResult(Criterion... criterions); /**
* 按Criteria查询唯一对象
* @param criteria
* @return T
*/
public T uniqueResult(Criteria criteria);
/**
* 按照criteria返回类型为Integer类型的某个字段的值
* @param criteria
* @return
*/
public Integer uniqueResultInt(Criteria criteria); /**
* 为Criteria添加distinct transformer
* @param criteria
* @return Criteria
*/
public Criteria distinct(Criteria criteria); /**
* 刷新session
*/
public void flush(); /**
* 清空session
*/
public void clear(); /**
* 创建Criteria实例
*/
public Criteria createCriteria(); /**
* 根据Criterion条件创建Criteria
* @param criterions
* @return Criteria
*/
public Criteria createCriteria(Criterion... criterions); /**
* 分页查询Criteria
* @param criteria
* @param pageNo 下页页码
* @param pageSize 页面数据量
* @return List<T>
*/
public List<T> findPage(Criteria criteria, int pageNo, int pageSize); /**
* 分页查询Criteria
* @param criteria
* @param pageNo
* @param pageSize
* @return PageInfo<T>
* @throws SecurityException
* @throws NoSuchFieldException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public PageInfo<T> findQuery(Criteria criteria, int pageNo, int pageSize); /**
*
* @param hql
* @param pageNo
* @param pageSize
* @param map
* @return List<T>
*/
public List<T> findQuery(String hql, int pageNo, int pageSize, Map<?, ?> map);
}

GenericServiceImpl.java

 package com.agen.service.impl;

 import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map; import org.hibernate.Criteria;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional; import com.agen.dao.impl.GenericDaoImpl;
import com.agen.service.GenericService;
import com.github.pagehelper.PageInfo; @Transactional
public class GenericServiceImpl<T, PK extends Serializable> implements GenericService<T, PK> { private GenericDaoImpl<T, PK> dao;
/**
* 设值注入Dao
* @param dao
*/
@Autowired
public void setDao(GenericDaoImpl<T, PK> dao) {
this.dao = dao;
} @Override
public List<T> list(Criteria criteria) {
// TODO Auto-generated method stub
return dao.list(criteria);
} @Override
public List<T> list(String orderBy, boolean isAsc) {
// TODO Auto-generated method stub
return dao.list(orderBy, isAsc);
} @Override
public List<T> list(DetachedCriteria criteria) {
// TODO Auto-generated method stub
return dao.list(criteria);
} @Override
public int countAll(Criteria criteria) {
// TODO Auto-generated method stub
return dao.countAll(criteria);
} @Override
public int countAll() {
// TODO Auto-generated method stub
return dao.countAll();
} @Override
public boolean exists(PK id) {
// TODO Auto-generated method stub
return dao.exists(id);
} @Override
@Transactional(propagation = Propagation.REQUIRED)
public void save(T t) {
// TODO Auto-generated method stub
dao.save(t);
} @Override
@Transactional(propagation = Propagation.REQUIRED)
public void saveOrUpdate(T t) {
// TODO Auto-generated method stub
dao.saveOrUpdate(t);
} @Override
@Transactional(propagation = Propagation.REQUIRED)
public T load(PK id) {
// TODO Auto-generated method stub
return dao.load(id);
} @Override
@Transactional(propagation = Propagation.REQUIRED)
public void merge(T entity) {
// TODO Auto-generated method stub
dao.merge(entity);
} @Override
public List<T> findAll() {
// TODO Auto-generated method stub
return dao.findAll();
} @Override
@Transactional(propagation = Propagation.REQUIRED)
public T get(PK id) {
// TODO Auto-generated method stub
return dao.get(id);
} @Override
public boolean contains(T t) {
// TODO Auto-generated method stub
return dao.contains(t);
} @Override
public void delete(T t) {
// TODO Auto-generated method stub
dao.delete(t);
} @Override
@Transactional(propagation = Propagation.REQUIRED)
public boolean deleteById(PK Id) {
// TODO Auto-generated method stub
return dao.deleteById(Id);
} @Override
public void deleteAll(Collection<T> entities) {
// TODO Auto-generated method stub
dao.deleteAll(entities);
} @Override
public void queryHql(String hqlString, Object... values) {
// TODO Auto-generated method stub
dao.queryHql(hqlString, values);
} @Override
public void querySql(String sqlString, Object... values) {
// TODO Auto-generated method stub
dao.querySql(sqlString, values);
} @Override
public T getByHQL(String hqlString, Object... values) {
// TODO Auto-generated method stub
return dao.getByHQL(hqlString, values);
} @Override
public List<T> getListByHQL(String hqlString, Object... values) {
// TODO Auto-generated method stub
return dao.getListByHQL(hqlString, values);
} @Override
public List<T> getListBySQL(String sqlString, Object... values) {
// TODO Auto-generated method stub
return dao.getListBySQL(sqlString, values);
} @Override
public void refresh(T t) {
// TODO Auto-generated method stub
dao.refresh(t);
} @Override
@Transactional(propagation = Propagation.REQUIRED)
public void update(T t) {
// TODO Auto-generated method stub
dao.update(t);
} @Override
public Long countByHql(String hql, Object... values) {
// TODO Auto-generated method stub
return dao.countByHql(hql, values);
} @Override
public PageInfo<T> findPageByHql(String hql, String countHql, int pageNo,
int pageSize, Object... values) {
// TODO Auto-generated method stub
return dao.findPageByHql(hql, countHql, pageNo, pageSize, values);
} @Override
public List<T> list(String propertyName, Object value) {
// TODO Auto-generated method stub
return dao.list(propertyName, value);
} @Override
public List<T> list(Criterion criterion) {
// TODO Auto-generated method stub
return dao.list(criterion);
} @Override
public List<T> list(Criterion... criterions) {
// TODO Auto-generated method stub
return dao.list(criterions);
} @Override
public T uniqueResult(String propertyName, Object value) {
// TODO Auto-generated method stub
return dao.uniqueResult(propertyName, value);
} @Override
public T uniqueResult(Criterion... criterions) {
// TODO Auto-generated method stub
return dao.uniqueResult(criterions);
} @Override
@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public T uniqueResult(Criteria criteria) {
// TODO Auto-generated method stub
return dao.uniqueResult(criteria);
} @Override
@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public Integer uniqueResultInt(Criteria criteria){
return dao.uniqueResultInt(criteria);
} @Override
public Criteria distinct(Criteria criteria) {
// TODO Auto-generated method stub
return dao.distinct(criteria);
} @Override
public void flush() {
// TODO Auto-generated method stub
dao.flush();
} @Override
public void clear() {
// TODO Auto-generated method stub
dao.clear();
} @Override
public Criteria createCriteria() {
// TODO Auto-generated method stub
return dao.createCriteria();
} @Override
public Criteria createCriteria(Criterion... criterions) {
// TODO Auto-generated method stub
return dao.createCriteria(criterions);
} @Override
public List<T> findPage(Criteria criteria, int pageNo, int pageSize) {
// TODO Auto-generated method stub
return dao.findPage(criteria, pageNo, pageSize);
} @Override
public PageInfo<T> findQuery(Criteria criteria, int pageNo, int pageSize) {
// TODO Auto-generated method stub
return dao.findQuery(criteria, pageNo, pageSize);
} @Override
public List<T> findQuery(String hql, int pageNo, int pageSize, Map<?, ?> map) {
// TODO Auto-generated method stub
return dao.findQuery(hql, pageNo, pageSize, map);
} }

我将这几个文件保存在如下:

【Java  新建项目】使用程序对新项目的各个实体 创建Dao、DaoImpl、Service、ServiceImpl层的文件

我们看到实体包下的各个实体:

【Java  新建项目】使用程序对新项目的各个实体 创建Dao、DaoImpl、Service、ServiceImpl层的文件

接下来  自动生成每一层的各个实体对应的相对应的代码文件:【注意在执行之前,查看基础文件位置是否正确/注意基础文件中关于工作包的代码 是否正确】

 package com.sxd.utils;

 import java.io.File;
import java.io.FileWriter;
import java.io.IOException; import org.junit.Test;
import org.springframework.util.FileCopyUtils;
/**
* 生成dao 、service等代码
* @author Administrator
*
*/
public class CreateJava { //包名 前半部分[java文件中内容]
private String packPath = "package com.sxd";
//包名 中间部分 例如:com.sxd.entity
private String middlePath = "sxd";
//项目名 用于生成文件的路径
private String productName = "shiro-first";
//dao service等基础的文件存放的路径
private String DaoServicePath = "F:/workspace2/DaoService"; @Test
public void mainTest() throws IOException{
createFiles();//第一步 生成各层文件夹,并从固定位置copy 基础dao,service文件
justCreateJava();//第二步 生成各个实体对应的Dao等层文件
} public void justCreateJava() throws IOException{
File file = new File("F:/workspace2/"+productName+"/src/main/java/com/"+middlePath+"/entity");
File []list = file.listFiles();
for (File file2 : list) {
String fileName = file2.getName().substring(0,file2.getName().lastIndexOf("."));
createDao(fileName);
createDaoImpl(fileName);
createService(fileName);
createServiceImpl(fileName);
}
}
/**
* 创建Dao层
* @param fileName
* @throws IOException
*/
public void createDao(String fileName) throws IOException{
//拼接 DaoImpl内容
String content = packPath+".dao;\r\n"
+ "\r\n"
+ "import com."+middlePath+".entity."+fileName+";\r\n"
+ "public interface "+fileName+"Dao extends GenericDao<"+fileName+", String> {\r\n"
+ "\r\n"
+ "}"; //指定将Dao文件生成到对应的指定位置
FileWriter writer = new FileWriter(new File("F:/workspace2/"+productName+"/src/main/java/com/"+middlePath+"/dao/"+fileName+"Dao.java"));
writer.write(content);
writer.close();
} /**
* 创建DaoImpl层
*/
public void createDaoImpl(String fileName) throws IOException{
//拼接 DaoImpl内容
String content = packPath+".dao.Impl;\r\n"
+ "\r\n"
+ "import org.springframework.stereotype.Repository;\r\n"
+ "import com."+middlePath+".dao."+fileName+"Dao;\r\n"
+ "import com."+middlePath+".entity."+fileName+";\r\n"
+ "@Repository \r\n"
+ "public class "+fileName+"DaoImpl extends GenericDaoImpl<"+fileName+", String> implements "+fileName+"Dao {\r\n"
+ "\r\n"
+ "}"; //指定将DaoImpl文件生成到对应的指定位置
FileWriter writer = new FileWriter(new File("F:/workspace2/"+productName+"/src/main/java/com/"+middlePath+"/dao/impl/"+fileName+"DaoImpl.java"));
writer.write(content);
writer.close();
} /**
* 创建 Service层
* @param fileName
* @throws IOException
*/
public void createService(String fileName) throws IOException{
//拼接Service内容
String content = packPath+".service;\r\n"
+ "import com."+middlePath+".entity."+fileName+";\r\n"
+ "public interface "+fileName+"Service extends GenericService<"+fileName+", String> {\r\n"
+ "\r\n"
+ "}"; FileWriter writer = new FileWriter(new File("F:/workspace2/"+productName+"/src/main/java/com/"+middlePath+"/service/"+fileName+"Service.java"));
writer.write(content);
writer.close();
} /**
* 创建ServiceImpl
* @throws IOException
*/
public void createServiceImpl(String fileName) throws IOException{
//拼接Service内容
String content = packPath+".service.Impl;\r\n"
+ "import org.springframework.beans.factory.annotation.Autowired;\r\n"
+ "import org.springframework.stereotype.Service;\r\n"
+ "import com."+middlePath+".dao."+fileName+"Dao;\r\n"
+ "import com."+middlePath+".entity."+fileName+";\r\n"
+ "import com."+middlePath+".service."+fileName+"Service;\r\n"
+ "@Service \r\n"
+ "public class "+fileName+"ServiceImpl extends GenericServiceImpl<"+fileName+", String> implements "+fileName+"Service {\r\n"
+ "\r\n"
+ "@Autowired\r\n"
+ "private "+fileName+"Dao dao;\r\n"
+ "}";
FileWriter writer = new FileWriter(new File("F:/workspace2/"+productName+"/src/main/java/com/"+middlePath+"/service/impl/"+fileName+"ServiceImpl.java"));
writer.write(content);
writer.close();
} /**
* 有了entity之后,创建各层文件夹,同时将 GenericDao等基础类和接口实现
* @throws IOException
*/
public void createFiles() throws IOException{
String daoPath = "F:/workspace2/"+productName+"/src/main/java/com/"+middlePath+"/dao";
String servicePath = "F:/workspace2/"+productName+"/src/main/java/com/"+middlePath+"/service";
/**
* 上来先删除掉 如果存在的话
*/
delFolder(daoPath);
delFolder(servicePath); /**
* 创建文件夹
*/
File file = new File(daoPath);
file.mkdirs();
File file2 = new File(servicePath);
file2.mkdirs();
File file3 = new File(daoPath+"/Impl");
file3.mkdirs();
File file4 = new File(servicePath+"/Impl");
file4.mkdirs();
copyDaoAndServiceFile(daoPath,servicePath); } //删除文件夹
//param folderPath 文件夹完整绝对路径 public void delFolder(String folderPath) {
try {
delAllFile(folderPath); //删除完里面所有内容
String filePath = folderPath;
filePath = filePath.toString();
java.io.File myFilePath = new java.io.File(filePath);
myFilePath.delete(); //删除空文件夹
} catch (Exception e) {
e.printStackTrace();
}
} //删除指定文件夹下所有文件
//param path 文件夹完整绝对路径
public boolean delAllFile(String path) {
boolean flag = false;
File file = new File(path);
if (!file.exists()) {
return flag;
}
if (!file.isDirectory()) {
return flag;
}
String[] tempList = file.list();
File temp = null;
for (int i = 0; i < tempList.length; i++) {
if (path.endsWith(File.separator)) {
temp = new File(path + tempList[i]);
} else {
temp = new File(path + File.separator + tempList[i]);
}
if (temp.isFile()) {
temp.delete();
}
if (temp.isDirectory()) {
delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
delFolder(path + "/" + tempList[i]);//再删除空文件夹
flag = true;
}
}
return flag;
} //将dao等基础文件 拷贝到 项目下固定包中
public void copyDaoAndServiceFile(String daoPath,String servicePath) throws IOException{
File file1 = new File(daoPath+"/GenericDao.java");
if(!file1.exists()){
file1.createNewFile();
}
File file2 = new File(daoPath+"/Impl/GenericDaoImpl.java");
if(!file2.exists()){
file2.createNewFile();
}
File file3 = new File(servicePath+"/GenericService.java");
if(!file3.exists()){
file3.createNewFile();
}
File file4 = new File(servicePath+"/Impl/GenericServiceImpl.java");
if(!file4.exists()){
file4.createNewFile();
}
FileCopyUtils.copy(new File(DaoServicePath+"/GenericDao.java"), file1);
FileCopyUtils.copy(new File(DaoServicePath+"/GenericDaoImpl.java"), file2);
FileCopyUtils.copy(new File(DaoServicePath+"/GenericService.java"), file3);
FileCopyUtils.copy(new File(DaoServicePath+"/GenericServiceImpl.java"), file4); }
}

生成完刷新

效果如下:

【Java  新建项目】使用程序对新项目的各个实体 创建Dao、DaoImpl、Service、ServiceImpl层的文件