您的位置:首页 > 其它

自定义ORM注解实现生成查询语句

2016-04-05 20:23 316 查看
package Annotation.Test;

@Table("Student")
public class Student {

@Column("Id")
private String Id;

@Column("name")
private String name;

@Column("age")
private int age;

public String getId() {
return Id;
}

public void setId(String id) {
Id = id;
}

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;
}

}


注解类:

/*用来映射表名称的注解*/
@Target({ElementType.TYPE})  //应用于类或接口
@Retention(RetentionPolicy.RUNTIME)  //方便运行时通过反射获取到
@Inherited  //类注解可被类继承
@Documented
public @interface Table {
String value();
}


@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Column {
String value();// 用于描述映射表字段的值
}


测试方法:

/*测试通过获取注解的信息生成sql语句*/
public class TestGenerateSQL {

public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

Student stu = new Student();
//stu.setId("1000");
stu.setName("水田奈落");
stu.setAge(23);
System.out.println(QueryStu(stu));

}

public static String QueryStu(Student stu) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
StringBuilder sb=new StringBuilder("select * from ");

// 获取类的class
Class stuClass = stu.getClass();

/*通过获取类的类注解,来获取类映射的表名称*/
if(stuClass.isAnnotationPresent(Table.class)){  //如果类映射了表
Table table=(Table)stuClass.getAnnotation(Table.class);
sb.append(table.value()+" where 1=1 ");  //加入表名称

/*遍历所有的字段*/
Field[] fields=stuClass.getDeclaredFields();//获取类的字段信息
for(Field field : fields){
if(field.isAnnotationPresent(Column.class)){
Column col=field.getAnnotation(Column.class); //获取列注解
String fieldName=field.getName(); //获取字段名称
String MethodName="get"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);//获取字段的get方法
Method method=stuClass.getMethod(MethodName); //get到field的值

/*空字段跳过拼接过程。。。*/
if(method.invoke(stu)==null || (method.invoke(stu) instanceof Integer && (Integer)method.invoke(stu)==0)){ //如果没有值,不拼接
continue;
}

/*通过函数的返回值类型来判断我强制转换时候该转换成什么类型*/
if(method.getReturnType()==String.class){
String fieldValue=(String)method.invoke(stu, null);
sb.append("and "+fieldName+"="+"'"+fieldValue+"'");
}else if(method.getReturnType()==int.class){
Integer fieldValue=(Integer) method.invoke(stu, null);
sb.append("and "+fieldName+"="+fieldValue);
}//根据情况else 其他数据类型,看着玩儿吧....
}else{
continue;
}
}
}else{
return null;
}
return sb.toString();
}

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