使用註解簡單地實現ORM框架

ORM框架

ORM : 對象關係映射
簡而言之,實體類與數據庫表字段的一一對應
我們要做的工作:使用註解來實現實體類與表的映射,並且使用反射技術生成Sql語句

代碼實現

1、定義表名的註解

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface SetTable {
	String table();
}

2、定義屬性名的註解

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SetProperty {
	String value(); 
}

3、定義User實體類

@SetTable(table="user")
public class User {
	@SetProperty(value="user_id")
	private int id;
	@SetProperty(value="user_name")
	private String name;
	@SetProperty(value="user_age")
	private int age;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.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;
	}
}

4、根據實體類中的註解,使用反射來生成查詢sql語句

public class OrmDemo {
	public static void main(String[] args) throws ClassNotFoundException {
		//加載User類文件
		Class<User> clazz = (Class<User>) Class.forName("cn.zyyx.demo.User");
		//從類對象中獲取到類上面的註解
		SetTable table = clazz.getAnnotation(SetTable.class);
		//獲取到表名
		String tableName = table.table();
		//使用StringBuffer拼接字符串
		StringBuffer sb = new StringBuffer();
		sb.append("select ");
		//獲取當前類的註解中的所有屬性
		Field[] fields = clazz.getDeclaredFields();
		for (int i = 0; i < fields.length; i++) {
			//獲得屬性對象
			Field field = fields[i];
			//獲得屬性對象上面的註解
			SetProperty property = field.getAnnotation(SetProperty.class);
			//獲得註解中的value
			String value = property.value();
			sb.append(value);
			if(i == fields.length - 1){
				sb.append(" from ");
			}else{
				sb.append(",");
			}
		}
		//拼接表名
		sb.append(tableName);
		System.out.println(sb.toString());
	}
}

輸出結果
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章