.net中我写了一个EntityHelper的类,主要是新增修改获取简单实体。现在将其移植到java中,由于对java 的泛型和反射还不太熟,花了好几个小时。
数据库操作定义接口
/*
* SqlInterface.java
* 2010/4/18
*/
package com.kecq.data;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.List;
import java.util.Map;
/**
* 数据库接口
* @author 方远均
* @version 1.0
*/
public interface IDbHelper {
public Connection getCurrentConnection() throws Exception;
//查询不能带参数?
public List<Map<String, Object>> GetListMap(String sql,Object...sqlValue) throws Exception;
public ResultSet GetResultSet(String sql,Object...sqlValue) throws Exception;
public int execute(String sql, Object... sqlValue)throws Exception;
public Object getObject(String sql,String columnName,Object... sqlValue)throws Exception ;
public boolean exists(String sql,Object...sqlValue) throws Exception;
public void closeDB() throws Exception;
}EntityHelper.java
package com.kecq.data;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.kecq.common.Convert;
public class EntityHelper {
private static Object Cast(Class<?> type, Object value)
throws ParseException {
if (type == int.class) {
return Convert.toInt(value);
}
if (type == double.class) {
return Convert.toDouble(value);
}
if (type == String.class) {
return Convert.toString(value);
}
if (type == Date.class) {
return Convert.toDateTime(value);
}
return value;
}
public static <T> T getEntity(Class<T> c,ResultSet rs) throws Exception
{
List<String> fields = new ArrayList<String>();
for (Field field : c.getDeclaredFields()) {
fields.add(field.getName());
}
List<String> methods = new ArrayList<String>();
for (Method method : c.getMethods()) {
methods.add(method.getName());
}
T t = null;
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
while (rs.next()) {
t = c.newInstance();
for (int i = 1; i <= columnCount; i++) {
String columnName = rsmd.getColumnName(i);
if (fields.contains(columnName)) {
Field f = c.getDeclaredField(columnName);
// 权限修饰符
int mo = f.getModifiers();
String priv = Modifier.toString(mo);
if (priv.equals("public")) {
f.set(t, Cast(f.getType(), rs.getObject(i)));
}
String methodEnd = "set"
+ columnName.substring(0, 1).toUpperCase()
+ columnName.substring(1);
if (methods.contains(methodEnd)) {
Method m = c.getMethod(methodEnd, f.getType());
m.invoke(t, Cast(f.getType(), rs.getObject(i)));
}
}
}
}
rs.close();
return t;
}
public static <T> T getEntity(Class<T> c, Object id, String tableName,
String primary, IDbHelper db) throws Exception {
String sql = "select * from " + tableName + " where " + primary + "='"
+ id.toString().replace("'", "") + "' limit 0,1";
ResultSet rs = db.GetResultSet(sql);
return getEntity(c,rs);
}
public static <T> int insert(T t, String tableName, String primary,
Boolean isAddPrimary, IDbHelper db) throws Exception {
Class<?> c = t.getClass();
String sql = "insert into " + tableName + "(";
String v = "";
List<Object> vlist = new ArrayList<Object>();
List<String> methods = new ArrayList<String>();
for (Method method : c.getMethods()) {
methods.add(method.getName());
}
// 取得本类的全部属性
Field[] field = c.getDeclaredFields();
for (int i = 0; i < field.length; i++) {
String name = field[i].getName();
if (isAddPrimary == false && name.equalsIgnoreCase(primary)) {
continue;
}
sql += name + ",";
v += "?,";
Object value = null;
// 权限修饰符
int mo = field[i].getModifiers();
String priv = Modifier.toString(mo);
if (priv.equals("public")) {
value = field[i].get(t);
}
String methodEnd = "get" + name.substring(0, 1).toUpperCase()
+ name.substring(1);
if (methods.contains(methodEnd)) {
Method m = c.getMethod(methodEnd);
value = m.invoke(t);
}
vlist.add(value);
}
sql = sql.substring(0, sql.length() - 1) + ")";
v = v.substring(0, v.length() - 1);
sql = sql + " values (" + v + ")";
int result = db.execute(sql, vlist.toArray());
return result;
}
private static Boolean isPrimary(String name, String... primary) {
for (String s : primary) {
if (s.equalsIgnoreCase(name)) {
return true;
}
}
return false;
}
public static <T> int update(T t, String tableName, IDbHelper db,
String... primary) throws Exception {
Class<?> c = t.getClass();
String sql = "update " + tableName + " set ";
List<Object> vlist = new ArrayList<Object>();
List<String> methods = new ArrayList<String>();
for (Method method : c.getMethods()) {
methods.add(method.getName());
}
String w = " where 1=1 ";
// 取得本类的全部属性
Field[] field = c.getDeclaredFields();
for (int i = 0; i < field.length; i++) {
String name = field[i].getName();
if (isPrimary(name, primary)) {
continue;
}
sql += name + "=?,";
Object value = null;
// 权限修饰符
int mo = field[i].getModifiers();
String priv = Modifier.toString(mo);
if (priv.equals("public")) {
value = field[i].get(t);
}
String methodEnd = "get" + name.substring(0, 1).toUpperCase()
+ name.substring(1);
if (methods.contains(methodEnd)) {
Method m = c.getMethod(methodEnd);
value = m.invoke(t);
}
vlist.add(value);
}
for (int i = 0; i < field.length; i++) {
String name = field[i].getName();
if (isPrimary(name, primary)) {
w += " and " + name + "=?,";
Object value = null;
// 权限修饰符
int mo = field[i].getModifiers();
String priv = Modifier.toString(mo);
if (priv.equals("public")) {
value = field[i].get(t);
}
String methodEnd = "get" + name.substring(0, 1).toUpperCase()
+ name.substring(1);
if (methods.contains(methodEnd)) {
Method m = c.getMethod(methodEnd);
value = m.invoke(t);
}
vlist.add(value);
}
}
w = w.substring(0, w.length() - 1);
sql = sql.substring(0, sql.length() - 1);
sql = sql + w;
int result = db.execute(sql, vlist.toArray());
return result;
}
}EntityHelper的泛型EntityHelperG.java
package com.kecq.data;
import org.springframework.context.annotation.Primary;
public class EntityHelperG <T>{
private Class<?> c;
private String tableName;
private Boolean isAddPrimary;
private IDbHelper db;
private String[] primary;
public EntityHelperG(Class<?> c,String tableName,Boolean isAddPrimary, IDbHelper db, String...primary)
{
this.c=c;
this.tableName=tableName;
this.isAddPrimary=isAddPrimary;
this.db=db;
this.primary=primary;
}
public T getEntity(Object id) throws Exception
{
T t=(T) EntityHelper.getEntity(c, id, tableName, primary[0], db);
return t;
}
public int insert(T t) throws Exception
{
return EntityHelper.insert(t, tableName, primary[0], isAddPrimary, db);
}
public int update(T t) throws Exception
{
return EntityHelper.update(t, tableName, db, primary);
}
}调用
DataInfo info = new DataInfo();
info.setDirverName("com.mysql.jdbc.Driver");
info.setConStr("jdbc:mysql://localhost:3306/db_fyj?characterEncoding=utf-8");
info.setUsername("root");
info.setPassword("xxxxxx");
IDbHelper db = new DbHelper(info);
EntityHelperG<blog_tb_blog> h=new EntityHelperG<blog_tb_blog>(blog_tb_blog.class,"blog_tb_blog",true,db,"blogID");
blog_tb_blog b = h.getEntity("222");
b.setBlogName("fyj3333");
int result = h.update(b);
珂珂的个人博客 - 一个程序猿的个人网站