您的位置:首页 > 其它

使用注解做添加删除修改

2016-02-28 11:39 260 查看
注解类:
package com.sql.annotation;

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 TableNameAnnotation {
public String table();
}
package com.sql.annotation;

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 ColumnNameAnnotation {
public String column();
}

注解处理器:
public class SQLProcessor {
private static Map methodMap = new HashMap();

public static String getAnnotationName(Object obj,Class annotationClazz, String name) throws Exception {
String value = null;
Annotation annotation = null;
Class clazz = obj.getClass();

if(clazz.isAnnotationPresent(annotationClazz)) {
annotation = clazz.getAnnotation(annotationClazz);
} else {
throw new Exception("没有需要处理的注解");
}

Method method = annotation.getClass().getMethod(name, null);
value = (String) method.invoke(annotation, null);
return value;
}

public static int createInsertSQL(Connection conn, Object obj) throws Exception {
String str1 = "insert into ";
String tableName = "";
String str2 = "(";
StringBuffer columnNmaes = new StringBuffer();
String str3 = ") values (";
StringBuffer params = new StringBuffer();
String str5 = ")";
Map map = new HashMap();

tableName = getAnnotationName(obj, TableNameAnnotation.class, "table");

Field[] fields = obj.getClass().getDeclaredFields();
int index = 1;
for (Field field : fields) {
ColumnNameAnnotation annotation = field.getAnnotation(ColumnNameAnnotation.class);
if(annotation == null) {
continue;
} else {
columnNmaes.append(annotation.column()).append(",");
params.append("?").append(",");
String typeName = field.getType().toString();
int tempIndex = typeName.lastIndexOf(".");
String type = null;
if(tempIndex > 0) {
type = typeName.substring(tempIndex+1);
} else {
type = typeName;
}
field.setAccessible(true);
map.put(type.toLowerCase()+"," + index, field.get(obj));
index++;
}
}

int deleteIndex = columnNmaes.lastIndexOf(",");
int deleteIndex2 = params.lastIndexOf(",");
String columnName = columnNmaes.toString().substring(0, deleteIndex);
String param = params.toString().substring(0, deleteIndex2);

StringBuffer sql = new StringBuffer();
sql.append(str1).append(tableName).append(str2).append(columnName).append(str3).append(param).append(str5);
PreparedStatement pstat = conn.prepareStatement(sql.toString());

setSqlParameter(pstat, map);

return pstat.executeUpdate();
}

public static void setSqlParameter(PreparedStatement pstat, Map map) throws SQLException {
Set keySet = map.keySet();
Iterator<String> iterater = keySet.iterator();
for(;iterater.hasNext();) {
String key = iterater.next();
String[] keyAndIndex = key.split(",");
int type = (Integer) methodMap.get(keyAndIndex[0]);
int parameterIndex = Integer.valueOf(keyAndIndex[1]);
switch (type) {
case 1:
pstat.setInt(parameterIndex, ((Integer)map.get(key)));
break;
case 2:
pstat.setFloat(parameterIndex, Float.valueOf((String)map.get(key)));
break;
case 3:
pstat.setDouble(parameterIndex, (Float)map.get(key));
break;
case 4:
pstat.setByte(parameterIndex, (Byte)map.get(key));
break;
case 5:
pstat.setLong(parameterIndex, (Long)map.get(key));
break;
case 6:
pstat.setShort(parameterIndex, (Short)map.get(key));
break;
case 7:
pstat.setTime(parameterIndex, (Time)map.get(key));
break;
case 8:
pstat.setTimestamp(parameterIndex, (Timestamp)map.get(key));
break;
case 9:
pstat.setString(parameterIndex, (String)map.get(key));
break;
case 10:
pstat.setDate(parameterIndex, (Date)map.get(key));
break;
case 11:
pstat.setBoolean(parameterIndex, (Boolean)map.get(key));
break;
default:
break;
}
}
}

static {
methodMap.put("int", 1);
methodMap.put("float", 2);
methodMap.put("double", 3);
methodMap.put("byte", 4);
methodMap.put("long", 5);
methodMap.put("short", 6);
methodMap.put("time", 7);
methodMap.put("timestamp", 8);
methodMap.put("string", 9);
methodMap.put("date", 10);
methodMap.put("boolean", 11);
}
}

测试实体类:
@TableNameAnnotation(table="departments")
public class Department {
private int did;
@ColumnNameAnnotation(column="department_name")
private String departmentName;

public int getDid() {
return did;
}

public void setDid(int did) {
this.did = did;
}

public String getDepartmentName() {
return departmentName;
}

public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
}
测试类:
public static void main(String[] args) throws SQLException, SecurityException, NoSuchFieldException {

Department depart = new Department();
depart.setDepartmentName("gggg");
//从ibatis获得Connection
SqlMapClient client = SQLMapClient.getSqlMaper();

Connection conn = client.getDataSource().getConnection();

SQLProcessor processor = new SQLProcessor();
try {
int b = processor.createInsertSQL(conn, depart);
System.out.println(b);
System.out.println("-------------------------------------");
conn.commit();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: