java 自定义注解应用实例

本文介绍了一种使用自定义注解为实体类打标记的方法,以实现自动生成SQL查询语句的功能。通过定义Table和Column注解,并应用于实体类中,结合反射技术实现了根据实体对象动态生成SQL查询语句的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本例子旨在使用自定义注解为实体打上标记,为自动生成 sql 提供依据,模拟 hibernate 的注解,至于注解的原理自己搜吧

1.定义 Table 注解

package test;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Inherited
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Table {
	String value() default "";
}

2.定义 Column 注解

package test;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Inherited
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Column {
	String value() default "";
}

3.定义使用注解的实体

package test;


@Table("tb_test")
public class TestDto {
	
	@Deprecated
	private String tt;
	
	@Column("_id")
	private String id;
	
	@Column("username")
	private String name;
	
	public TestDto(String id, String name) {
		super();
		this.id = id;
		this.name = name;
	}

	public String getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

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

4.测试注解

package test;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Test {
	public static void main(String[] args) {
		TestDto testDto = new TestDto("123", "34");
		TestDto testDto1 = new TestDto("123", "test1");
		TestDto testDto2 = new TestDto("", "test1,test2,test3,test4");
		String sql = assembleSqlFromObj(testDto);
		String sql1 = assembleSqlFromObj(testDto1);
		String sql2 = assembleSqlFromObj(testDto2);
		System.out.println(sql);
		System.out.println(sql1);
		System.out.println(sql2);
	}

	/**
	 * 通过注解来组装查询条件,生成查询语句
	 * 
	 * @param obj
	 * @return
	 */
	public static String assembleSqlFromObj(Object obj) {
		Table table = obj.getClass().getAnnotation(Table.class);
		StringBuffer sbSql = new StringBuffer();
		String tableName = table.value();
		sbSql.append("select * from " + tableName + " where 1=1 ");
		Field[] fileds = obj.getClass().getDeclaredFields();
		for (Field f : fileds) {
			String fieldName = f.getName();
			String methodName = "get" + fieldName.substring(0, 1).toUpperCase()
					+ fieldName.substring(1);
			try {
				Column column = f.getAnnotation(Column.class);
				if (column != null) {
					Method method = obj.getClass().getMethod(methodName);
					String value = (String) method.invoke(obj);
					if (value != null && !value.equals("")) {
						if (!isNum(column.value()) && !isNum(value)) {
							// 判断参数是不是 in 类型参数 1,2,3
							if (value.contains(",")) {
								sbSql.append(" and " + column.value() + " in (" + value + ") ");
							} else {
								sbSql.append(" and " + column.value() + " like '%" + value + "%' ");
							}
						} else {
							sbSql.append(" and " + column.value() + "=" + value + " ");
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return sbSql.toString();
	}

	/**
	 * 检查给定的值是不是 id 类型 1.检查字段名称 2.检查字段值
	 * 
	 * @param target
	 * @return
	 */
	public static boolean isNum(String target) {
		boolean isNum = false;
		if (target.toLowerCase().contains("id")) {
			isNum = true;
		}
		if (target.matches("\\d+")) {
			isNum = true;
		}
		return isNum;
	}
}

测试结果:

select * from tb_test where 1=1  and _id=123  and username=34
select * from tb_test where 1=1  and _id=123  and username like '%test1%'
select * from tb_test where 1=1  and username in (test1,test2,test3,test4)


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值