基于SSH编写通用的DAO、Service、Action

1.创建项目


2.Dao

package cn.opencil.core.base.dao;

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

import cn.opencil.common.util.PageResult;
import cn.opencil.core.query.BaseQuery;


public interface BaseDao<T> {

	/**
	 * 分页的查询
	 * @param baseQuery
	 * @return
	 */
	public PageResult<T> getPageResult(final BaseQuery baseQuery);
	
	/**
	 * 查询某一张表的总的记录数
	 */
	public int getCount(final BaseQuery baseQuery);
	/**
	 * 添加
	 * @param t
	 */
	public void addEntry(T t);
	
	/**
	 * 查询一个
	 * @return
	 */
	public T getEntryById(Serializable id);
	
	/**
	 * 按ids查询
	 */
	public Set<T> getEntrysByIds(Serializable[] ids);
	
	/**
	 * 不分页的查询
	 * @return
	 */
	public Collection<T> getEntrys();
	
	/**
	 * 修改
	 * @param t
	 */
	public void updateEntry(T t);
	
	/**
	 * 根据ids删除一些数据
	 * @param ids
	 */
	public void deleteEntriesByIDS(Serializable[] ids);
	
	/**
	 * 根据id删除一条数据
	 * @param id
	 */
	public void deleteEntry(Serializable id);
	
}

3.DaoImpl

package cn.opencil.core.base.dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.metadata.ClassMetadata;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;

import cn.opencil.common.util.PageResult;
import cn.opencil.core.base.dao.BaseDao;
import cn.opencil.core.query.BaseQuery;

public class BaseDaoImpl<T> implements BaseDao<T> {

	Class entityClass;
	ClassMetadata classMetadata;
	@Resource(name = "hibernateTemplate")
	private HibernateTemplate hibernateTemplate;

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	@PostConstruct
	public void init() {
		this.classMetadata = this.hibernateTemplate//
				.getSessionFactory()//
				.getClassMetadata(entityClass);
	}

	public BaseDaoImpl() {
		Type superclass = this.getClass().getGenericSuperclass();
		ParameterizedType type = (ParameterizedType) superclass;
		Type[] args = type.getActualTypeArguments();
		entityClass = (Class) ((null != args && args.length > 0) ? args[0]
				: null);
	}

	@Override
	public void addEntry(T t) {
		this.hibernateTemplate.save(t);
	}

	@Override
	public T getEntryById(Serializable id) {

		return (T) this.hibernateTemplate.get(entityClass, id);
	}

	@Override
	public Collection<T> getEntrys() {

		return this.hibernateTemplate.find("from "
				+ this.entityClass.getSimpleName());
	}

	@Override
	public void updateEntry(T t) {
		this.hibernateTemplate.update(t);
	}

	@Override
	public void deleteEntriesByIDS(Serializable[] ids) {
		StringBuilder builder = new StringBuilder();
		for (int i = 0; i < ids.length; i++) {
			if (i == ids.length - 1) {
				builder.append(ids[i]);
			} else {
				builder.append(ids[i]).append(",");
			}
		}

		StringBuilder hql = new StringBuilder();
		hql.append("from " + entityClass.getSimpleName()); 
				hql.append(" where ");
				hql.append(this.classMetadata.getIdentifierPropertyName());
				hql.append(" in (");
				hql.append(builder.toString() + " )");
		List list = this.hibernateTemplate.find(hql.toString());
		this.hibernateTemplate.deleteAll(list);
	}

	@Override
	public void deleteEntry(Serializable id) {
		T t = (T) this.hibernateTemplate.get(entityClass, id);
		this.hibernateTemplate.delete(t);

	}
	

	@Override
	public int getCount(final BaseQuery baseQuery) {
	
		
		return this.hibernateTemplate.execute(new HibernateCallback<Integer>() {

			@Override
			public Integer doInHibernate(Session session) throws HibernateException,
					SQLException {
				StringBuilder hql = new StringBuilder();
				/**
				 * 使用select count(1) 报错?
				 */
				hql.append("select count("+classMetadata.getIdentifierPropertyName()+") from ");
				String name = entityClass.getSimpleName();
				hql.append(name);
				hql.append(" where 1 = 1 ");
				Map<String, Object> buildWhere = baseQuery.buildWhere();
				
				/**
				 * 构造 where 1 = 1 and key =: key
				 */
				for(Entry<String, Object> entry : buildWhere.entrySet()){
					hql.append(" and "+entry.getKey() + " =: "+entry.getKey());
				}
			
				Query query = session.createQuery(hql.toString());
				
				for (Entry<String, Object> entry : buildWhere.entrySet()) {
					query.setParameter(entry.getKey(), entry.getValue());
				}
				
				Long count = (Long) query.uniqueResult();
				
				return count.intValue();
			}
		});
	}

	@Override
	public PageResult<T> getPageResult(final BaseQuery baseQuery) {
		//找到符合条件的总记录数
		final int count = this.getCount(baseQuery);
		return this.hibernateTemplate.execute(new HibernateCallback<PageResult<T>>() {

			@Override
			public PageResult<T> doInHibernate(Session session) throws HibernateException,
					SQLException {
				StringBuilder hql = new StringBuilder();
				hql.append("from "+entityClass.getSimpleName() + " where 1 = 1 ");
				Map<String, Object> whereKV = baseQuery.buildWhere();
				
				for(Entry<String,Object> entry : whereKV.entrySet()){
					hql.append(" and "+entry.getKey()+" =: "+entry.getKey() );
				}
				
				Query query = session.createQuery(hql.toString());
				
				for(Entry<String,Object> entry : whereKV.entrySet()){
					query.setParameter(entry.getKey(), entry.getValue());
				}
				
				//分页
				int firstResult = (baseQuery.getCurrentPage()-1)*baseQuery.getPageSize();
				query.setFirstResult(firstResult).setMaxResults(baseQuery.getPageSize());
				PageResult<T> pageResult = new PageResult<T>(baseQuery.getCurrentPage(),baseQuery.getPageSize(),count);
				List list = query.list();
				pageResult.setRows(list);
				return pageResult;
			}
		});
	
	}

	
	@Override
	public Set<T> getEntrysByIds(Serializable[] ids) {
		
		StringBuilder id = new StringBuilder();
		if(ids!=null && ids.length>0){
			for (int i = 0;i<ids.length;i++) {
				if(i==ids.length-1){
					id.append(ids[i]);
				}else{
					id.append(ids[i]).append(",");
				}
			}
		}
		
		StringBuilder hql = new StringBuilder();
		hql.append("from "+this.entityClass.getSimpleName()+" where 1 = 1 ");
		hql.append(" and "+this.classMetadata.getIdentifierPropertyName()+" in("+id+")");
		List list = this.hibernateTemplate.find(hql.toString());
		return new HashSet(list);
	}

}

4.Service

package cn.opencil.core.base.service;

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

import cn.opencil.common.util.PageResult;
import cn.opencil.core.query.BaseQuery;


public interface BaseService<T> {
	/**
	 * 分页的查询
	 * @param baseQuery
	 * @return
	 */
	public PageResult<T> getPageResult(final BaseQuery baseQuery);
	/**
	 * 添加
	 * 
	 * @param t
	 */
	public void addEntry(T t);

	/**
	 * 查询一个
	 * 
	 * @return
	 */
	public T getEntryById(Serializable id);
	/**
	 * 按ids查询
	 */
	public Set<T> getEntrysByIds(Serializable[] ids);
	
	/**
	 * 不分页的查询
	 * 
	 * @return
	 */
	public Collection<T> getEntrys();

	/**
	 * 修改
	 * 
	 * @param t
	 */
	public void updateEntry(T t);

	/**
	 * 根据ids删除一些数据
	 * 
	 * @param ids
	 */
	public void deleteEntriesByIDS(Serializable[] ids);

	/**
	 * 根据id删除一条数据
	 * 
	 * @param id
	 */
	public void deleteEntry(Serializable id);
}


5.serviceImpl

package cn.opencil.core.base.service.impl;

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

import org.springframework.transaction.annotation.Transactional;

import cn.opencil.common.util.PageResult;
import cn.opencil.core.base.dao.BaseDao;
import cn.opencil.core.base.service.BaseService;
import cn.opencil.core.query.BaseQuery;

/**
 * Project Name:SC
 * File Name:BaseServiceImpl.java
 * Date:2016-3-25下午9:30:28
 * Author : 王基伟
 * @param <T>
 * @param <T>
 *
 */
public abstract class BaseServiceImpl<T> implements BaseService<T>{

	public abstract BaseDao getBaseDao();//此种实现可提高扩展性
	
	public PageResult<T> getPageResult(final BaseQuery baseQuery){
		return this.getBaseDao().getPageResult(baseQuery);
	}
	
	@Transactional
	@Override
	public void addEntry(T t) {
		this.getBaseDao().addEntry(t);
		
	}

	@Override
	public T getEntryById(Serializable id) {
		return (T) this.getBaseDao().getEntryById(id);
	}
	@Override
	public Set<T> getEntrysByIds(Serializable [] ids){
		return this.getBaseDao().getEntrysByIds(ids);
	}
	
	@Override
	public Collection<T> getEntrys() {
		// TODO Auto-generated method stub
		return this.getBaseDao().getEntrys();
	}
	@Transactional
	@Override
	public void updateEntry(T t) {
		this.getBaseDao().updateEntry(t);
		
	}
	@Transactional
	@Override
	public void deleteEntriesByIDS(Serializable[] ids) {
		this.getBaseDao().deleteEntriesByIDS(ids);
	}
	@Transactional
	@Override
	public void deleteEntry(Serializable id) {
		this.getBaseDao().deleteEntry(id);
	}

}
6.Action

package cn.opencil.core.base.action;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

/**
 * Project Name:SC
 * File Name:BaseAction.java
 * Date:2016-3-25下午9:33:10
 * Author : 王基伟
 *
 */
public class BaseAction<T> extends ActionSupport implements ModelDriven<T>,ServletRequestAware,ServletResponseAware{

	private HttpServletRequest request;
	private HttpServletResponse response;
	
	

	Class entityClass;
	T t;
	/**
	 * 解析泛型
	 */
	public BaseAction(){
		Type superclass = this.getClass().getGenericSuperclass();
		ParameterizedType type = (ParameterizedType) superclass;
		Type[] args = type.getActualTypeArguments();
		entityClass = (Class) ((null != args && args.length > 0) ? args[0]
				: null);
		try {
			this.t = (T) entityClass.newInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public T getModel() {
		
		return this.t;
	}
	
	public HttpSession getSession(){
		return ServletActionContext.getRequest().getSession();
	}
	
	private int currentPage = 1;
	
	
	public int getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	private Long [] ids;
	
	public Long[] getIds() {
		return ids;
	}

	public void setIds(Long[] ids) {
		this.ids = ids;
	}

	public static final String LISTACTION = "listAction";//跳转到列表页面的字符串
	public String listAction = LISTACTION;
	
	public static final String ACTION2ACTION = "action2action";//action跳转到action
	public String action2action = ACTION2ACTION;
	
	public static final String ACTIONRACTION = "actionRaction";//action重定向到action
	public String actionRaction = ACTIONRACTION;
	
	public static final String ADDUI = "addUI";
	public String addUI = ADDUI;
	
	public static final String UPDATEUI = "updateUI";
	public String updateUI = UPDATEUI;
	@Override
	public void setServletRequest(HttpServletRequest request) {
		
		this.request = request;
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {

		this.response = response;
	}
	
	public HttpServletRequest getRequest() {
		return request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}
}

好处:

以后所有的Service可以直接继承,不需要再编写代码(CRUD操作,不涉及到特殊需求)

public interface DepartmentService extends BaseService<Department>{
	public static final String SERVICENAME = "cn.opencil.core.basedata.service.impl.DepartmentServiceImpl";
}

DepartmentServiceImpl

@Service(DepartmentService.SERVICENAME)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements DepartmentService{

	@Resource(name=DepartmentDao.DAONAME)	
	private DepartmentDao departmentDao;
	
	@Override
	public BaseDao getBaseDao() {
		// TODO Auto-generated method stub
		return this.departmentDao;
	}

}

DepartmentDaoImpl

@Repository(DepartmentDao.DAONAME)
public class DepartmentDaoImpl extends BaseDaoImpl<Department> implements DepartmentDao {

}



  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值