📄 simpledao.java
字号:
/*
* Created on 2006-7-21 15:12:59
*
* By SinoBest
* Copyright hnisi.com.cn, 2005-2006, All rights reserved.
*/
package cn.com.juneng.system.common.util;
import java.beans.PropertyDescriptor;
import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import cn.com.juneng.system.common.COMMON;
import cn.com.juneng.system.common.exception.DBOperException;
import cn.com.juneng.system.common.exception.SystemRuleException;
/**
* @author yehailong
*
* <p>
* 一个简单实现的DAO操作 适用范围比较简单:
* <ol>
* <li>只适应单表操作
* <li>在不使用AIB工具生成的proxy/dao类的情况下,此类方可使用
* </ol>
*/
public class SimpleDAO {
private String tableName;
private Class voClass;
private String[] propNames;
private Class[] propTypes;
private String keyProp;
private Class keyType;
private static HashMap SQL_TYPES;
private static HashMap TABLE_KEYS = new HashMap();
private static DataSource dataSource=null;
private static String dataSourceJNDI="jdbc/hetong";
static {
SQL_TYPES = new HashMap();
SQL_TYPES.put(String.class, new Integer(Types.VARCHAR));
SQL_TYPES.put(Integer.class, new Integer(Types.INTEGER));
SQL_TYPES.put(Long.class, new Integer(Types.BIGINT));
SQL_TYPES.put(Float.class, new Integer(Types.FLOAT));
SQL_TYPES.put(Double.class, new Integer(Types.DOUBLE));
SQL_TYPES.put(BigDecimal.class, new Integer(Types.NUMERIC));
SQL_TYPES.put(Timestamp.class, new Integer(Types.TIMESTAMP));
SQL_TYPES.put(java.util.Date.class, new Integer(Types.DATE));
}
public static void main(String[] args) {
// SimpleDAO dao = new
// SimpleDAO("WF_PROCESS",WF_PROCESSValueObject.class);
}
public SimpleDAO() {
}
/**
* @param tableName
* @param voClass
* @throws SystemRuleException
*/
public SimpleDAO(String tableName, Class voClass) throws SystemRuleException {
this.tableName = tableName;
this.voClass = voClass;
try {
parseTable();
parseProperty();
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getSqlConnection() throws SQLException {
try{
if(dataSource==null){
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
dataSource = (DataSource)envCtx.lookup(dataSourceJNDI);
}
}catch(Exception ne){
ne.printStackTrace();
}
return dataSource.getConnection();
}
public static void closeConnection(Connection conn) {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
conn = null;
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* 解析VO CLASS的所有属性
*/
private void parseProperty() {
PropertyDescriptor propD[] = PropertyUtils
.getPropertyDescriptors(this.voClass);
String propName = null;
this.propTypes = new Class[this.propNames.length];
for (int i = 0; i < propD.length; i++) {
propName = propD[i].getName();
int index = COMMON.arrayIndexOf(this.propNames, propName);
if (index == -1) {
continue;
}
Class type = propD[i].getPropertyType();
propTypes[index] = type;
if (propName.equals(this.keyProp)) {
this.keyType = type;
}
}
}
/**
* 解析数据表的所有列
*/
private void parseTable() {
//Log.getLogger().debug(" parse the table:" + tableName);
Connection con = null;
PreparedStatement pstmt = null;
try {
// 获取表列
con = getSqlConnection();
pstmt = con.prepareStatement("select * from " + this.tableName
+ " where 1=2");
ResultSet rs = pstmt.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
this.propNames = new String[rsmd.getColumnCount()];
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
propNames[i - 1] = rsmd.getColumnName(i);
}
rs.close();
pstmt.close();
//Log.getLogger().debug(" get the table '" + tableName + "' column ok.");
// 获取主键
pstmt = con
.prepareStatement("Select a.COLUMN_NAME From User_Cons_Columns a,User_Constraints b Where a.constraint_name = b.constraint_name And a.table_name = '"
+ this.tableName + "' And b.constraint_type='P'");
rs = pstmt.executeQuery();
if (rs != null && rs.next()) {
this.keyProp = rs.getString(1);
TABLE_KEYS.put(tableName, keyProp);
}
//Log.getLogger().debug(" get the table '" + tableName + "' primary key ok.");
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(con);
}
}
/**
* 表字段字符串
*
* @return
*/
private String getColumnStr() {
StringBuffer colsBuf = new StringBuffer();
String[] props = this.propNames;
for (int i = 0; i < props.length; i++) {
colsBuf.append("," + propNames[i]);
}
return colsBuf.substring(1);
}
/**
* "?"字符串
*
* @return
*/
private String getQStr() {
StringBuffer qBuf = new StringBuffer();
String[] props = this.propNames;
for (int i = 0; i < props.length; i++) {
qBuf.append(",?");
}
return qBuf.substring(1);
}
/**
* INSERT SQL
*
* @return
*/
private String insertSql() {
StringBuffer sqlBuf = new StringBuffer();
sqlBuf.append("insert into ");
sqlBuf.append(this.tableName);
sqlBuf.append(" (");
sqlBuf.append(this.getColumnStr());
sqlBuf.append(" )");
sqlBuf.append(" values (");
sqlBuf.append(this.getQStr());
sqlBuf.append(")");
//Log.getLogger().debug(sqlBuf);
return sqlBuf.toString();
}
/**
* UPDATE SQL
*
* @return
*/
private String updateSql() {
StringBuffer sqlBuf = new StringBuffer();
sqlBuf.append("update ");
sqlBuf.append(this.tableName);
sqlBuf.append(" set ");
for (int i = 0; i < this.propNames.length; i++) {
sqlBuf.append(propNames[i] + " = ?,");
}
// 删除最后一个","
sqlBuf.deleteCharAt(sqlBuf.length() - 1);
sqlBuf.append(" where ");
sqlBuf.append(this.keyProp + " = ?");
//Log.getLogger().debug(sqlBuf);
return sqlBuf.toString();
}
/**
* SELECT SQL
*
* @return
*/
private String selectSql() {
StringBuffer sqlBuf = new StringBuffer("select ");
sqlBuf.append(this.getColumnStr());
sqlBuf.append(" from ");
sqlBuf.append(this.tableName);
// //Log.getLogger().debug(sqlBuf);
return sqlBuf.toString();
}
/**
* 检查对象的合法性
*
* @param obj
* @return
* @throws SystemRuleException
*/
private boolean checkObject(Object obj) throws SystemRuleException {
if (obj.getClass() != voClass) {
throw new SystemRuleException("ValueObject class type error!");
}
return true;
}
/**
* 对象创建 如果主建值为空,则取系统唯一ID做为主建值,否则,以当前对象的属性值做为主建值
*
* @param obj
* @return
* @throws DBOperException
* @throws SystemRuleException
*/
public Object create(Object obj) throws DBOperException, SystemRuleException {
List objList = new ArrayList();
objList.add(obj);
this.batchCreate(objList);
return obj;
}
/**
* 批量创建
*
* @param objList
* @return
* @throws DBOperException
* @throws SystemRuleException
*/
public List batchCreate(List objList) throws DBOperException,
SystemRuleException {
if (COMMON.isEmpty(objList)) {
return objList;
}
Connection con = null;
PreparedStatement pstmt = null;
try {
con = getSqlConnection();
pstmt = con.prepareStatement(insertSql());
for (int k = 0; k < objList.size(); k++) {
Object obj = objList.get(k);
checkObject(obj);
String propName = null;
Object value = null;
for (int i = 0; i < propNames.length; i++) {
propName = propNames[i];
if (propName.equals(this.keyProp)) {
// key的处理
value = PropertyUtils.getProperty(obj, propName);
if (value == null || value.equals("null")
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -