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();
|
}
|
}
|