重温Java持久化(二)

2014-11-24 08:36:39 · 作者: · 浏览: 2

}finally {
closeAll(connection, ps, null);
}
return num;
}
/**
* 为PreparedStatement对象填充参数
* @param ps
* @param param
* @throws SQLException
*/
public void buildPreparedStatement(PreparedStatement ps, Object... params) throws SQLException {
// 设置参数
for (int i = 0; i < params.length; i++) {
// 将Date转换成java.sql.Date
if (params[i] instanceof Date) {
Date d = (Date) params[i];
ps.setObject(i + 1, new Timestamp(d.getTime()));
} else {
ps.setObject(i + 1, params[i]);
}
}
}
/**
* 执行查询操作
* @param sql
* @param param
* @return RowSet
* @throws SQLException
* @throws ClassNotFoundException
*/
public RowSet executeQuery(String sql, Object... params) throws SQLException, ClassNotFoundException {
Connection connection = null;
PreparedStatement ps = null;
ResultSet rs = null;
RowSet rowset = null;
try {
connection = this.getConn();
ps = connection.prepareStatement(sql);
buildPreparedStatement(ps, params);
logger.info("Oper: " + sql);
rs = ps.executeQuery();
rowset = populate(rs);
} catch (SQLException e) {
throw e;
} catch (ClassNotFoundException e) {
throw e;
} finally {
closeAll(connection, ps, rs);
}
return rowset;
}
/**
* 将ResultSet转换为RowSet对象
* @param rs
* @return RowSet
* @throws SQLException
*/
public RowSet populate(ResultSet rs) throws SQLException {
CachedRowSetImpl crs = new CachedRowSetImpl();
crs.populate(rs);
return crs;
}
/**
* 从RowSet中获取列头
* @param rs
* @return ArrayList
* @throws SQLException
* @throws ErpServerException
*/
public List getRowSetColName(RowSet rs) throws SQLException {
ArrayList collist = new ArrayList();
for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {
collist.add(rs.getMetaData().getColumnName(i + 1).toUpperCase());
}
return collist;
}
}
=====================================
/**
* 用于创建表的辅助类
*
* @author ypf
*/
public class TableHelper {
private Logger log = Logger.getLogger(TableHelper.class.getName());
private Session session;
public TableHelper(Session session) {
this.session = session;
}
/**
* 创建表
* @param
* @param clazz
*/
public void createTable(Class clazz) {
String tableName = "";
if (clazz.isAnnotationPresent(Table.class)) {
Table table = (Table) clazz.getAnnotation(Table.class);
tableName = table.name();
} else {
return;
}
StringBuilder sb = new StringBuilder();
// 用来判断表是否存在,如果存在则不执行改操作
sb.append("CREATE TABLE ").append(tableName).append(" (");
List allFields = ClassUtil.joinFields(clazz);
for (Field field : allFields) {
if (!field.isAnnotationPresent(Column.class)) {
continue;
}
Column column = (Column) field.getAnnotation(Column.class);
String columnType = "";
// 判断column的type字段是否为空,如果为空则根据字段的值将其转换为对应的数据库类型
if (column.type().equals(""))
columnType = getColumnType(field.getType());
else {
columnType = getColumnType(column.type());
}
sb.append(column.name() + " " + columnType);
if (column.length() != 0) {
sb.append("(" + column.length() + ")");
}
// 添加主键
if (field.isAnnotationPresent(Id.class)) {
sb.append(" PRIMARY KEY");
}
sb.append(", ");