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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
package com.vci.server.base.persistence.dao;
 
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
 
import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.connection.ConnectionProvider;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.type.Type;
 
import com.vci.common.objects.UserEntity;
import com.vci.common.resource.CommonProperties;
import com.vci.server.base.persistence.event.HistoryQueryListener;
import com.vci.server.base.persistence.event.PostDeleteQueryListener;
import com.vci.server.base.persistence.event.PostUpdateQueryListener;
import com.vci.server.base.persistence.event.QueryImpl;
 
public class GenericHibernateDao<T extends Serializable, PK extends Serializable> implements GenericDao<T, PK> {
 
    // 实体类类型(由构造方法自动赋值)
    protected Class<T> entityClass;
    protected Session session;
    protected String logQuerySwitch = "off";
 
    public GenericHibernateDao() {
        this.entityClass = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass())
                .getActualTypeArguments()[0];
        this.session = HibernateSessionFactory.getSession();
        logQuerySwitch = CommonProperties.getStringProperty("log.query.switch");
    }
 
//---------------------基本检索、增加、修改、删除操作-----------------------------
 
    /**
     * ok
     */
    // 根据主键获取实体。如果没有相应的实体,返回null。
    @SuppressWarnings("unchecked")
    public T getById(PK id) {
        return (T) session.get(entityClass, id);
    }
 
    // 根据主键获取实体并加锁。如果没有相应的实体,返回null。
    @SuppressWarnings("unchecked")
    public T getByIdWithLock(PK id, LockMode lock) {
        T t = (T) session.get(entityClass, id, lock);
        if (t != null) {
            this.flush(); // 立即刷新,否则锁不会生效。
        }
 
        return t;
    }
 
    // 根据主键获取实体。如果没有相应的实体,抛出异常
    @SuppressWarnings("unchecked")
    public T loadById(PK id) {
        return (T) session.load(entityClass, id);
    }
 
    // 根据主键获取实体并加锁。如果没有相应的实体,抛出异常
    @SuppressWarnings("unchecked")
    public T loadByIdWithLock(PK id, LockMode lock) {
        T t = (T) session.load(entityClass, id);
        if (t != null) {
            this.flush(); // 立即刷新,否则锁不会生效。
        }
 
        return t;
    }
 
    // 获取全部实体
    @SuppressWarnings("unchecked")
    public List<T> loadAll() {
//        return session.createCriteria(entityClass).list();
        List<T> list = session.createQuery("from " + entityClass.getName()).list();
        return list;
    }
 
    // 获得指定页的实体
    @SuppressWarnings("unchecked")
    public List<T> findList(int pageNo, int pageSize) {
        return session.createCriteria(entityClass).setFirstResult((pageNo - 1) * pageSize).setMaxResults(pageSize)
                .list();
    }
 
    
    //获得指定页的实体
    @SuppressWarnings("unchecked")
    public List<T> findList(int pageNo, int pageSize, Order order) {
            return session.createCriteria(entityClass)
                    .setFirstResult((pageNo - 1) * pageSize)
                    .setMaxResults(pageSize).addOrder(order).list();
    }
 
    // added by xiong fei 2011-02-14 日志查询
    @SuppressWarnings("unchecked")
    public List<T> findList(int pageNo, int pageSize, String sql, Order order) {
        if (order == null) {
            return session.createCriteria(entityClass).setFirstResult((pageNo - 1) * pageSize).setMaxResults(pageSize)
                    .add(Expression.sqlRestriction(sql)).list();
        } else {
            return session.createCriteria(entityClass).setFirstResult((pageNo - 1) * pageSize).setMaxResults(pageSize)
                    .add(Expression.sqlRestriction(sql)).addOrder(order).list();
        }
    }
 
    // 获得存储对象的个数
    public int getCount() {
        Integer count = (Integer) session.createCriteria(entityClass).setProjection(Projections.rowCount())
                .uniqueResult();
        if (null == count) {
            return 0;
        } else {
            return count.intValue();
        }
    }
 
    // added by xiong fei 2011-02-14 日志查询
    public long getCountForLog(String sql) {
        Long count = (Long) session.createCriteria(entityClass).add(Expression.sqlRestriction(sql))
                .setProjection(Projections.rowCount()).uniqueResult();
        if (null == count) {
            return 0;
        } else {
            return count.longValue();
        }
    }
 
    // 更新实体
    public void update(T entity) {
        session.update(entity);
        this.flush();
    }
 
    // 更新实体并加锁
    public void updateWithLock(T entity, LockMode lock) {
        session.update(entity);
        this.flush();
    }
 
    // 存储实体到数据库
    public void save(T entity) {
        session.save(entity);
        this.flush();
    }
 
    // 增加或更新实体
    public void saveOrUpdate(T entity) {
        session.saveOrUpdate(entity);
        this.flush();
    }
 
    // 增加或更新集合中的全部实体
    public void saveOrUpdateAll(Collection<T> entities) {
        for (T t : entities) {
            session.saveOrUpdate(t);
        }
        this.flush();
    }
 
    // 删除指定的实体
    public void delete(T entity) {
        session.delete(entity);
        this.flush();
    }
 
    // 根据主键删除指定的实体
    public void deleteByKey(PK id) {
        this.delete(this.loadById(id));
        this.flush();
    }
 
    // 删除集合中的全部实体
    public void deleteAll(Collection<T> entities) {
        this.flush();
        session.delete(entities);
    }
 
    public T merge(T entity) {
        return (T) session.merge(entity);
    }
 
    // -----------------------------HSQL------------------------------
    // 使用hql进行删除和更新操作,未记录更新日志
    public void createQuery(String hql) {
        Query query = session.createQuery(hql);
        query.executeUpdate();
    }
 
    // 使用hql进行删除和更新操作,未记录更新日志
    public void createQuery(String hql, Object[] values) {
        Query query = session.createQuery(hql);
        for (int i = 0; i < values.length; i++) {
            query.setParameter(i, values[i]);
        }
        query.executeUpdate();
    }
 
    // 使用hql进行删除和更新操作,未记录更新日志
    public void createQuery(String hql, String[] names, Object[] values) {
        Query query = session.createQuery(hql);
        for (int i = 0; i < values.length; i++) {
            query.setParameter(names[i], values[i]);
        }
        query.executeUpdate();
    }
 
    /**
     * 删除指定ID对象,并记录日志
     * 
     * @param hql,hql               语句
     * @param idName,id对应在hql语句中的名称
     * @param id,                   id的值
     * @param userEntity,用户信息
     */
    public void deleteQueryObject(String hql, String idName, String id, UserEntity userEntity) {
        Query query = session.createQuery(hql);
        Object obj = session.get(entityClass, id);
        query.setParameter(idName, id);
        int count = query.executeUpdate();
        if (count < 1) {
            return;
        }
        if (logQuerySwitch == null || !logQuerySwitch.equalsIgnoreCase("on")) {
            return;
        }
        PostDeleteQueryListener listener = new HistoryQueryListener();
        QueryImpl impl = new QueryImpl(listener);
        impl.deletQueryById(session, "id", id, obj, userEntity);
    }
 
    /**
     * 批量删除指定ID的对象,并记录日志
     * 
     * @param hql,hql语句
     * @param ids,id的数组信息
     * @param userEntity,用户信息
     */
    public void deleteQueryObject(String hql, String[] ids, UserEntity userEntity) {
        Query query = session.createQuery(hql);
        int len = ids.length;
        Object[] objs = new Object[ids.length];
        for (int i = 0; i < len; i++) {
            query.setParameter(i, ids[i]);
            objs[i] = session.get(entityClass, ids[i]);
        }
        int count = query.executeUpdate();
        if (count < 1) {
            return;
        }
        if (logQuerySwitch == null || !logQuerySwitch.equalsIgnoreCase("on")) {
            return;
        }
 
        PostDeleteQueryListener listener = new HistoryQueryListener();
        QueryImpl impl = new QueryImpl(listener);
        impl.deleteQueryByIds(session, "id", ids, objs, userEntity);
    }
 
    /**
     * 通过指定属性信息进行对象删除,并记录日志
     * 
     * @param hql,hql语句
     * @param props,hql语句中的属性名称
     * @param values,hql语句中属性值
     * @param userEntity,用户信息
     */
    public void deleteQueryObject(String hql, String[] props, String[] values, UserEntity userEntity) {
        Query query = session.createQuery(hql);
        int len = props.length;
        for (int i = 0; i < len; i++) {
            query.setParameter(props[i], values[i]);
        }
        int count = query.executeUpdate();
        if (count < 1) {
            return;
        }
        if (logQuerySwitch == null || !logQuerySwitch.equalsIgnoreCase("on")) {
            return;
        }
 
        PostDeleteQueryListener listener = new HistoryQueryListener();
        QueryImpl impl = new QueryImpl(listener);
        impl.deleteQueryByProps(session, props, values, entityClass.getSimpleName(), userEntity);
    }
 
    /**
     * 根据ID更新指定属性的属性值,并记录更改日志
     * 
     * @param hql,hql语句
     * @param id,更新对象的id值
     * @param props,hql语句中对应的属性名称
     * @param values,hql语句中对应的属性值
     * @param userEntity,用户信息
     */
    public void updateQueryObject(String hql, String id, String[] props, String[] values, UserEntity userEntity) {
        Query query = session.createQuery(hql);
        int len = props.length;
        for (int i = 0; i < len; i++) {
            query.setParameter(props[i], values[i]);
        }
        int count = query.executeUpdate();
        if (count < 1) {
            return;
        }
        if (logQuerySwitch == null || !logQuerySwitch.equalsIgnoreCase("on")) {
            return;
        }
        Object obj = session.get(entityClass, id);
        PostUpdateQueryListener listener = new HistoryQueryListener();
        QueryImpl impl = new QueryImpl(listener);
        impl.updateQueryById(session, userEntity, id, props, values, obj);
    }
 
    /** lizf 以下操作采用JDBC连接数据库 **/
    /**
     * 根据SQL语句创建、删除、更新 数据表 return 0 成功创建 -1 创建失败 -2 数据库已经存在该表
     */
    public int oprateTable(String sTableName, String sSQL) {
        Statement statement = null;
        Connection conn = null;
        int ncheck = -1;
        try {
            ConnectionProvider cp = ((SessionFactoryImplementor) session.getSessionFactory()).getConnectionProvider();
            conn = cp.getConnection();
 
            boolean checkTableExist = checkTableExist(conn, sTableName);
            if (checkTableExist) {
                ncheck = -2;
                return ncheck;
            }
            statement = conn.createStatement();
            conn.commit();
            statement.executeUpdate(sSQL);
            ncheck = 0;
        } catch (SQLException e) {
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        } finally {
            try {
                if (conn != null) {
                    conn.close();
                }
                if (statement != null) {
                    statement.close();
                }
            } catch (SQLException e) {
            }
        }
        return ncheck;
    }
 
    /**
     * 
     * 根据SQL语句创建、删除、更新 数据表 return 0 成功创建 -1 创建失败 -2 数据库已经存在该表
     *
     * @param conn
     * @param sTableName
     * @param sSQL
     * @return
     */
    public int oprateTable(Connection conn, String sTableName, String sSQL) {
        Statement statement = null;
        int ncheck = -1;
        try {
            boolean checkTableExist = checkTableExist(conn, sTableName);
            if (checkTableExist) {
                ncheck = -2;
                return ncheck;
            }
            statement = conn.createStatement();
            conn.commit();
            statement.executeUpdate(sSQL);
            ncheck = 0;
        } catch (SQLException e) {
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        } finally {
            try {
                if (statement != null) {
                    statement.close();
                }
            } catch (SQLException e) {
            }
        }
        return ncheck;
    }
 
    /**
     * 校验当前创建的表是不是存在
     */
    private boolean checkTableExist(Connection conn, String tableName) {
        boolean bCheck = false;
        DatabaseMetaData meta = null;
        ResultSet rs = null;
        try {
            meta = conn.getMetaData();
            rs = meta.getTables(null, null, tableName, new String[] { "TABLE" });
            if (rs.next()) {
                bCheck = true;
            } else {
                bCheck = false;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return bCheck;
    }
 
    /** lizf 以上操作采用JDBC连接数据库 **/
 
    /**
     * ok
     */
    // 使用HSQL语句进行对象查询
    @SuppressWarnings("unchecked")
    public T findEntity(String hsql) {
        return (T) session.createQuery(hsql).uniqueResult();
    }
 
    // 使用HSQL以及单属性条件进行对象查询
    @SuppressWarnings("unchecked")
    public T findEntity(String hsql, String name, String value) {
        return (T) session.createQuery(hsql).setString(name, value).uniqueResult();
    }
 
    /**
     * ok
     */
    // 使用HSQL语句查询对象集合
    @SuppressWarnings("unchecked")
    public List<T> findEntities(String hsql) {
        return session.createQuery(hsql).list();
    }
 
    /**
     * ok
     */
    // 使用HSQL语句查询对象集合
    @SuppressWarnings("unchecked")
    public List<T> findEntities(String hsql, String name, String value) {
        return session.createQuery(hsql).setString(name, value).list();
    }
 
    /**
     * ok
     */
    // 使用带参数的HSQL语句检索数据
    @SuppressWarnings("unchecked")
    public List<T> findEntites(String hsql, Object[] values) {
        Query query = session.createQuery(hsql);
        for (int i = 0; i < values.length; i++) {
            query.setParameter(i, values[i]);
        }
        List list = query.list();
        return list;
    }
 
    // 根据HSQL语句获取符合要求的对象
    public List createQueryList(String hsql) {
        Query query = session.createQuery(hsql);
        List list = query.list();
        return list;
    }
 
    // 根据HSQL语句获取符合要求的对象
    public List createQueryList(String hsql, Object[] values) {
        Query query = session.createQuery(hsql);
        for (int i = 0; i < values.length; i++) {
            query.setParameter(i, values[i]);
        }
        List list = query.list();
        return list;
    }
 
    @SuppressWarnings("unchecked")
    public T findEntity(String hsql, Object[] values) {
        Query query = session.createQuery(hsql);
        for (int i = 0; i < values.length; i++) {
            query.setParameter(i, values[i]);
        }
        return (T) query.uniqueResult();
    }
 
    /**
     * ok
     */
    @SuppressWarnings("unchecked")
    public List<T> findEntites(String hsql, int start, int number) {
        Query query = session.createQuery(hsql);
        query.setFirstResult(start);
        query.setMaxResults(number);
        List list = query.list();
        return list;
    }
 
    /**
     * ok
     */
    @SuppressWarnings("unchecked")
    public List<T> findEntites(String hsql, int start, int number, Object[] values) {
        Query query = session.createQuery(hsql);
        for (int i = 0; i < values.length; i++) {
            query.setParameter(i, values[i]);
        }
        query.setFirstResult(start);
        query.setMaxResults(number);
        List list = query.list();
        return list;
    }
 
    // 使用命名的HSQL语句检索数据
    @SuppressWarnings("unchecked")
    public List<T> findByNamedQuery(String queryName) {
        return session.getNamedQuery(queryName).list();
    }
 
    // 使用带参数的命名HSQL语句检索数据
    @SuppressWarnings("unchecked")
    public List<T> findByNamedQuery(String queryName, Object[] values) {
        Query query = session.getNamedQuery(queryName);
        for (int i = 0; i < values.length; i++) {
            query.setParameter(i, values[i]);
        }
        return query.list();
    }
 
    // 使用带命名参数的命名HSQL语句检索数据
    @SuppressWarnings("unchecked")
    public List<T> findByNamedQueryAndNamedParam(String queryName, String[] paramNames, Object[] values) {
        Query query = session.getNamedQuery(queryName);
        for (int i = 0; i < paramNames.length; i++) {
            query.setParameter(paramNames[i], values[i]);
        }
        return query.list();
    }
 
    // 使用HSQL语句检索数据,返回Iterator
    public Iterator iterate(String queryString) {
        return session.createQuery(queryString).iterate();
    }
 
    // 使用带参数HSQL语句检索数据,返回Iterator
    public Iterator iterate(String queryString, Object[] values) {
        Query query = session.createQuery(queryString);
        for (int i = 0; i < values.length; i++) {
            query.setParameter(i, values[i]);
        }
        return query.iterate();
    }
 
    // ---------------------------------------------Criteria------------------------
 
    // 创建与会话无关的检索标准对象
    public DetachedCriteria createDetachedCriteria() {
        return DetachedCriteria.forClass(this.entityClass);
    }
 
    // 创建与会话绑定的检索标准对象
    public Criteria createCriteria() {
        return this.createDetachedCriteria().getExecutableCriteria(session);
    }
 
    // 使用指定的检索标准检索数据
    @SuppressWarnings("unchecked")
    public List<T> findByCriteria(DetachedCriteria criteria) {
        return criteria.getExecutableCriteria(session).list();
    }
 
    // 使用指定的检索标准检索数据,返回部分记录
    @SuppressWarnings("unchecked")
    public List<T> findByCriteria(DetachedCriteria criteria, int firstResult, int maxResults) {
        return criteria.getExecutableCriteria(session).setFirstResult(firstResult).setMaxResults(maxResults).list();
    }
 
    @SuppressWarnings("unchecked")
    public List<T> findByCriteria(Criterion... criterion) {
        Criteria crit = session.createCriteria(entityClass);
 
        for (Criterion c : criterion) {
            if (c != null) {
                crit.add(c);
            }
        }
 
        return crit.list();
    }
 
    // 使用指定的检索标准检索数据,返回指定范围的记录
    public Integer getRowCount(DetachedCriteria criteria) {
        criteria.setProjection(Projections.rowCount());
        List list = this.findByCriteria(criteria, 0, 1);
        return (Integer) list.get(0);
    }
 
    // 使用指定的检索标准检索数据,返回指定统计值
    public Object getStatValue(DetachedCriteria criteria, String propertyName, String StatName) {
        if (StatName.toLowerCase().equals("max")) {
            criteria.setProjection(Projections.max(propertyName));
        } else if (StatName.toLowerCase().equals("min")) {
            criteria.setProjection(Projections.min(propertyName));
        } else if (StatName.toLowerCase().equals("avg")) {
            criteria.setProjection(Projections.avg(propertyName));
        } else if (StatName.toLowerCase().equals("sum")) {
            criteria.setProjection(Projections.sum(propertyName));
        } else {
            return null;
        }
 
        List list = this.findByCriteria(criteria, 0, 1);
        return list.get(0);
 
    }
 
    // 通过给定的一个对象,查找与其匹配的对象,表关联比较多时,用户可以根据需要扩展
    @SuppressWarnings("unchecked")
    public List<T> findByExample(T entity) {
        Criteria crit = session.createCriteria(entityClass);
        Example example = Example.create(entity);
        example.ignoreCase().enableLike(MatchMode.ANYWHERE);// 忽略大小写,并进行模糊比辿
        example.excludeZeroes();// 对于属性中有数字类型的,如果entity的属性值为0,就把它添加到查询中
        crit.add(example);
        return crit.list();
    }
 
    // ---------------------------------SQL------------------------------------
    /**
     * 使用SQL进行删除和更新
     * <p>
     * Description:
     * </p>
     * 
     * @author xchao
     * @time 2012-5-29
     * @param sql
     */
    public void createSQLQuery(String sql) {
        SQLQuery query = session.createSQLQuery(sql);
        query.executeUpdate();
    }
 
    /**
     * 使用SQL进行删除和更新,占位符参数传递
     * <p>
     * Description:
     * </p>
     * 
     * @author xchao
     * @time 2012-5-29
     * @param sql
     * @param values
     */
    public void createSQLQuery(String sql, Object[] values) {
        SQLQuery query = session.createSQLQuery(sql);
        for (int i = 0; i < values.length; i++) {
            query.setParameter(i, values[i]);
        }
        query.executeUpdate();
    }
 
    /**
     * 使用SQL进行删除和更新,命名参数传递
     * <p>
     * Description:
     * </p>
     * 
     * @author xchao
     * @time 2012-5-29
     * @param sql
     * @param names
     * @param values
     */
    public void createSQLQuery(String sql, String[] names, Object[] values) {
        SQLQuery query = session.createSQLQuery(sql);
        for (int i = 0; i < values.length; i++) {
            query.setParameter(names[i], values[i]);
        }
        query.executeUpdate();
    }
 
    /**
     * 通过sql语句批量删除数据库数据
     */
    public void deleteEntityBySQL(Connection connection, String sql, String[] values) throws SQLException {
        PreparedStatement stmt = null;
        try {
            stmt = connection.prepareStatement(sql);
            int len = values.length;
            for (int i = 0; i < len; i++) {
                stmt.setString(i + 1, values[i]);
            }
            stmt.executeUpdate();
        } finally {
            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException e) {
            }
        }
    }
 
    /**
     * 
     * <p>
     * Description: 根据传输的sql语句以及sql语句中的参数,通过jdbc获取符合条件的结果集合,并把结果集合返回
     * </p>
     * 
     * @author Administrator
     * @time 2011-7-21
     * @param sql:sql查询语句
     * @param values:sql语句中的参数
     * @param columns:需要返回的列,如果没有返回列,则返回所有查询出来的列
     * @return
     * @throws SQLException
     */
    @Deprecated
    public Object[][] findObjectsBySQL(String sql, String[] values, String[] columns) throws SQLException {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        Object[][] objs = null;
 
        try {
            // modify by xchao 2012.05.28
            ConnectionProvider cp = ((SessionFactoryImplementor) session.getSessionFactory()).getConnectionProvider();
            conn = cp.getConnection();
            stmt = conn.prepareStatement(sql);
            int len = values.length;
            for (int i = 0; i < len; i++) {
                stmt.setString(i + 1, values[i]);
            }
 
            rs = stmt.executeQuery();
            len = columns.length;
            if (len == 0) {
                ResultSetMetaData rsm = rs.getMetaData();
                len = rsm.getColumnCount();
                columns = new String[len];
                for (int i = 0; i < len; i++) {
                    columns[i] = rsm.getColumnName(i + 1);
                    String column = rsm.getColumnName(i + 1);
                    if (column.lastIndexOf(" ") > 0) { // SQL中的列带别名,则只取别名
                        String[] strs = column.split(" ");
                        column = strs[strs.length - 1];
                    }
                }
            }
            Object[] rsArray = null;
            ArrayList<Object[]> list = new ArrayList<Object[]>();
            while (rs.next()) {
                rsArray = new Object[len];
                for (int i = 0; i < len; i++) {
                    rsArray[i] = rs.getObject(columns[i]);
                }
                list.add(rsArray);
            }
            int size = list.size();
            objs = list.toArray(new Object[size][]);
        } finally {
            try {
                if (conn != null) {
                    conn.close();
                }
                if (stmt != null) {
                    stmt.close();
                }
                if (rs != null) {
                    rs.close();
                }
            } catch (SQLException e) {
            }
        }
 
        return objs;
    }
 
    public List<T> findEntites(String sql, Object[] values, String param, Class cls) {
        Query query = session.createSQLQuery(sql).addEntity(param, cls);
        for (int i = 0; i < values.length; i++) {
            query.setParameter(i, values[i]);
        }
        List list = query.list();
        return list;
    }
 
    public List findEntitesBySQL(String sql, Object[] values, Map<String, Type> map) {
        SQLQuery s = (SQLQuery) session.createSQLQuery(sql);
        for (int i = 0; i < values.length; i++) {
            s.setParameter(i, values[i]);
        }
        Iterator itor = map.keySet().iterator();
        while (itor.hasNext()) {
            String key = (String) itor.next();
            Type value = map.get(key);
            s.addScalar(key, value);
        }
        List list = s.list();
        return list;
    }
 
    /**
     * 检查对象中是否包含指定的数据
     * 
     * @param tableName 表名
     * @param valueMaps key:列名 value:值
     * @return
     */
    public boolean hasValue(String tableName, HashMap<String, String> valueMaps) {
        boolean res = false;
        if (tableName.equals("") || tableName == null || valueMaps.size() == 0)
            return res;
        String sql = "select cmoid from " + tableName + " where 1=1 ";
        java.util.Set<String> keys = valueMaps.keySet();
        java.util.Iterator<String> it = keys.iterator();
        while (it.hasNext()) {
            String key = it.next();
            String value = valueMaps.get(key);
//            sql += " and '''' || " + key + " || '''' = '''" + value + "'''";
            sql += " and " + key + " = '" + value + "'";
        }
        Query q = session.createSQLQuery(sql);
        List l = q.list();
        res = l.size() != 0;
        return res;
    }
 
    // -------------------------------- Others --------------------------------
 
    // 加锁指定的实体
    public void lock(T entity, LockMode lockMode) {
        session.lock(entity, lockMode);
    }
 
    // 强制立即更新缓冲数据到数据库(否则仅在事务提交时才更新)
    public void flush() {
        session.flush();
    }
 
    // 清空缓存
    public void clear() {
        session.clear();
    }
}