操作数据库的通用BaseDAO

package com.dao;

import java.io.InputStream;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.entity.User;

public class BaseDAO<T> {

private static String driveClassName = "com.mysql.jdbc.Driver";
private static String url = "jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=utf-8";
private static String user = "root";
private static String password = "123";
static {
try {
Class.forName(driveClassName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private Connection conn = null;

public BaseDAO() {
try {
conn = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}

}

public void save(T entity) throws Exception {

String sql = "insert into " + entity.getClass().getSimpleName().toLowerCase() + "(";
List<Method> list = this.matchPojoMethods(entity, "get");
Iterator<Method> iter = list.iterator();
while (iter.hasNext()) {
Method method = iter.next();
sql += method.getName().substring(3).toLowerCase() + ",";
}
sql = sql.substring(0, sql.lastIndexOf(",")) + ") values(";
for (int j = 0; j < list.size(); j++) {
sql += "?,";
}
sql = sql.substring(0, sql.lastIndexOf(",")) + ")";

PreparedStatement statement = conn.prepareStatement(sql);
int i = 0;
iter = list.iterator();
while (iter.hasNext()) {
Method method = iter.next();
if (method.getReturnType().getSimpleName().indexOf("String") != -1) {
statement.setString(++i, this.getString(method, entity));
} else if (method.getReturnType().getSimpleName().indexOf("Date") != -1) {
statement.setDate(++i, this.getDate(method, entity));
} else if (method.getReturnType().getSimpleName().indexOf("InputStream") != -1) {
statement.setAsciiStream(++i, this.getBlob(method, entity), 1440);
} else {
statement.setInt(++i, this.getInt(method, entity));
}
}
statement.executeUpdate();

}

public void update(T entity) throws Exception {
String sql = "update " + entity.getClass().getSimpleName().toLowerCase() + " set ";
List<Method> list = this.matchPojoMethods(entity, "get");
Method tempMethod = null;
Method idMethod = null;
Iterator<Method> iter = list.iterator();
while (iter.hasNext()) {
tempMethod = iter.next();
if (tempMethod.getName().lastIndexOf("Id") != -1 && tempMethod.getName().substring(3).length() == 2) {
idMethod = tempMethod;
iter.remove();
} else if ((entity.getClass().getSimpleName() + "Id").equalsIgnoreCase(tempMethod.getName().substring(3))) {
idMethod = tempMethod;
iter.remove();
}
}

iter = list.iterator();
while (iter.hasNext()) {
tempMethod = iter.next();
sql += tempMethod.getName().substring(3).toLowerCase() + "= ?,";
}

sql = sql.substring(0, sql.lastIndexOf(","));

sql += " where " + idMethod.getName().substring(3).toLowerCase() + " =?";
System.out.println("--" + sql);
PreparedStatement statement = conn.prepareStatement(sql);

int i = 0;
iter = list.iterator();
while (iter.hasNext()) {
Method method = iter.next();
if (method.getReturnType().getSimpleName().indexOf("String") != -1) {
statement.setString(++i, this.getString(method, entity));
} else if (method.getReturnType().getSimpleName().indexOf("Date") != -1) {
statement.setDate(++i, this.getDate(method, entity));
} else if (method.getReturnType().getSimpleName().indexOf("InputStream") != -1) {
statement.setAsciiStream(++i, this.getBlob(method, entity), 1440);
} else {
statement.setInt(++i, this.getInt(method, entity));
}
}

if (idMethod.getReturnType().getSimpleName().indexOf("String") != -1) {
statement.setString(++i, this.getString(idMethod, entity));
} else {
statement.setInt(++i, this.getInt(idMethod, entity));
}
statement.executeUpdate();
}

public void delete(T entity,String id) throws Exception {
String sql = "delete from " + entity.getClass().getSimpleName().toLowerCase() + " where id="+id;
Method idMethod = null;
List<Method> list = this.matchPojoMethods(entity, "get");
Iterator<Method> iter = list.iterator();
while (iter.hasNext()) {
Method tempMethod = iter.next();
if (tempMethod.getName().lastIndexOf("Id") != -1 && tempMethod.getName().substring(3).length() == 2) {
idMethod = tempMethod;
iter.remove();
} else if ((entity.getClass().getSimpleName() + "Id").equalsIgnoreCase(tempMethod.getName().substring(3))) {
idMethod = tempMethod;
iter.remove();
}
}

sql += idMethod.getName().substring(3).toLowerCase() + " = ?";
System.out.println("--" + sql);
PreparedStatement statement = conn.prepareStatement(sql);
int i = 0;
if (idMethod.getReturnType().getSimpleName().indexOf("String") != -1) {
statement.setString(++i, this.getString(idMethod, entity));
} else {
statement.setInt(++i, this.getInt(idMethod, entity));
}
statement.executeUpdate();
}

@SuppressWarnings("unchecked")
public List<T> findAll(T entity) throws Exception{
List<T> list=new ArrayList<T>();
String sql = "select * from " + entity.getClass().getSimpleName().toLowerCase();



PreparedStatement statement = conn.prepareStatement(sql);
ResultSet rsResultSet=statement.executeQuery(sql);
while (rsResultSet.next()) {
User user=new User();
user.setId(rsResultSet.getInt(1));
user.setUsername(rsResultSet.getString(2));
user.setPassword(rsResultSet.getString(3));
user.setNumber(rsResultSet.getString(4));
user.setPermissions(rsResultSet.getInt(5));
list.add((T) user);
}

return list;
}



public T findById(T entity, int id) throws Exception {
String sql = "select * from " + entity.getClass().getSimpleName().toLowerCase() + " where ";
Method idMethod = null;

List<Method> list = this.matchPojoMethods(entity, "set");
Iterator<Method> iter = list.iterator();

while (iter.hasNext()) {
Method tempMethod = iter.next();
if (tempMethod.getName().indexOf("Id") != -1 && tempMethod.getName().substring(3).length() == 2) {
idMethod = tempMethod;
} else if ((entity.getClass().getSimpleName() + "Id").equalsIgnoreCase(tempMethod.getName().substring(3))) {
idMethod = tempMethod;
}
}
sql += idMethod.getName().substring(3, 4).toLowerCase() + idMethod.getName().substring(4) + " = ?";
System.out.println(sql);
PreparedStatement statement = conn.prepareStatement(sql);
statement.setInt(1, id);
ResultSet rs = statement.executeQuery();

iter = list.iterator();
while (rs.next()) {
while (iter.hasNext()) {
Method method = iter.next();
if (method.getParameterTypes()[0].getSimpleName().indexOf("String") != -1) {
this.setString(method, entity, rs.getString(method.getName().substring(3).toLowerCase()));
} else if (method.getParameterTypes()[0].getSimpleName().indexOf("Date") != -1) {
this.setDate(method, entity, rs.getDate(method.getName().substring(3).toLowerCase()));
} else if (method.getParameterTypes()[0].getSimpleName().indexOf("InputStream") != -1) {
this.setBlob(method, entity,
rs.getBlob(method.getName().substring(3).toLowerCase()).getBinaryStream());
} else {
this.setInt(method, entity, rs.getInt(method.getName().substring(3).toLowerCase()));
}
}
}
return entity;
}



private List<Method> matchPojoMethods(T entity, String methodName) {
Method[] methods = entity.getClass().getDeclaredMethods();
List<Method> list = new ArrayList<Method>();
for (int index = 0; index < methods.length; index++) {
if (methods[index].getName().indexOf(methodName) != -1) {
list.add(methods[index]);
}
}
return list;
}

public Integer getInt(Method method, T entity) throws Exception {
return (Integer) method.invoke(entity, new Object[] {});
}


public String getString(Method method, T entity) throws Exception {
return (String) method.invoke(entity, new Object[] {});
}


public InputStream getBlob(Method method, T entity) throws Exception {
return (InputStream) method.invoke(entity, new Object[] {});
}


public Date getDate(Method method, T entity) throws Exception {
return (Date) method.invoke(entity, new Object[] {});
}


public Integer setInt(Method method, T entity, Integer arg) throws Exception {
return (Integer) method.invoke(entity, new Object[] { arg });
}


public String setString(Method method, T entity, String arg) throws Exception {
return (String) method.invoke(entity, new Object[] { arg });
}


public InputStream setBlob(Method method, T entity, InputStream arg) throws Exception {
return (InputStream) method.invoke(entity, new Object[] { arg });
}

public Date setDate(Method method, T entity, Date arg) throws Exception {
return (Date) method.invoke(entity, new Object[] { arg });
}

public static void main(String[] args) throws Exception {

}
}

原文地址:https://www.cnblogs.com/xyd51cto/p/7732141.html