自定义注解实现orm框架

一、首先自定义两个注解,分别是表名映射注解和字段名映射注解

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)
@interface TableName{
	String value();
}

//属性映射注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FieldName{
	String name();
	int length() default 0;
	
}

二、定义表对应的实体类

@TableName("student_info")
public class Student {
	
	@FieldName(name="id",length=10)
	private String id;
	
	@FieldName(name="user_name")
	private String userName;
	
	@FieldName(name="user_age")
	private String userAge;
	
}

三、使用实体类注解拼成查询sql

import java.lang.reflect.Field;

public class Main1 {
	public static String createSql() throws ClassNotFoundException{
		StringBuffer sqlBuffer = new StringBuffer();
		sqlBuffer.append("select ");
		Class<?> clas= Class.forName("spring.Student");
		
		/*
		 * 获取属性注解值即字段名
		 */
		Field[] declaredFields = clas.getDeclaredFields();
		String[] field = new String[declaredFields.length];
		for(int i = 0;i<declaredFields.length;i++){
			FieldName annotation2 = declaredFields[i].getAnnotation(FieldName.class);
			field[i]=annotation2.name();
			sqlBuffer.append(annotation2.name());
			if(i<declaredFields.length-1){
				sqlBuffer.append(",");
			}
		}
		/*
		 * 获取类注解值表名
		 */
		TableName annotation = clas.getAnnotation(TableName.class);
		String tableName = "";//表名
		if(null != annotation){
			tableName = annotation.value();
		}
		sqlBuffer.append(" from "+tableName);
		return sqlBuffer.toString();
	}
	
	public static void main(String[] args) throws ClassNotFoundException {
		System.out.println(createSql());
	}
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值