您的位置:首页 > 编程语言 > Java开发

java反射生成DAO【demo】

2016-05-05 21:36 459 查看

java反射生成DAO【demo】

java反射生成DAOdemo
java注解和反射制作dao基类的练习

java 反射写的 通用DAO 类

java注解和反射制作dao基类的练习

转载地址:

http://my.oschina.net/mfkwfc/blog/60885?p=1

java 反射写的 通用DAO 类

转载地址:

http://www.xuebuyuan.com/815211.html

Demo:

//DAO.java
package com.reflect;

import java.util.ArrayList;
import java.util.LinkedHashMap;

public interface DAO {
/**
* 获取总记录总数
*
* @param entityClass
*            实体类
* @return
*/
public <T> long getCount(Class<T> entityClass);

public <T> long getCount(Class<T> entityClass, String wherejpql, Object[] queryParams);

/**
* 保存实体
*
* @param entity
*/
public void save(Object entity);

/**
* 更新
*
* @param obj
*/
public void update(Object entity, String[] primaryKeys);

public void update(Object entity, String primaryKey);

/**
* 删除单个
*
* @param <T>
* @param entityClass
* @param primaryKeys
* @param entityid
*/
public <T> void delete(Class<T> entityClass, String primaryKeys, Object entityid);

public <T> void delete(Class<T> entityClass, String[] primaryKeys, Object[] entityid);

public <T> void deletes(Class<T> entityClass, String primaryKeys, Object[] entityids);

/**
* 删除数组
*
* @param <
4000
;T>
* @param entityClass
* @param primaryKeys
*            数据表 主键数组
* @param entityids
*            主键值
*/
public <T> void deletes(Class<T> entityClass, String[] primaryKeys, Object[][] entityids);

/**
* 得到实体
*
* @param <T>
* @param entityClass
*            实体类
* @param entityId
*            实体id
* @return
*/
public <T> T find(Class<T> entityClass, String primaryKey, Object entity);

/**
* 获取分页数据
*
* @param <T>
* @param entityClass
*            实体类
* @param firstindex
*            开始索引
* @param maxresult
*            需要获取的记录数
* @return
*/
public <T> ArrayList<T> getScrollData(Class<T> entityClass, int firstindex, int maxresult, String wherejpql,
Object[] queryParams, LinkedHashMap<String, String> orderby);

public <T> ArrayList<T> getScrollData(Class<T> entityClass, int firstindex, int maxresult, String wherejpql,
Object[] queryParams);

public <T> ArrayList<T> getScrollData(Class<T> entityClass, int firstindex, int maxresult,
LinkedHashMap<String, String> orderby);

public <T> ArrayList<T> getScrollData(Class<T> entityClass, int firstindex, int maxresult);

public <T> ArrayList<T> getScrollData(Class<T> entityClass);

/**
* 关闭数据库 连接
*
*/
public void closeConnection();
}


//DaoSupport.java
package com.reflect;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
public class DaoSupport implements DAO {

// conMysql为连接数据库工具类,此处未完成,需要自行编写
class conMysql {
Connection getConnection() {
return conn;
}
}

private Connection conn = null;
private PreparedStatement psmt = null;
private ResultSet rs = null;
public DaoSupport() {
conMysql con = new conMysql();
conn = con.getConnection();
}
public <T> void delete(Class<T> entityClass, String[] primaryKeys,
Object[] entityid) {
// TODO Auto-generated method stub
this.deletes(entityClass, primaryKeys, new Object[][] { entityid });
}
public <T> void deletes(Class<T> entityClass, String[] primaryKeys,
Object[][] entityids) {
// TODO Auto-generated method stub
StringBuffer sql = new StringBuffer("delete from ");
sql.append(this.getTable(entityClass)).append(" where ");
for (String primaryKey : primaryKeys) {
sql.append(primaryKey).append("=").append("?").append(" and ");
}
sql.delete(sql.length() - 5, sql.length());
System.out.println(sql);
try {
psmt = conn.prepareStatement(sql.toString());
for (Object[] entityid : entityids) {
for (int i = 0; i < primaryKeys.length; i++) {
psmt.setString(i + 1, String.valueOf(entityid[i]));
}
psmt.executeUpdate();
}
if (rs != null) {
rs.close();
}
if (psmt != null) {
psmt.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}
if (psmt != null) {
psmt.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public <T> long getCount(Class<T> entityClass) {
return this.getCount(entityClass, null, null);
}
public <T> long getCount(Class<T> entityClass, String wherejpql,
Object[] queryParams) {
long count = 0;
try {
psmt = conn.prepareStatement("selcet count(*) from "
+ this.getTable(entityClass)
+ (wherejpql == null ? "" : " where " + wherejpql));
if (queryParams != null) {
for (int i = 0; i < queryParams.length; i++) {
psmt.setString(i + 1, String.valueOf(queryParams[i]));
}
}
rs = psmt.executeQuery();
rs.next();
count = rs.getLong(1);
if (rs != null) {
rs.close();
}
if (psmt != null) {
psmt.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
rs = null;
}
if (psmt != null) {
psmt.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return count;
}
public <T> T find(Class<T> entityClass, String primaryKey, Object entity) {
StringBuffer sql = new StringBuffer("select * from ");
sql.append(this.getTable(entityClass)).append(" where ").append(
primaryKey).append("=").append("'").append(
String.valueOf(entity)).append("'");
Method[] methods = entityClass.getDeclaredMethods();
T obj = null;
System.out.println(sql);
try {
psmt = conn.prepareStatement(sql.toString());
rs = psmt.executeQuery();
while (rs.next()) {
try {
obj = entityClass.newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (Method method : methods) {
// System.out.println(method.getName().matches("/w"));
String methodName = method.getName();
if (methodName.startsWith("set")) {
String column = this.getColumn(methodName);
if (rs.getString(column) != null) {
Object[] objs = this.findOutParamValue(rs
.getString(column), method);
try {
method.invoke(obj, objs);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return obj;
}
/**
* 查询出,与实体entity 具有相同属性值的 项
* @param <T>
* @param entityClass
* @param entity
* @return
*/
public <T> ArrayList<T> finds(Class<T> entityClass, Object entity) {
ArrayList<T> arraylist = new ArrayList<T>();
Method[] methods = entity.getClass().getDeclaredMethods();
StringBuffer sql = new StringBuffer("select * from ");
sql.append(this.getTable(entityClass)).append(" where ");
for (Method method : methods) {
if (method.getName().startsWith("get")) {
Object[] args = new Object[] {};
try {
Object values = method.invoke(entity, args);
if (values != null) {
String column = this.getColumn(method.getName());
sql.append(column).append("=");
// 为字符串的时候,添加''
if (values.getClass().getSimpleName().equals("String")) {
sql.append("'").append(String.valueOf(values))
.append("
107d2
'").append(" and ");
} else {
sql.append(String.valueOf(values)).append(" and ");
}
}
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
sql.delete(sql.length() - 5, sql.length());
System.out.println(sql);
T obj = null;
try {
psmt = conn.prepareStatement(sql.toString());
rs = psmt.executeQuery();
while (rs.next()) {
try {
obj = entityClass.newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (Method method : methods) {
// System.out.println(method.getName().matches("/w"));
String methodName = method.getName();
if (methodName.startsWith("set")) {
String column = this.getColumn(methodName);
if (rs.getString(column) != null) {
Object[] objs = this.findOutParamValue(rs
.getString(column), method);
try {
method.invoke(obj, objs);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
arraylist.add(obj);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return arraylist;
}
public <T> ArrayList<T> getScrollData(Class<T> entityClass, int firstindex,
int maxresult, LinkedHashMap<String, String> orderby) {
// TODO Auto-generated method stub
return this.getScrollData(entityClass, firstindex, maxresult, null,
null, orderby);
}
public <T> ArrayList<T> getScrollData(Class<T> entityClass, int firstindex,
int maxresult, String wherejpql, Object[] queryParams,
LinkedHashMap<String, String> orderby) {
ArrayList<T> arraylist = new ArrayList<T>();
Method[] methods = entityClass.getDeclaredMethods();
String limit = "";
if (firstindex != -1 && maxresult != -1)
limit = " limit " + firstindex + "," + maxresult;
try {
psmt = conn.prepareStatement("select * from "
+ getTable(entityClass)
+ (wherejpql == null ? "" : " where " + wherejpql)
+ buildOrderby(orderby) + limit);
if (queryParams != null) {
for (int i = 0; i < queryParams.length; i++) {
psmt.setString(i + 1, String.valueOf(queryParams[i]));
}
}
rs = psmt.executeQuery();
while (rs.next()) {
T obj = null;
try {
obj = entityClass.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
for (Method method : methods) {
// System.out.println(method.getName().matches("/w"));
String methodName = method.getName();
if (methodName.startsWith("set")) {
String column = this.getColumn(methodName);
if (rs.getString(column) != null) {
Object[] objs = this.findOutParamValue(rs
.getString(column), method);
try {
method.invoke(obj, objs);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
arraylist.add(obj);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
rs = null;
}
if (psmt != null) {
psmt.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return arraylist;
}
public <T> ArrayList<T> getScrollData(Class<T> entityClass, int firstindex,
int maxresult, String wherejpql, Object[] queryParams) {
// TODO Auto-generated method stub
return this.getScrollData(entityClass, firstindex, maxresult,
wherejpql, queryParams, null);
}
public <T> ArrayList<T> getScrollData(Class<T> entityClass, int firstindex,
int maxresult) {
// TODO Auto-generated method stub
return this.getScrollData(entityClass, firstindex, maxresult, null,
null, null);
}
public <T> ArrayList<T> getScrollData(Class<T> entityClass) {
return this.getScrollData(entityClass, -1, -1, null, null, null);
}
public void save(Object entity) {
Method[] methods = entity.getClass().getMethods();
String table = this.getTable(entity.getClass());
StringBuffer sql = new StringBuffer("insert into ").append(table);
StringBuffer sql1 = new StringBuffer("(");
StringBuffer sql2 = new StringBuffer("(");
for (Method method : methods) {
if (method.getName().startsWith("get")
&& (!method.getName().equals("getClass"))) {
Object[] args = new Object[] {};
try {
Object values = method.invoke(entity, args);
if (values != null) {
String column = this.getColumn(method.getName());
sql1.append(column).append(",");
// 为字符串的时候,添加''
if (values.getClass().getSimpleName().equals("String")) {
sql2.append("'").append(String.valueOf(values))
.append("'").append(",");
} else {
sql2.append(String.valueOf(values)).append(",");
}
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
sql1.deleteCharAt(sql1.length() - 1).append(")");
sql2.deleteCharAt(sql2.length() - 1).append(")");
sql.append(" ").append(sql1).append(" values").append(sql2);
System.out.println(sql);
try {
psmt = conn.prepareStatement(sql.toString());
psmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
rs = null;
}
if (psmt != null) {
psmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public void update(Object entity, String[] primaryKeys) {
StringBuffer wheresql = new StringBuffer(" where ");
StringBuffer sql0 = new StringBuffer(" ");
Field[] fields = entity.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
// Class Type = field.getType();
Object value = null;
try {
// value = Type.cast(field.get(entity)); 强制类型转换
value = field.get(entity);
if ((!field.getName().equals("primaryKeys")) && value != null) {
if (field.getType().getSimpleName().equals("String")) {
sql0.append(field.getName()).append("=").append("'")
.append(String.valueOf(value)).append("'")
.append(",");
} else {
sql0.append(field.getName()).append("=").append(
String.valueOf(value)).append(",");
}
}
for (String primaryKey : primaryKeys) {
if (field.getName().endsWith(primaryKey) && (value != null)) {
if (field.getType().getSimpleName().equals("String")) {
wheresql.append(primaryKey).append("=").append("'")
.append(String.valueOf(value)).append("' ")
.append("and");
} else {
wheresql.append(primaryKey).append("=").append(
String.valueOf(value)).append(" and ");
}
}
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
wheresql.delete(wheresql.length() - 5, wheresql.length());
String table = this.getTable(entity.getClass());
StringBuffer sql = new StringBuffer("update ").append(table).append(
" set ");
sql.append(sql0).deleteCharAt(sql.length() - 1).append(wheresql);
System.out.println(sql);
try {
psmt = conn.prepareStatement(sql.toString());
psmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
rs = null;
}
if (psmt != null) {
psmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 转换为对应类型的值
*
* @param param
* @param method
* @return
*/
private Object[] findOutParamValue(String param, Method method) {
Class[] params = method.getParameterTypes();
Object[] objs = new Object[params.length];
for (int i = 0; i < params.length; i++) {
// System.out.println(params.length);
// System.out.println(param);
if (params[i] == String.class) {
objs[i] = param;
} else if (params[i] == Integer.TYPE) {
// int temp = Integer.parseInt(param);
objs[i] = new Integer(param);
} else if (params[i] == Short.TYPE) {
objs[i] = new Short(param);
} else if (params[i] == Float.TYPE) {
objs[i] = new Float(param);
} else if (params[i] == Double.TYPE) {
objs[i] = new Double(param);
} else if (params[i] == Boolean.TYPE) {
objs[i] = new Boolean(param);
} else if (params[i] == Long.TYPE) {
objs[i] = new Long(param);
}
}
return objs;
}
/**
* 通过get or set 方法 得到数据表列名
*
* @param name
* @return
*/
private String getColumn(String name) {
String newname = name.substring(3);
if (newname.matches("//w[A-Z].*")) {
return newname;
} else {
char[] temp = newname.toCharArray();
if ('A' <= temp[0] && temp[0] <= 'Z') {
temp[0] = (char) ((int) temp[0] + 32);
}
return new String(temp);
}
}
/**
* 得到表名
*
* @param entityClass
* @return
*/
private String getTable(Class entityClass) {
String entityName = entityClass.getSimpleName();
return entityName.substring(0, entityName.length() - 2);
}
/**
* 组装order by语句
*
* @param orderby
* @return
*/
protected String buildOrderby(LinkedHashMap<String, String> orderby) {
StringBuffer orderbyql = new StringBuffer("");
if (orderby != null && orderby.size() > 0) {
orderbyql.append(" order by ");
for (String key : orderby.keySet()) {
orderbyql.append(key).append(" ").append(orderby.get(key))
.append(",");
}
orderbyql.deleteCharAt(orderbyql.length() - 1);
}
return orderbyql.toString();
}
public void closeConnection() {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// 强制类型转换
// public static <T> T cast(Class<T> clazz, Object obj) {
// return clazz.cast(obj);
// }
public void update(Object entity, String primaryKey) {
this.update(entity, new String[] { primaryKey });
}
public <T> void delete(Class<T> entityClass, String primaryKeys,
Object entityid) {
this.delete(entityClass, new String[] { primaryKeys },
new Object[] { entityid });
}
public <T> void deletes(Class<T> entityClass, String primaryKeys,
Object[] entityids) {
this.delete(entityClass, new String[] { primaryKeys }, entityids);
}
}


//测试用 voardVO.java
package com.reflect;

public class boardVO {
// public String[] primaryKeys = {"boardID","boardRootID"};
// public String primaryKeys = "boardID";
private Integer boardID; // 模块ID
private String boardType; // varchar(30) not null, -- 模块类型
private String boardName; // varchar(30) not null, -- 模块名
private Integer boardRootID; // int(3) DEFAULT 0, -- 父节点
private Integer boardOrders; // int(3) DEFAULT 0, -- 模块排序
private String boardInfo; // varchar(600), -- 模块信息

public boardVO() {
}

public boardVO(String boardType, String boardName, int boardRootID, String boardInfo) {
this.boardType = boardType;
this.boardName = boardName;
this.boardRootID = boardRootID;
this.boardInfo = boardInfo;
}

public String getBoardInfo() {
return boardInfo;
}

public void setBoardInfo(String boardInfo) {
this.boardInfo = boardInfo;
}

public String getBoardName() {
return boardName;
}

public void setBoardName(String boardName) {
this.boardName = boardName;
}

public Integer getBoardOrders() {
return boardOrders;
}

public void setBoardOrders(int boardOrders) {
this.boardOrders = boardOrders;
}

public Integer getBoardRootID() {
return boardRootID;
}

public void setBoardRootID(int boardRootID) {
this.boardRootID = boardRootID;
}

public String getBoardType() {
return boardType;
}

public void setBoardType(String boardType) {
this.boardType = boardType;
}

public Integer getBoardID() {
return boardID;
}

public void setBoardID(int boardID) {
this.boardID = boardID;
}
}


Markdown编辑器
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: