java Annotation 拼装SQL语句

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;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FiledRef
{
String fieldName();
}

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableRef
{
String tableName();
}

@TableRef(tableName = "MobDevice")
public class ReflectTest
{
@FiledRef(fieldName = "ID")
private Long id;

@FiledRef(fieldName = "DEVICE_NAME")
private String name;

@FiledRef(fieldName = "DEVICE_CODE")
private String code;

public ReflectTest(Long id, String name, String code)
{
this.id = id;
this.name = name;
this.code = code;
}

public Long getId()
{
return id;
}

public void setId(Long id)
{
this.id = id;
}

public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}

public String getCode()
{
return code;
}

public void setCode(String code)
{
this.code = code;
}

/**
* @description
* @author zhangml
* @date May 17, 2010 4:39:30 PM
* @param args
*/
public static void main(String[] args)
{
ReflectTest rt = new ReflectTest(new Long(1), "2", "3");
StringBuffer sql = new StringBuffer("");
buildSql(rt, sql);
System.err.println(sql);
}

public static void buildSql(Object obj, StringBuffer sb)
{
Class<? extends Object> clazz = obj.getClass();
Field[] fields = clazz.getDeclaredFields();
if (clazz.isAnnotationPresent(TableRef.class))
{
TableRef tr = (TableRef) clazz.getAnnotation(TableRef.class);
sb.append("SELECT * FROM ");
sb.append(tr.tableName());
}
if (fields != null && fields.length > 0)
{
sb.append(" WHERE ");
for (Field field : fields)
{
try
{
Object value = field.get(obj);
if (value != null && field.isAnnotationPresent(FiledRef.class))
{
FiledRef fr = field.getAnnotation(FiledRef.class);
sb.append(fr.fieldName() + "=" + value);
sb.append(" AND ");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
int length = sb.length();
sb.delete(length-5, length);
}
}

}

执行结果:SELECT * FROM MobDevice WHERE ID=1 AND DEVICE_NAME=2 AND DEVICE_CODE=3
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值