Jdbc 템 플 릿, 동적 SQL 생 성 실현...
5821 단어 자바
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import org.ddang.util.DbUtil;
/**
* :
* 1. “tb_” + “ ”
* 2. ( , ID )
* : CRUD
* : , ,
DbUtil.
* @author Administrator
*
*/
public class JdbcTemplate {
public final static String TABLE_PREFIX = "tb_";
private String tableName = "";
private Field[] fields;
private List getFields(Object obj) {
Class c = obj.getClass();
//
String className = obj.getClass().getSimpleName();
// + =
tableName = TABLE_PREFIX + className.toLowerCase();
//
fields = c.getDeclaredFields();
Method[] method = c.getMethods();
List list = new ArrayList();
for (int j = 0; j < fields.length; j++) {
String m = "get" + fields[j].getName().toUpperCase().charAt(0)
+ fields[j].getName().substring(1);
for (int i = 0; i < method.length; i++) {
if (method[i].getName().endsWith(m)) {
// method[i].invoke("", null);
try {
list.add(method[i].invoke(obj, null));
System.out.println("---------"
+ method[i].invoke(obj, null));
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
}
return list;
}
private String getInsertSQL(Object obj) {
// SQL
StringBuffer sql = new StringBuffer();
sql.append("INSERT INTO ");
sql.append("`" + tableName + "`");
sql.append(" (");
for (int i = 0; i < fields.length; i++) {
sql.append("`" + fields[i].getName() + "`");
if (i < fields.length - 1) {
sql.append(",");
}
}
sql.append(") ");
sql.append(" VALUES(");
for (int i = 0; i < fields.length; i++) {
sql.append("?");
if (i < fields.length - 1) {
sql.append(",");
}
}
sql.append(") ");
return sql.toString();
}
private String getUpdateSQL(Object obj) {
// SQL
StringBuffer sql = new StringBuffer();
sql.append("UPDATE ");
sql.append("`" + tableName + "` ");
sql.append(" SET ");
for (int i = 1; i < fields.length; i++) {
sql.append("`" + fields[i].getName() + "`");
sql.append("=?");
if (i < fields.length - 1) {
sql.append(",");
}
}
sql.append(" WHERE ");
sql.append(fields[0].getName());
sql.append("=?");
return sql.toString();
}
private String getSelectSQL(Object obj) {
// SQL
StringBuffer sql = new StringBuffer();
sql.append("SELECT * FROM ");
sql.append("`" + tableName + "` ");
return sql.toString();
}
private String getDeleteSQL(Object obj) {
// SQL
StringBuffer sql = new StringBuffer();
sql.append("DELETE FROM ");
sql.append("`" + tableName + "` ");
sql.append(" WHERE ");
sql.append(fields[0].getName());
sql.append("=?");
return sql.toString();
}
public boolean save(Object obj) throws Exception {
// obj
List list = getFields(obj);
// sql
String sql = getInsertSQL(obj);
System.out.println(sql);
// DbUtil//
Connection conn = DbUtil.getConn();
PreparedStatement ps = conn.prepareStatement(sql);
for (int i = 1; i <= list.size(); i++) {
ps.setObject(i, list.get(i-1));
}
boolean flag = ps.executeUpdate() > 0 ? true : false;
DbUtil.close(conn);
return flag;
}
public boolean update(Object obj) throws Exception {
// obj
List list = getFields(obj);
// sql
String sql = getUpdateSQL(obj);
// DbUtil
Connection conn = DbUtil.getConn();
PreparedStatement ps = conn.prepareStatement(sql);
for (int i = 1; i < list.size(); i++) {
ps.setObject(i, list.get(i));
}
ps.setInt(list.size(), (Integer) list.get(0));
boolean flag = ps.executeUpdate() > 0 ? true : false;
DbUtil.close(conn);
return flag;
}
public List select(Object obj) throws Exception {
return select(obj,null,null);
}
public List select(Object obj,String fieldName,Object fieldValue) throws Exception {
// obj
List lists = getFields(obj);
// sql
String sql = getSelectSQL(obj);
if(fieldName != null)
sql += " WHERE `"+ fieldName +"` =?";
// DbUtil
System.out.println("SQL:"+sql);
Connection conn = DbUtil.getConn();
PreparedStatement ps = conn.prepareStatement(sql);
if(fieldName != null)
ps.setObject(1, fieldValue);
ResultSet rs = ps.executeQuery();
Class c = obj.getClass();
Method[] method = c.getMethods();
List list = new ArrayList();
while (rs.next()) {
Object o = c.newInstance();
//
for (int j = 0; j < fields.length; j++) {
String m = "set" + fields[j].getName().toUpperCase().charAt(0)
+ fields[j].getName().substring(1);
for (int i = 0; i < method.length; i++) {
if (method[i].getName().endsWith(m)) {
//System.out.println("dd"+rs.getObject(j));
try{
method[i].invoke(o, rs.getObject(j+1));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
list.add(o);
}
DbUtil.close(conn);
return list;
}
public boolean delete(Object obj,Integer id) throws Exception {
// obj
List list = getFields(obj);
// sql
String sql = getDeleteSQL(obj);
// DbUtil
Connection conn = DbUtil.getConn();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, id);
boolean flag = ps.executeUpdate() > 0 ? true : false;
DbUtil.close(conn);
return flag;
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.