Spring + Struts + Hibernate 简单封装通用接口

Posted 追梦赤子心

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring + Struts + Hibernate 简单封装通用接口相关的知识,希望对你有一定的参考价值。

1、BaseDao

public interface BaseDao<T> {
    /**
     * 获取符合条件的记录数
     * @param filter
     * @param sortName
     * @param sortOrder
     * @return int
     */
    public int findCount(String filter, String sortName, String sortOrder);
    
    /**
     * 获取分页数据
     * @param filter
     * @param sortName
     * @param sortOrder
     * @param startSize
     * @param pageSize
     * @return List<T>
     */
    public List<T> findGrid(String filter, String sortName, String sortOrder, int startSize, int pageSize);
    
    /**
     * 添加实体类对象
     * @param entity
     * @return int
     */
    public int add(T entity);
    
    /**
     * 根据主键获取实体类对象
     * @param id
     * @return T
     */
    public T getById(int id);
    
    /**
     * 更新实体类对象
     * @param entity
     * @return boolean
     */
    public boolean update(T entity);
    
    /**
     * 删除实体类对象
     * @param id
     * @return boolean
     */
    public boolean delete(int id);
    
}

 

2、BaseDaoImpl

public  class BaseDaoImpl<T> implements BaseDao<T>{
    
    private Class<T> clazz = null;// 表示当前的类型
    
    private SessionFactory sessionFactory;
    /**
     * 通过反射技术获得子类T的真实值
     * 由于在子类中首先调用的是父类的构造方法
     */
    @SuppressWarnings("unchecked")
    public BaseDaoImpl(){  
        // 获取当前new的对象的泛型的父类类型
         ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
        // 获取第一个类型参数的真实类型
        clazz = (Class<T>) pt.getActualTypeArguments()[0]; 
    }  
    
    public Session getSession() {
        return sessionFactory.openSession();
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Override
    public int findCount(String filter, String sortName, String sortOrder) {
        Session session=getSession();    
        StringBuffer hql=new StringBuffer("");
        hql.append("from ").append(clazz.getSimpleName()).append(" where ").append(filter).append(" order by ").append(sortName).append(" ").append(sortOrder);       
        int num=0;
        try{    
            Query query = session.createQuery(hql.toString());
            List<T> list=query.list();
            num=list.size();
        }catch(Exception ex){
            ex.printStackTrace();    
        }finally{
            session.close();
        }
        return num;
    }

    @Override
    public List<T> findGrid(String filter, String sortName, String sortOrder, int startSize, int pageSize) {
        Session session=getSession();    
        List<T> list=null;
        StringBuffer hql=new StringBuffer("");
        hql.append("from ").append(clazz.getSimpleName()).append(" where ").append(filter).append(" order by ").append(sortName).append(" ").append(sortOrder);       
        try{
            Query query =session.createQuery(hql.toString());
            query.setFirstResult(startSize); //设置这一页显示的第一条记录的索引
            query.setMaxResults(pageSize); //这一页显示的记录个数
            list=query.list();
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            session.close();
        }
        return list;
    }
    
    @Override
    public int add(T entity) {
        int num=0; //标识注册是否成功
        Session session=getSession();
        try{
            Transaction trans=session.beginTransaction();
            num=Integer.parseInt(session.save(entity).toString());//在缓存中保存数据,受影响行数
            trans.commit();//写入数据库表
        }catch (Exception e) {
            e.printStackTrace();
        }finally{
            session.close();
        }
        return num;
    }

    @Override
    public T getById(int id) {
        T entity=null;
        Session session=getSession();
        try{
            entity=(T)session.get(clazz,id);        
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            session.close();
        }
        return entity;    
    }

    @Override
    public boolean update(T entity) {
        boolean flag=false;
        Session session = getSession();
        try{
            Transaction trans=session.beginTransaction();
            session.update(entity);
            trans.commit();    
            flag=true;
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            session.close();
        }
        return flag;
    }

    @Override
    public boolean delete(int id) {
        boolean flag=false;
        Session session=getSession();
        try{        
            T entity=(T)session.get(clazz,id);
            Transaction trans=session.beginTransaction();
            session.delete(entity);
            trans.commit();
            flag=true;
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            session.close();
        }
        return flag;
    }

}

 

3、BaseService

public interface BaseService<T> {

    public Map<String,Object> findGrid(String filter, String sortName, String sortOrder, int startSize, int pageSize);
    
    public int add(T entity);
    
    public T getById(int id);
    
    public boolean update(T entity);
    
    public boolean delete(int id);
        
}

 

4、BaseServiceImpl

public class BaseServiceImpl<T> implements BaseService<T> {

    private BaseDao baseDao;
    
    public BaseDao getBaseDao() {
        return baseDao;
    }
    public void setBaseDao(BaseDao baseDao) {
        this.baseDao = baseDao;
    }

    @Override
    public Map<String, Object> findGrid(String filter, String sortName, String sortOrder, int startSize, int pageSize) {
        // TODO Auto-generated method stub
        Map<String,Object> result = new HashMap<String,Object>();
        int total=baseDao.findCount( filter, sortName, sortOrder);
        List<T> rows=baseDao.findGrid(filter, sortName, sortOrder, startSize, pageSize);
        result.put("total",total);
        result.put("rows",rows);
        return result;
    }

    @Override
    public int add(T entity) {
        // TODO Auto-generated method stub
        return baseDao.add(entity);
    }

    @Override
    public T getById(int id) {
        // TODO Auto-generated method stub
        return (T) baseDao.getById(id);
    }
    
    @Override
    public boolean update(T entity) {
        // TODO Auto-generated method stub
        return baseDao.update(entity);
    }
    
    @Override
    public boolean delete(int id) {
        // TODO Auto-generated method stub
        return baseDao.delete(id);
    }
}

 

5、BaseAction

public class BaseAction<T> extends ActionSupport{
    // 取得request对象
    protected HttpServletRequest request = null;
    // 取得response对象
    protected HttpServletResponse response = null;
    //service类对象
    protected BaseService baseService;
    //实体类对象
    protected T entity;
    //主键
    protected int id;
    //主键字符串ids
    protected String ids;
    //每页的记录数
    protected int pageSize;    
    //第几页
    protected int pageNumber;    
    //排序字段
    protected String sortName;    
    //排序方式
    protected String sortOrder;    
    //返回结果
    protected Result result=new Result(false, "操作失败");
    //过滤条件
    protected String filter=null;
    //查询字段
    //protected String fieldlist = null;
    
    public BaseService getBaseService() {
        return baseService;
    }
    public void setBaseService(BaseService baseService) {
        this.baseService = baseService;
    }
    public T getEntity() {
        return entity;
    }
    public void setEntity(T entity) {
        this.entity = entity;
    }    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getIds() {
        return ids;
    }
    public void setIds(String ids) {
        this.ids = ids;
    }
    public int getPageSize() {
        return pageSize;
    }
    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }
    public int getPageNumber() {
        return pageNumber;
    }
    public void setPageNumber(int pageNumber) {
        this.pageNumber = pageNumber;
    }
    public String getSortName() {
        return sortName;
    }
    public void setSortName(String sortName) {
        this.sortName = sortName;
    }
    public String getSortOrder() {
        return sortOrder;
    }
    public void setSortOrder(String sortOrder) {
        this.sortOrder = sortOrder;
    }    
    
    protected void grid(){
        int startSize=(pageNumber-1) * pageSize;    
        toAjax(baseService.findGrid(filter, sortName, sortOrder, startSize, pageSize));
    }

    protected void save(){
        if(id!=0){
            boolean flag=baseService.update(entity);
            if(flag){  
                result.setFlag(true);
                result.setMsg("操作成功");
            }
            toAjax(result);
        }else{
            int i=baseService.add(entity);
            if(i > 0){
                result.setFlag(true);
                result.setMsg("操作成功");
            }
            toAjax(result);
        }
    }
    
    protected void getById() {
        toAjax(baseService.getById(id));
    }
    
    protected void delete(){
        String[] array = ids.split(",");  
        boolean flag=false;
        for(String id : array){
            flag=baseService.delete(Integer.parseInt(id));                            
        }
        if(flag){  
            result.setFlag(true);
            result.setMsg("操作成功");
        }
        toAjax(result);
    }

    
    /**
     * 转换成ajax可以接收的数据
     * @param data
     */
    protected void toAjax(Object data) {
        Gson gson= new Gson();
        final String json= gson.toJson(data);
        System.out.println("打印数据:"+json);
        try {
            response = ServletActionContext.getResponse();
            response.setContentType("text/html;charset=UTF-8");
            response.setHeader("cache-control", "no-cache");
            response.setCharacterEncoding("UTF-8");
            response.flushBuffer();
            response.getWriter().write(json);
            response.getWriter().flush();  
            response.getWriter().close();    
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }
}

 

 这是小编的原创随笔,请尊重原创,若是转载请注明出处,谢谢。

以上是关于Spring + Struts + Hibernate 简单封装通用接口的主要内容,如果未能解决你的问题,请参考以下文章

jsf struts jsp spring 啥关系和区别?

struts与spring整合

请问spring与struts有啥区别?

struts2 与spring整合

下面关于spring和struts的描述

struts2集成Spring,Hibernate的问题!!