📄 abstractdaosupport.java
字号:
/*
* Created on 2005-8-26 9:57:42
*
* By SinoBest
* Copyright E3.org, 2005-2006, All rights reserved.
*/
package cn.com.juneng.system.common;
import java.io.Serializable;
import java.io.StringWriter;
import java.sql.CallableStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.cfg.Environment;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.jdbc.core.CallableStatementCallback;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import cn.com.juneng.system.common.exception.SystemRuleException;
public abstract class AbstractDaoSupport extends HibernateDaoSupport {
private JdbcTemplate jdbcTemplate;
protected Class modelClass = null;
public AbstractDaoSupport() {
}
public AbstractDaoSupport(Class modelClass) {
super();
this.modelClass = modelClass;
}
/**
* 根据主键查找数据对象
*
* @param key
* 主键
* @return 数据库映射对象Model
* @throws Exception
*/
public Object findByPrimaryKey(Serializable key) throws Exception {
Object obj = null;
try {
obj = (Object) getHibernateTemplate().load(modelClass, key);
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
/**
* 创建一个对象,数据表增加一条记录
*
* @param obj
* @throws Exception
*/
public void create(Object obj) throws Exception {
getHibernateTemplate().save(obj);
}
/**
* 更新对象,数据表修改一条记录
*
* @param obj
* 要更新的数据对象model
* @throws Exception
*/
public void update(Object obj) throws Exception {
getHibernateTemplate().update(obj);
}
/**
* 删除数据对象model,数据表删除一条记录
*
* @param obj
* 要修改的数据对象model
* @throws Exception
*/
public void remove(Object obj) throws Exception {
getHibernateTemplate().delete(obj);
}
/**
* 根据主键删除对象
*
* @param key
* 主键
* @throws Exception
*/
public void remove(Serializable key) throws Exception {
Object obj = findByPrimaryKey(key);
remove(obj);
}
protected void checkWriteOperationAllowed(Session session)
throws InvalidDataAccessApiUsageException {
if (getHibernateTemplate().isCheckWriteOperations()
&& getHibernateTemplate().getFlushMode() != HibernateTemplate.FLUSH_EAGER
&& FlushMode.NEVER.equals(session.getFlushMode())) {
throw new InvalidDataAccessApiUsageException(
"Write operations are not allowed in read-only mode (FlushMode.NEVER) - turn your Session "
+ "into FlushMode.AUTO or remove 'readOnly' marker from transaction definition");
}
}
/**
* 保存一批数据
*
* @param objects
* @return
* @throws DataAccessException
*/
public void batchSave(final Collection objects) throws DataAccessException {
getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException {
int count = 0;
// boolean flushed = true;
checkWriteOperationAllowed(session);
for (Iterator it = objects.iterator(); it.hasNext();) {
session.save(it.next());
// flushed = false;
if ((++count) % getJDBCBatchSize() == 0) {
// 将本批插入的对象立即写入数据库并释放内存
session.flush();
session.clear();
// flushed = true;
}
}
// if(!flushed) {
// session.flush();
// session.clear();
// }
return null;
}
}, true);
}
/**
* 保存一批数据,返回保存对象的id
*
* @param objects
* @return 对象id的集合
* @throws DataAccessException
*/
public List batchSaveReturnIds(final Collection objects)
throws DataAccessException {
return (List) getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException {
checkWriteOperationAllowed(session);
int count = 0;
List ids = new ArrayList();
for (Iterator it = objects.iterator(); it.hasNext();) {
Object id = session.save(it.next());
ids.add(id);
if ((++count) % getJDBCBatchSize() == 0) {
// 将本批插入的对象立即写入数据库并释放内存
session.flush();
session.clear();
}
}
return ids;
}
}, true);
}
/**
* 更新一批数据
*
* @param objects
* @return
* @throws DataAccessException
*/
public void batchUpdate(final Collection objects)
throws DataAccessException {
getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException {
checkWriteOperationAllowed(session);
int count = 0;
for (Iterator it = objects.iterator(); it.hasNext();) {
session.update(it.next());
if ((++count) % getJDBCBatchSize() == 0) {
// 将本批插入的对象立即写入数据库并释放内存
session.flush();
session.clear();
}
}
return null;
}
}, true);
}
/**
* 保存、更新、删除一批数据
*
* @param objects
* 一批持久化对象,不为null
* @param operations
* 对对象的相应操作,在cn.hnisi.eecmis.service.impl.ServiceUtils类中定义,不为null
* @return
* @throws DataAccessException
*/
public void batchProcess(final Collection objects, final List operations)
throws DataAccessException {
if (operations == null || objects == null
|| operations.size() != objects.size()) {
throw new IllegalArgumentException("传入方法的参数不正确");
}
getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException {
checkWriteOperationAllowed(session);
int count = 0;
Iterator it = objects.iterator();
for (int i = 0; i < operations.size(); i++) {
if (((Number) operations.get(i)).intValue() == 2) {
session.update(it.next());
}
if (((Number) operations.get(i)).intValue() == 1) {
session.save(it.next());
}
if (((Number) operations.get(i)).intValue() == 3) {
session.delete(it.next());
}
if ((++count) % getJDBCBatchSize() == 0) {
// 将本批插入的对象立即写入数据库并释放内存
session.flush();
session.clear();
}
}
return null;
}
}, true);
}
/**
* 使用HQL Update语句更新数据
*
* @param hqlString
* HQL Update和Delete语句
* @param params
* 更新参数
* @return int 更新的记录数
* @throws DataAccessException
*/
public int update(final String hqlString, final Object[] params)
throws DataAccessException {
Object result = getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException {
Query queryObject = session.createQuery(hqlString);
prepareQuery(queryObject);
if (params != null) {
for (int i = 0; i < params.length; i++) {
queryObject.setParameter(i, params[i]);
}
}
return new Integer(queryObject.executeUpdate());
}
}, true);
int value = ((Integer) result).intValue();
result = null;
return value;
}
/**
* 清理Hibernate Session 缓存
*
* @param entities
* @throws DataAccessException
*/
public void evict(final Collection entities) throws DataAccessException {
this.getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException {
for (Iterator iter = entities.iterator(); iter.hasNext();) {
session.evict(iter.next());
}
return null;
}
}, true);
}
/**
* 调用存储过程并返回执行结果
*
* @param callStr
* 调用语句
* @param inValues
* 调用存储过程传入的参数值,依次传入
* @param outTypes
* 调用存储过程返回的结果类型,是sql 类型,见{@link java.sql.Types}.
* @return 根据存储过程定义的out参数返回执行结果
*/
public Object callProcedure(final String callStr, final Object[] inValues,
final int[] outTypes) {
return getJdbcTemplate().execute(callStr,
new CallableStatementCallback() {
public Object doInCallableStatement(CallableStatement cs)
throws SQLException {
int i = 0;
if (inValues != null) {
for (int index = 0; index < inValues.length; index++) {
i++;
Object inValue = inValues[index];
if (inValue instanceof StringBuffer
|| inValue instanceof StringWriter) {
cs.setString(i, inValue.toString());
} else if ((inValue instanceof java.util.Date)
&& !(inValue instanceof java.sql.Date
|| inValue instanceof java.sql.Time || inValue instanceof java.sql.Timestamp)) {
cs.setTimestamp(i, new java.sql.Timestamp(
((java.util.Date) inValue)
.getTime()));
} else if (inValue instanceof Calendar) {
Calendar cal = (Calendar) inValue;
cs.setTimestamp(i, new java.sql.Timestamp(
cal.getTime().getTime()));
} else {
// Fall back to generic setObject call
// without SQL type specified.
cs.setObject(i, inValue);
}
}
}
if (outTypes != null) {
for (int index = 0; index < outTypes.length; index++) {
i++;
cs.registerOutParameter(i, outTypes[index]);
}
}
boolean retVal = cs.execute();
int updateCount = cs.getUpdateCount();
if (retVal || updateCount != -1) {
// Map returnedResults = new HashMap();
// returnedResults.putAll(extractReturnedResultSets(cs,
// declaredParameters, updateCount));
}
if (outTypes == null || outTypes.length <= 0) {
return null;
} else if (outTypes.length == 1) {
return cs.getObject(i);
} else {
List results = new ArrayList();
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -