首页 > 代码库 > 一个通用的数据访问层实现类

一个通用的数据访问层实现类

   在java商城开发中以及人事系统开发中我们知道会涉及到很多的数据表,如果每一个数据库都按照我们开发人员所定义的那样一个表,一个实现类,然后是一个数据访问层接口,数据访问层实现类,业务逻辑层接口,业务逻辑层实现类...这样写下去,代码量无疑是很大的。

下面我们就介绍一个基本的数据访问层实现类,至于接口的定义,我想只要明白实现类,接口的定义应该很简单。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package cn.com.bochy.crm.dao.impl;
 
import java.io.Serializable;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
 
import javax.annotation.Resource;
 
import org.apache.commons.lang.StringUtils;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
 
 
 
 
 
 
import cn.com.bochy.crm.dao.BaseDao;
import cn.com.bochy.crm.util.QueryResult;
@SuppressWarnings("rawtypes")
@Transactional(readOnly=true)
@Repository(BaseDao.SERVER_NAME)
public class BaseDaoImpl implements BaseDao {
 
    /*
     * 注入sessionfactory
     * save(Object entity):保存实体
     * update(Object entity):修改实体方法
     *  queryById(Class entity, Serializable id):根据id查询实体
     *
     * (non-Javadoc)
     * @see cn.com.bochy.crm.dao.BaseDao#save(java.lang.Object)
     */
     
     
    @Resource(name="hibernateTemplate")
    private HibernateTemplate hibernateTemplate;
     
    @Override
    public Object queryById(Class entity, Serializable id) {
        // TODO Auto-generated method stub
        return hibernateTemplate.get(entity, id);
    }
 
     
    @Override
    @Transactional(isolation=Isolation.DEFAULT,propagation=Propagation.REQUIRED,readOnly=false)
    public void save(Object entity) {
        // TODO Auto-generated method stub
        hibernateTemplate.save(entity);
    }
 
    @Override
    @Transactional(isolation=Isolation.DEFAULT,propagation=Propagation.REQUIRED,readOnly=false)
    public void update(Object entity) {
        // TODO Auto-generated method stub
        hibernateTemplate.update(entity);
    }
     
     
    //删除数据(实体)
 
    @Override
    @Transactional(isolation=Isolation.DEFAULT,propagation=Propagation.REQUIRED,readOnly=false)
    public void delete(Class entity, Serializable... id) {
        // TODO Auto-generated method stub
        //判断id存在
        if(id.length>0&&id!=null){
            //通过for循环来判断id的实体是否存在,存在删除,不存在抛出异常
            for(Serializable ids:id){
           Object entityclass=hibernateTemplate.load(entity, ids);
           if(entityclass==null){
              throw new RuntimeException("实体不存在");  
           }
           hibernateTemplate.delete(entityclass);
           }
        }
    }
 
     
    @Override
    /*
     * 无分页的查询
     * queryListWithNoPage(Class entityClass,String wherehql,Object[] params)
     * String hql="select s from sysusergroup s where 1=1 and s.name like ?"
     * 拼出上面的hql语句需要获得类名,和参数
     * 通过java反射机制获得类名
     */
    public List queryListWithNoPage(Class entityClass, String wherehql,
             final Object[] params,LinkedHashMap<String, String> orderby) {
        // TODO Auto-generated method stub
         
        //通过java反射机制获得类名
        String entityName=entityClass.getSimpleName();
        String hql="select s from "+entityName+" s where 1=1";
         if(StringUtils.isNotBlank(wherehql)){//判断wherehql的返回值是不是为空
             hql=hql+wherehql;
         }
          
         //处理map类型的orderby
          String order=getOrderBy(orderby);
         final String shql=hql+order;
         System.out.println(shql);
         List list=(List)hibernateTemplate.execute(
                 //拟名内部类,在拟名内部类中所有的参数为最终参数
                 new HibernateCallback() {
            @Override
            public Object doInHibernate(Session session) throws HibernateException,
                    SQLException {
                // TODO Auto-generated method stub
                 
                Query query=session.createQuery(shql);
                 
                setQuery(query,params);
                 
                return query.list();
            }
 
        });
          
        return list;
    }
 
     
     
 
     
 
    //放置参数的方法
    protected void setQuery(Query query, Object[] params) {
        // TODO Auto-generated method stub
        if(params!=null&&params.length>0){
            for(int i=0;i<params.length;i++){
                query.setParameter(i, params[i]);
            }
        }
    }
     
    protected String getOrderBy(LinkedHashMap<String, String> orderby) {
        // TODO Auto-generated method stub
         StringBuffer sf=new StringBuffer(" order by ");
         
        if(orderby!=null&&!orderby.isEmpty()){
            Iterator<String> items=orderby.keySet().iterator();
            if(items.hasNext()){
                String key=items.next();
                String val=orderby.get(key);
                sf.append(key);
                sf.append(" "+val);
                 
            }
        }
        String order=sf.toString();
        System.out.println("排序:"+order);
        return order;
    }
 
 
    @Override
    public QueryResult PageList(Class entityClass, String wherehql,
            Object[] param, LinkedHashMap<String, String> orderby) {
        // TODO Auto-generated method stub
         
        //利用类反射机制获取类名
        String entityName=entityClass.getSimpleName();
        String hql="select s from "+entityName+" s where 1=1";
        String chql="select count(*) from "+entityName+"s where 1=1";
        if(StringUtils.isNotBlank(wherehql)){
            hql=hql+wherehql;
        }
         
        String order=getOrderBy(orderby);
        final String shql=hql+order;
         
         
        return null;
    }
 
     
     
 
}