ORMapping框架简单实现,利用java反射机制
ZBean.java 类注解对应数据库表
package com.seagate.client.dao.ormapping.anotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface ZBean {
String value();
}
ZField.java 变量注解对应数据库列
package com.seagate.client.dao.ormapping.anotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ZField {
String value();
}
Tools.java 工具类获取注解表名,列字段及get、set方法
package com.seagate.client.dao.ormapping.anotation;
import java.lang.reflect.Field;
public class Tools {
public static String getTable(Class clazz) {
String tableName = "";
ZBean huHuBean = clazz.getAnnotation(ZBean.class);
if (huHuBean != null) {
// 获取注解中的值
tableName = huHuBean.value();
} else {
// 如果为空,就直接获取类名
tableName = clazz.getSimpleName();
}
return tableName;
}
/**
* 根据注解获取属性名称
*
* @param field
* @return
*/
public static String getColumn(Field field) {
String column = "";
ZField huHuField = field.getAnnotation(ZField.class);
if (huHuField != null) {
// 获取注解中的值
column = huHuField.value();
} else {
// 如果为空,就直接获取字段名
column = field.getName();
}
return column;
}
/**
* 根据字段获取对应的get方法
*
* @param field
* @return
*/
public static String getMethod(Field field) {
String fieldName = field.getName();
// id==>getId
// name==>getNamet
String name = fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);
return "get" + name;
}
public static String setMethod(Field field) {
String fieldName = field.getName();
// id==>getId
// name==>getNamet
String name = fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);
return "set" + name;
}
}
OrMappingInterface.java
package com.seagate.client.dao.ormapping.dao;
import java.io.Serializable;
import java.util.List;
public interface OrMappingInterface {
Serializable save(T t) throws Exception;
Serializable save(List t) throws Exception;
Serializable update(T t) throws Exception;
Serializable delete(T t) throws Exception;
//query运用的场景会比较多,因此直接传入sql,返回对象,不做代码级的运算解析
List query(String sql, Class clazz) throws Exception;
}
package com.seagate.client.dao.ormapping.dao;
import java.io.Serializable;
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 com.seagate.client.common.DataSource;
import com.seagate.client.dao.ormapping.anotation.Tools;
public class OrMappingService implements OrMappingInterface {
@Override
public Serializable save(T t) throws Exception{
StringBuilder builder = new StringBuilder("insert into ");
String table = Tools.getTable(t.getClass());
builder.append(table).append(" (");
Class clazz = t.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
if (!field.getName().equals("id")) {
String column = Tools.getColumn(field);
builder.append(column).append(",");
}
}
builder.deleteCharAt(builder.toString().length()-1)
.append(") values (");
for (Field field : fields) {
if (!field.getName().equals("id")) {
builder.append("?,");
}
}
builder.deleteCharAt(builder.toString().length()-1)
.append(")");
Connection connection = null;
PreparedStatement pstmt = null;
ResultSet rs =null;
int index = 1;
try {
connection = DataSource.getPostgresConnection();
pstmt = connection.prepareStatement(builder.toString(), new String[]{"id"});
for (Field field : fields) {
if (!field.getName().equals("id")) {
String getMethod = Tools.getMethod(field);
Method method = clazz.getDeclaredMethod(getMethod);
Object obj = method.invoke(t);
pstmt.setObject(index++, obj);
}
}
int rowCount = pstmt.executeUpdate();
System.out.println("rowCount: " + rowCount);
if (rowCount > 0) {
rs = pstmt.getGeneratedKeys();
rs.next();
int id = Integer.parseInt(rs.getObject(1).toString());
for (Field field : fields) {
if (field.getName().equals("id")) {
String setMethod = Tools.setMethod(field);
Method method = clazz.getDeclaredMethod(setMethod,Integer.class);
method.invoke(t,id);
break;
}
}
}
} catch (Exception e) {
throw e;
} finally{
DataSource.close(connection, pstmt);
}
return null;
}
@Override
public Serializable save(List t) throws Exception{
StringBuilder builder = new StringBuilder("insert into ");
String table = Tools.getTable(t.get(0).getClass());
builder.append(table).append(" (");
Class clazz = t.get(0).getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
if (!field.getName().equals("id")) {
String column = Tools.getColumn(field);
builder.append(column).append(",");
}
}
builder.deleteCharAt(builder.toString().length()-1)
.append(") values (");
for (Field field : fields) {
if (!field.getName().equals("id")) {
builder.append("?,");
}
}
builder.deleteCharAt(builder.toString().length()-1)
.append(")");
Connection connection = null;
PreparedStatement pstmt = null;
int index = 1;
try {
connection = DataSource.getPostgresConnection();
pstmt = connection.prepareStatement(builder.toString());
for(T st: t){
for (Field field : fields) {
if (!field.getName().equals("id")) {
String getMethod = Tools.getMethod(field);
Method method = clazz.getDeclaredMethod(getMethod);
Object obj = method.invoke(st);
pstmt.setObject(index++, obj);
}
}
pstmt.addBatch();
index = 1;
}
pstmt.executeBatch();
} catch (Exception e) {
throw e;
} finally{
DataSource.close(connection, pstmt);
}
return null;
}
@Override
public Serializable update(T t) throws Exception{
String table = Tools.getTable(t.getClass());
StringBuilder builder = new StringBuilder("update "+table+" set ");
Class clazz = t.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
if (!field.getName().equals("id")) {
String column = Tools.getColumn(field);
builder.append(column+"= ?,");
}
}
builder.deleteCharAt(builder.toString().length()-1);
builder.append(" where id=?");
Connection connection = null;
PreparedStatement pstmt = null;
int index = 1;
try {
connection = DataSource.getPostgresConnection();
pstmt = connection.prepareStatement(builder.toString());
for (Field field : fields) {
String getMethod = Tools.getMethod(field);
Method method = clazz.getDeclaredMethod(getMethod);
Object obj = method.invoke(t);
if (!field.getName().equals("id")) {
pstmt.setObject(index++, obj);
}else{
pstmt.setObject(fields.length, obj);
}
}
pstmt.execute();
} catch (Exception e) {
throw e;
} finally{
DataSource.close(connection, pstmt);
}
return null;
}
@Override
public Serializable delete(T t) throws Exception{
String table = Tools.getTable(t.getClass());
Class clazz = t.getClass();
Field[] fields = clazz.getDeclaredFields();
int id = 0;
for (Field field : fields) {
if (field.getName().equals("id")) {
String getMethod = Tools.getMethod(field);
Method method = clazz.getDeclaredMethod(getMethod);
id = Integer.parseInt(method.invoke(t).toString());
break;
}
}
StringBuilder builder = new StringBuilder("delete from "+table+" where id = "+id);
Connection connection = null;
PreparedStatement pstmt = null;
try {
connection = DataSource.getPostgresConnection();
pstmt = connection.prepareStatement(builder.toString());
pstmt.execute();
} catch (Exception e) {
throw e;
} finally{
DataSource.close(connection, pstmt);
}
return null;
}
@Override
public List query(String sql, Class clazz) throws Exception{
Field[] fields = clazz.getDeclaredFields();
List result = new ArrayList();
Connection connection = null;
PreparedStatement pstmt = null;
ResultSet rs =null;
try {
connection = DataSource.getPostgresConnection();
pstmt = connection.prepareStatement(sql);
rs = pstmt.executeQuery();
while(rs.next()){
T t = clazz.newInstance();
int columnCount = rs.getMetaData().getColumnCount();
for(int i=1;i type = field.getType();
String setMethod = Tools.setMethod(field);
Method method = clazz.getDeclaredMethod(setMethod,type);
if(type == int.class){
method.invoke(t,rs.getInt(i));
}else if(type == double.class){
method.invoke(t,rs.getDouble(i));
}else if(type == float.class){
method.invoke(t,rs.getFloat(i));
}else{
method.invoke(t,rs.getObject(i));
}
/*if(type == String.class){
method.invoke(t,rs.getString(i));
}else if(type == Integer.class){
method.invoke(t,rs.getInt(i));
}else if(type == int.class){
method.invoke(t,rs.getInt(i));
}else if(type == double.class){
method.invoke(t,rs.getDouble(i));
}else if(type == float.class){
method.invoke(t,rs.getFloat(i));
}else if(type == Double.class){
method.invoke(t,rs.getDouble(i));
}else if(type == Float.class){
method.invoke(t,rs.getFloat(i));
}*/
break;
}
}
}
result.add(t);
}
} catch (Exception e) {
throw e;
} finally{
DataSource.close(connection, pstmt);
}
return result;
}
}
数据库表or_user
Or_User对象
package com.seagate.client.dao.ormapping.dao;
import com.seagate.client.dao.ormapping.anotation.ZBean;
import com.seagate.client.dao.ormapping.anotation.ZField;
@ZBean("or_user")
public class OrUser {
@ZField("id")
private int id;
@ZField("user_name")
private String userName;
@ZField("user_code")
private String userCode;
@ZField("phone")
private String phone;
@ZField("address")
private String address;
public int getId() {
return id;
}
public OrUser(){
}
public OrUser(int id, String userName, String userCode, String phone,
String address) {
super();
this.id = id;
this.userName = userName;
this.userCode = userCode;
this.phone = phone;
this.address = address;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserCode() {
return userCode;
}
public void setUserCode(String userCode) {
this.userCode = userCode;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Test.java
public static void main(String[] args) throws Exception {
DataSource.init();
OrMappingService service = new OrMappingService();
long currenttime = System.currentTimeMillis();
OrUser user = new OrUser(0,"Jack","P001","123456","Wuxi Road 1");
service.save(user);
String sql = "select * from or_user where user_name='Jack'";
List users = service.query(sql, OrUser.class);
System.out.println(users.get(0).getId()+","+users.get(0).getUserName()+","
+users.get(0).getUserCode()+","+users.get(0).getPhone()+","+users.get(0).getAddress());
users.get(0).setPhone("654321");
users.get(0).setAddress("Beijing Road 1");
service.update(users.get(0));
List userUpdate = service.query(sql, OrUser.class);
System.out.println(userUpdate.get(0).getId()+","+userUpdate.get(0).getUserName()+","
+userUpdate.get(0).getUserCode()+","+userUpdate.get(0).getPhone()+","+userUpdate.get(0).getAddress());
service.delete(userUpdate.get(0));
List userDelete = service.query(sql, OrUser.class);
System.out.println(userDelete.size());
System.out.println("Cost time:"+(System.currentTimeMillis()-currenttime));
}
运行结果
完成!