自定义注解@Column
package com.hzcominfo.hermes_study;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Column {
String value();
}
自定义注解@Table
package com.hzcominfo.hermes_study;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Table {
String value();
}
测试用实体类
package com.hzcominfo.hermes_study;
@Table(value = "student")
public class Student {
@Column(value = "name")
private String name;
@Column(value = "age")
private int age;
@Column(value = "xh")
private String xh;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getXh() {
return xh;
}
public void setXh(String xh) {
this.xh = xh;
}
}
测试用main方法
public static void main(String[] args) {
Student s = new Student();
s.setAge(18);
s.setName("xx");
System.out.println(querySql(s));
}
public static String querySql(Object o) {
StringBuffer sb = new StringBuffer();
Class<? extends Object> clazz = o.getClass();
if(clazz.isAnnotationPresent(Table.class)) {
Table t = clazz.getAnnotation(Table.class);
sb.append("select * from " +t.value() +" where 1=1 ");
for (Field field : clazz.getDeclaredFields()) {
if(field.isAnnotationPresent(Column.class)) {
Column c = field.getAnnotation(Column.class);
String fieldName = c.value();
String method = "get"+fieldName.substring(0, 1).toUpperCase()+fieldName.substring(1);
try {
Method m = clazz.getDeclaredMethod(method);
Object fieldValue = m.invoke(o);
if(fieldValue == null) continue;
sb.append(" and "+fieldName+" = ");
if(fieldValue instanceof String) {
sb.append("'"+fieldValue+"'");
}else {
sb.append(fieldValue);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return sb == null ? null : sb.toString();
}
总结 1注解式编程方便且b格高
2 可代替文件配置,可以参考https://www.cnblogs.com/everxs/p/4575131.html(侵权即删)