使用过Hibernate,EF之类的ORM框架都知道一般的CRUD之类的简单操作,只要调用框架封装好了的方法,框架就自动生成相应的SQL语句了,参照实习公司给的代码,那个是C#版的,今天弄了一下java的,这里介绍怎么从实体转换为标准的Insert SQL语句,其他的也差不多
思路很简单:只要获取得了实例化后的类的信息,之后再进行组装
关于如何获取java类信息,我参照了:java获取对象属性类型、属性名称、属性值 这篇博客
由于个人水平的问题,这里还有一些bug:
1.约定实体的主键命名为“id”且由数据库库自动生成(如果想要自己设置id的值可以注释下面的代码),这里可以进行判断,不过有点麻烦就算了,所以自己弄了一个约定
if (list.get(i).get("f_name").toString() == "id") i++;
2.属性类型为数值类型时,没有手动赋值时会自动赋值为0,所以期待大神们帮忙解决
在代码里面也有标注;
下面是示例,这里我只写了生成Insert语句的方法,如下:
为了演示代码的通用性,首先准备两个不同的实体类:User 和 Book
User类:
-
package com.tan.ctesql;
-
-
public class User {
-
private int id;
-
private String name;
-
private String email;
-
private String sex;
-
-
public int getId() {
-
return id;
-
}
-
-
public void setId(int id) {
-
this.id = id;
-
}
-
-
public String getName() {
-
return name;
-
}
-
-
public void setName(String name) {
-
this.name = name;
-
}
-
-
public String getEmail() {
-
return email;
-
}
-
-
public void setEmail(String email) {
-
this.email = email;
-
}
-
-
public String getSex() {
-
return sex;
-
}
-
-
public void setSex(String sex) {
-
this.sex = sex;
-
}
-
-
}
-
Book类:
-
package com.tan.ctesql;
-
-
public class Book {
-
private int id;
-
private String name;
-
private String date;
-
private float price;
-
-
public int getId() {
-
return id;
-
}
-
public void setId(int id) {
-
this.id = id;
-
}
-
public String getName() {
-
return name;
-
}
-
public void setName(String name) {
-
this.name = name;
-
}
-
public String getDate() {
-
return date;
-
}
-
public void setDate(String date) {
-
this.date = date;
-
}
-
public float getPrice() {
-
return price;
-
}
-
public void setPrice(float price) {
-
this.price = price;
-
}
-
-
-
}
-
下面就是生成SQL语句的方法了:
-
package com.tan.ctesql;
-
-
import java.lang.reflect.Field;
-
import java.lang.reflect.Method;
-
import java.util.ArrayList;
-
import java.util.HashMap;
-
import java.util.List;
-
import java.util.Map;
-
-
public class CreateInsert<T> {
-
-
public String createinsert(T entity) {
-
-
String sql = "Insert into ";
-
String column = ""; // 列
-
String c_values = ""; // 列值
-
List<Map<String, Object>> list = getFiledsInfo(entity);
-
sql += list.get(0).get("obj_name").toString() + " ";
-
for (int i = 0; i < list.size(); i++) {
-
-
//約定id在數據庫自動生成-20130807
-
-
if (list.get(i).get("f_name").toString() == "id")
-
i++;
-
if (list.get(i).get("f_value") != null) {
-
-
// System.out.println("属性数据类型:" + list.get(i).get("f_type"));
-
column += list.get(i).get("f_name") + ",";
-
c_values += "'" + list.get(i).get("f_value") + "',";
-
}
-
-
}
-
sql += "(" + column.substring(0, column.length() - 1) + ") values ("
-
+ c_values.substring(0, c_values.length() - 1) + ");";
-
-
return sql;
-
}
-
-
/**
-
* 根据属性名获取属性值
-
* */
-
protected Object getFieldValueByName(String fieldName, Object o) {
-
try {
-
String firstLetter = fieldName.substring(0, 1).toUpperCase();
-
String getter = "get" + firstLetter + fieldName.substring(1);
-
Method method = o.getClass().getMethod(getter, new Class[] {});
-
Object value = method.invoke(o, new Object[] {});
-
return value;
-
} catch (Exception e) {
-
// log.error(e.getMessage(), e);
-
return null;
-
}
-
}
-
-
/**
-
* 类名(obj_name)获取属性类型(f_type),属性名(f_name),属性值(f_value)的map组成的list
-
* */
-
@SuppressWarnings("unused")
-
protected List getFiledsInfo(Object o) {
-
-
String obj_name = o.getClass().getSimpleName().toString();
-
Field[] fields = o.getClass().getDeclaredFields();
-
String[] fieldNames = new String[fields.length];
-
List<Map> list = new ArrayList();
-
Map<String, Object> infoMap;
-
-
for (int i = 0; i < fields.length; i++) {
-
infoMap = new HashMap<String, Object>();
-
-
infoMap.put("obj_name", obj_name);
-
infoMap.put("f_type", fields[i].getType().toString());
-
infoMap.put("f_name", fields[i].getName());
-
infoMap.put("f_value", getFieldValueByName(fields[i].getName(), o));
-
list.add(infoMap);
-
}
-
return list;
-
}
-
-
// // 判断属性类型
-
// protected boolean checkType(String f_type) {
-
// if (f_type.equals("int") || f_type.equals("float")
-
// || f_type.equals("double")) {
-
//
-
// return true;
-
// }
-
// return false;
-
// }
-
//
-
// // 轉換
-
// protected boolean convert(String f_value) {
-
//
-
// if (Integer.parseInt(f_value) == 0)
-
// return false;
-
// return true;
-
//
-
// }
-
-
}
-
最后是测试代码:
-
package com.tan.ctesql;
-
-
import static org.junit.Assert.*;
-
-
import java.text.SimpleDateFormat;
-
import java.util.Date;
-
import java.util.Iterator;
-
import java.util.List;
-
import java.util.Map;
-
-
import org.junit.Test;
-
-
public class MyTest {
-
-
@Test
-
public void test() {
-
// fail("Not yet implemented");
-
-
User user = new User();
-
//user.setId(1);
-
user.setName("Tan");
-
user.setEmail("tan@sina.cn");
-
user.setSex("boy");
-
-
Date dt = new Date();
-
SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
-
-
Book book = new Book();
-
book.setName("精通SQL");
-
book.setPrice(100);
-
book.setDate(sf.format(dt));
-
-
CreateInsert ci = new CreateInsert();
-
// User
-
System.out.println("生成User的插入SQL語句:" + ci.createinsert(user));
-
//Book
-
System.out.println("生成Book的插入SQL語句:" + ci.createinsert(book));
-
-
}
-
}
-
测试结果:
原文地址:https://blog.csdn.net/mr_tank_/article/details/9816771