• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

BaseDao Java利用反射技术原生实现BaseDao,自动拼装SQL语句

error 来源:蔡瑞圣 12次浏览

Java利用反射技术原生实现BaseDao,自动拼装SQL语句

这里我用了注解+反射

首先声明三个注解:


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;
/**
 * 
 * 标识表名
 * @author Crs
 *
 */
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Table {
	String value();
}


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;
/**
 * 该注解用于标识字段
 * @author Crs
 *
 */
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Column {
	String value();
}

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;
/**
 * 该注解标识主键
 * @author Crs
 *
 */
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Id {
}

实体类 

package stusys.entity;

import stusys.dao.annotation.Column;
import stusys.dao.annotation.Id;
import stusys.dao.annotation.Table;

@Table("tb_student")
public class Student {
	
	@Column("tstuName")
	private String stuName;
	
	@Column("tstuGender")
	private String stuGender;
	
	@Column("tstuAge")
	private Integer stuAge;
	
	@Id  //标识此字段为主键
	@Column(value = "tstuNumber")
	private String stuNumber;
	
	@Column("tstuAddress")
	private String stuAddress;
	
	private Classes clz;

	public String getStuName() {
		return stuName;
	}

	public void setStuName(String stuName) {
		this.stuName = stuName;
	}

	public String getStuGender() {
		return stuGender;
	}

	public void setStuGender(String stuGender) {
		this.stuGender = stuGender;
	}

	public Integer getStuAge() {
		return stuAge;
	}

	public void setStuAge(Integer stuAge) {
		this.stuAge = stuAge;
	}

	public String getStuNumber() {
		return stuNumber;
	}

	public void setStuNumber(String stuNumber) {
		this.stuNumber = stuNumber;
	}

	public String getStuAddress() {
		return stuAddress;
	}

	public void setStuAddress(String stuAddress) {
		this.stuAddress = stuAddress;
	}

	public Classes getClz() {
		return clz;
	}

	public void setClz(Classes clz) {
		this.clz = clz;
	}

	@Override
	public String toString() {
		return "Student [stuName=" + stuName + ", stuGender=" + stuGender + ", stuAge=" + stuAge + ", stuNumber="
				+ stuNumber + ", stuAddress=" + stuAddress + ", clz=" + clz + "]";
	}
	
	
}

BaseDao实现类


import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import stusys.dao.BaseDao;
import stusys.dao.annotation.Column;
import stusys.dao.annotation.Id;
import stusys.dao.annotation.Table;

public class BaseDaoImpl<T> implements BaseDao<T>{
	
	private Class<?> clazz;
	public BaseDaoImpl(Class<?> clazz){
		this.clazz=clazz;
	}
	
	@Override
	public boolean save(T t) throws IllegalArgumentException, IllegalAccessException {
		// TODO Auto-generated method stub
		StringBuffer sb = new StringBuffer("INSERT INTO ");
		StringBuilder columnSb = new StringBuilder("(");
		StringBuilder valuesSb = new StringBuilder("(");
		if(clazz.isAnnotationPresent(Table.class)){
			Table table = (Table) clazz.getAnnotation(Table.class);		
			String tableName = table.value();		
			sb.append(tableName);				
			Field[] fields1 = clazz.getDeclaredFields();	
			ArrayList<Field> arr = new ArrayList<Field>();
			for(Field fields:fields1){
				if(fields.isAnnotationPresent(Column.class)){
					arr.add(fields);
				}
			}
			
			Field[] fields = arr.toArray(new Field[arr.size()]);
			for(int i = 0;i<fields.length;i++){
				Column col = fields[i].getAnnotation(Column.class);
				fields[i].setAccessible(true); 
				String colmun = col.value();
				Object value = fields[i].get(t);
				if(colmun!=null&&colmun.length()>0&&value!=null&&value.toString().length()>0){
					if(i==fields.length-1){
						columnSb.append(colmun+")");
						valuesSb.append(value.toString()+");");
					}else{
						columnSb.append(colmun+",");
						valuesSb.append(value.toString()+",");
					}
				}
			}
			sb.append(columnSb.toString()).append("VALUES").append(valuesSb.toString());
			System.out.println(sb.toString());
		}
		return false;
	}

	@Override
	public boolean update(T t) throws IllegalArgumentException, IllegalAccessException {
		// TODO Auto-generated method stub
		StringBuilder sql= new StringBuilder("UPDATE ");
		StringBuilder valueSb = new StringBuilder("");
		if(clazz.isAnnotationPresent(Table.class)){
			Table table = clazz.getAnnotation(Table.class);
			String tableName = table.value();
			sql.append(tableName+" SET ");
			Field[] fields = clazz.getDeclaredFields();
			ArrayList<Field> arr = new ArrayList<Field>();
			for(Field field:fields){
				if(field.isAnnotationPresent(Column.class)){
					arr.add(field);
				}
			}
			Field[] fields2 = arr.toArray(new Field[arr.size()]);
			for(int i = 0 ;i<fields2.length;i++){
				fields2[i].setAccessible(true);
				Column column = fields2[i].getAnnotation(Column.class);
				String colName = column.value();
				Object value = fields2[i].get(t);
				if(fields2[i].isAnnotationPresent(Id.class)){
					if(colName!=null&&colName.length()>0&&value!=null&&value.toString().length()>0){
						valueSb.append("where "+column.value()+" = "+value.toString()+";");
					}
				}else if(i==fields2.length-1){
					if(colName!=null&&colName.length()>0&&value!=null&&value.toString().length()>0){
						sql.append(colName+"="+value.toString()+" ");
					}
				}else{
					sql.append(colName+"="+value.toString()+",");
				}
			}
			sql.append(valueSb.toString());
			System.out.println(sql.toString());
		}
		return false;
	}

	@Override
	public boolean delete(T t) throws IllegalArgumentException, IllegalAccessException {
		StringBuilder sb = new StringBuilder("DELETE FROM ");
		if(clazz.isAnnotationPresent(Table.class)){
			Table table = clazz.getAnnotation(Table.class);
			sb.append(table.value()+" where ");
			Field[] fields = clazz.getDeclaredFields();
			for(Field field:fields){
				if(field.isAnnotationPresent(Id.class)&&field.isAnnotationPresent(Column.class)){
					field.setAccessible(true);
					Column col = field.getAnnotation(Column.class);
					String colStr = col.value();
					Object value = field.get(t);
					if(colStr!=null&&colStr.length()>0&&value!=null&&value.toString().length()>0){
						sb.append(colStr+" = "+value.toString()+";");
					}
				}
			}
		}
		System.out.println(sb.toString());
		return false;
	}

	@Override
	public List<T> findAll() {
		// TODO Auto-generated method stub
		StringBuilder sb = new StringBuilder("SELECT * FROM ");
		if(clazz.isAnnotationPresent(Table.class)){
			Table table = clazz.getAnnotation(Table.class);
			sb.append(table.value()+";");
		}
		System.out.println(sb.toString());
		return null;
	}

	@Override
	public T find(Integer id) throws IllegalArgumentException, IllegalAccessException {
		// TODO Auto-generated method stub
		StringBuilder sb = new StringBuilder("SELECT * FROM ");
		if(clazz.isAnnotationPresent(Table.class)){
			Table table = (Table) clazz.getAnnotation(Table.class);
			sb.append(table.value()+" where ");
			Field[] fields = clazz.getDeclaredFields();
			for(Field field:fields){
				if(field.isAnnotationPresent(Id.class)&&field.isAnnotationPresent(Column.class)){
					field.setAccessible(true);
					Column col = field.getAnnotation(Column.class);
					String colStr = col.value();
					if(colStr!=null&&colStr.length()>0&&id!=null&&id.toString().length()>0){
						sb.append(colStr+" = "+id.toString()+";");
					}
				}
			}
		}
		System.out.println(sb.toString());
		return null;
	}

}

测试Main方法

public static void main(String[] args) {
		
		BaseDaoImpl<Student> stuDao = new BaseDaoImpl<Student>(Student.class);
		
		Student stu = new Student();
		stu.setStuName("张三");
		stu.setStuAge(18);
		stu.setStuGender("男");
		stu.setStuAddress("陕西省西安市");
		stu.setStuNumber("10002");
		
		try {
			stuDao.save(stu);
		} catch (IllegalArgumentException | IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			stuDao.delete(stu);
		} catch (IllegalArgumentException | IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			stuDao.find(10002);
		} catch (IllegalArgumentException | IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		stuDao.findAll();
		
		
		try {
			stuDao.update(stu);
		} catch (IllegalArgumentException | IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

测试结果

INSERT INTO tb_student(tstuName,tstuGender,tstuAge,tstuNumber,tstuAddress)VALUES(张三,男,18,10002,陕西省西安市);
DELETE FROM tb_student where tstuNumber = 10002;
SELECT * FROM tb_student where tstuNumber = 10002;
SELECT * FROM tb_student;
UPDATE tb_student SET tstuName=张三,tstuGender=男,tstuAge=18,tstuAddress=陕西省西安市 where tstuNumber = 10002;

以上就是实现代码了,如有不足之处,请多多指教!


版权声明:本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。
喜欢 (0)