根据JavaBean创建数据库的操作SQL
import java.lang.reflect.Field; public class GenerateSQL { public static void main(String[] args) { Field[] fileds = User.class.getDeclaredFields();
System.out.println(generateFieldsLine(fileds));
System.out.println(generateInsertSql("user", fileds, "user"));
System.out.println(generateUpdateSql("user", fileds, "user")); } public static String generateFieldsLine(Field[] fileds) {
StringBuffer sqlBuilder = new StringBuffer();
for (int i = 0, size = fileds.length; i < size; i++) {
if (i == fileds.length - 1) {
sqlBuilder.append(fileds[i].getName());
continue;
}
sqlBuilder.append(fileds[i].getName()).append(",");
}
return sqlBuilder.toString();
} /**
* @param tableName 数据库表名
* @param fileds 字段数组
* @param beanName mybatis的mapper参数名字
* @return
*/
public static String generateInsertSql(String tableName, Field[] fileds, String beanName) {
String sql = "INSERT INTO " + tableName + "(" + generateFieldsLine(fileds) + ") values ("; StringBuffer sqlBuilder = new StringBuffer();
for (int i = 0, size = fileds.length; i < size; i++) {
if (i == fileds.length - 1) {
sqlBuilder.append("#{" + beanName).append(".").append(fileds[i].getName()).append("}");
continue;
}
sqlBuilder.append("#{" + beanName).append(".").append(fileds[i].getName()).append("}").append(",");
}
return sql + sqlBuilder.toString() + ")";
} public static String generateSelectSQL(String tableName, Field[] fileds) {
StringBuilder sqlBuilder = new StringBuilder();
return sqlBuilder.append("SELECT ").append(generateFieldsLine(fileds)).append(" FROM ").append(tableName).toString();
} public static String generateUpdateSql(String tableName, Field[] fileds, String beanName) {
String sql = "UPDATE " + tableName + " SET "; StringBuffer sqlBuilder = new StringBuffer();
for (int i = 0, size = fileds.length; i < size; i++) {
if (i == fileds.length - 1) {
sqlBuilder.append(fileds[i].getName()).append("=").append("#{" + beanName).append(".").append(fileds[i].getName()).append("}");
continue;
}
sqlBuilder.append(fileds[i].getName()).append("=").append("#{" + beanName).append(".").append(fileds[i].getName()).append("}").append(",");
}
return sql + sqlBuilder.toString() + ")";
} }