1. 程式人生 > >Spring + Struts + Hibernate 簡單封裝通用接口

Spring + Struts + Hibernate 簡單封裝通用接口

.get ber 當前 ger 接收 lte count style trac

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 簡單封裝通用接口