通过反射与注解拼装sql查询的小例子

package com.imooc.ann;


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.lang.reflect.Method;


public class Tests {
public static void main(String[] args) {
Users u1 = new Users();
u1.setUserName("张三");

Users u2 = new Users();
u2.setId(4);
u2.setAddress("济南");


String sql1 = query(u1);
String sql2 = query(u2);

//输出sql查询语句
System.out.println(sql1);
System.out.println(sql2);

}

@SuppressWarnings({ "unchecked", "rawtypes" })
public static String query(Object obj){
//字符串缓冲区
StringBuilder sb = new StringBuilder();
Class u = obj.getClass();
//拼装sql语句

boolean isExist = u.isAnnotationPresent(Table.class);
if(isExist){
sb.append("select * from ");
//得到表名
Table t = (Table)u.getAnnotation(Table.class);
sb.append(t.value()+" where 1=1 ");
}
//得到字段名和值
Field[] f = u.getDeclaredFields();
for (Field field : f) {
boolean fExists = field.isAnnotationPresent(Column.class);
Column c = null;
if(fExists){
//拿到字段
c = (Column)field.getAnnotation(Column.class);

}
//拿到字段值
String fieldName = field.getName();
Object methodValue =null;
try {
//拼装方法名
String methodName = "get"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);
//通过反射获取方法
Method m = u.getMethod(methodName);
//通过反射获取方法内的值
methodValue = (Object)m.invoke(obj);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//判断值是否为空或如果是Integer类型数据值是否为0
if(methodValue==null||(methodValue instanceof Integer&&(Integer)methodValue==0)){
continue;
}
//添加字段名
sb.append(" and "+c.value());
//添加字段值
if(methodValue instanceof Integer){
sb.append(" = "+methodValue);
}
if(methodValue instanceof String){
sb.append(" = '"+methodValue+"'");
}
}

return sb.toString();

}


}
//自定义注解
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface Table{
String value();
}
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@interface Column{
String value();
}


//关联数据库表
@Table("users")
class Users{
@Column("id")
private Integer id;
@Column("user_name")
private String userName;
@Column("email")
private String email;
@Column("address")
private String address;



public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值