手写ORM框架

1.准备连接数据库工具类

public class DbUtil {
	private static String driverName="";
	private static String url="";
	private static String username="";
	private static String password="";
	
	static {
	// 	静态代码块
		try {
			InputStream inputStream = ClassLoader.getSystemResourceAsStream("db.properties");
			Properties properties=new Properties();
			properties.load(inputStream);
			driverName=properties.getProperty("db.driver");
			url=properties.getProperty("db.url");
			username=properties.getProperty("db.username");
			password=properties.getProperty("db.password");
		}catch (Exception e) {
			System.out.println("名字为db.properties的属性文件不存在");
			e.printStackTrace();
		}
	}
	
// 	获取连接对象
	public static Connection getConnection() throws Exception {
		Class.forName(driverName);
		Connection connection= DriverManager.getConnection(url,username,password);
		return connection;
	}
	
// 	关闭资源
	public static void closeAll(Connection connection, PreparedStatement ps, ResultSet rs){
		try {
			if (rs!=null){
				rs.close();
			}
			if (ps!=null){
				ps.close();
			}
			if (connection!=null) {
				connection.close();
			}
		}catch (Exception e){
			e.printStackTrace();
		}
	}
}

2.编写注解类

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

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TableId {
	String value() default "id";
}

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TableName {
	// 在实体类标记对应的表名
	String value() default "";
}

3.准备实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("tbl_dept")
public class TblDept implements Serializable {

    /**
    * 
    */
    @TableId
    private Integer id;
    /**
    * 
    */
    private String name;
    /**
    * 
    */
    private String loc;
}

4.编写BaseDao方法

public class BaseDao<T> {
	Class<T> clazz;
	public BaseDao() {
		//获取BaseDao子类的反射类对象
		Class<? extends BaseDao> aClass = this.getClass();
		//获取当前dao子类的父类的反射类
		ParameterizedType parameterizedType = (ParameterizedType) aClass.getGenericSuperclass();
		//得到泛型的反射类
		Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
		clazz= (Class<T>) actualTypeArguments[0];
	}
	
	// 	通用的添加操作
	//通用添加SQL语句:insert into 表名(列名,列名。。。) values(值,值。。。)
	public int insert(T t) throws Exception {
		StringBuffer sql = new StringBuffer("insert into ");
		// 	根据对象获取Class反射类
		Class<?> aClass = t.getClass();
		//获取反射类上的注解对象
		TableName annotation = aClass.getAnnotation(TableName.class);
		//表名
		String tableName = aClass.getSimpleName();
		if (annotation != null) {
			tableName=annotation.value();
		}
		sql.append(tableName);
		//获取列名
		Field[] fields = aClass.getDeclaredFields();
		//列名
		ArrayList<String> columns = new ArrayList<>();
		ArrayList<String> values = new ArrayList<>();
		for (Field field:fields){
			//属性名
			String name = field.getName();
			TableId annotation1 = field.getAnnotation(TableId.class);
			if (annotation1 != null||name.equals("id")){
				continue;
			}
			TableField annotation2 = field.getAnnotation(TableField.class);
			if (annotation2 != null){
				name=annotation2.value();
			}
			field.setAccessible(true);
			Object o = field.get(t);
			columns.add(name);
			values.add("'"+o+"'");
		}
		String columnNames = columns.toString().replace("[", "(").replace("]", ")");
		String columnValues = values.toString().replace("[", "(").replace("]", ")");
		sql.append(columnNames);
		sql.append(" values ");
		sql.append(columnValues);
		//执行sql
		Connection connection = DbUtil.getConnection();
		PreparedStatement ps = connection.prepareStatement(sql.toString());
		int i = ps.executeUpdate();
		return i;
	}
	
	//修改方法
	public int update(T t) throws Exception {
		StringBuffer sql = new StringBuffer("update ");
		// 	根据对象获取Class反射类
		Class<?> aClass = t.getClass();
		//获取反射类上的注解对象
		TableName annotation = aClass.getAnnotation(TableName.class);
		//表名
		String tableName = aClass.getSimpleName();
		if (annotation != null) {
			tableName=annotation.value();
		}
		sql.append(tableName+" set ");
		//获取列名
		Field[] fields = aClass.getDeclaredFields();
		String where=" where ";
		for (Field field:fields){
			field.setAccessible(true);
			//属性名
			String name = field.getName();
			TableId tableId = field.getAnnotation(TableId.class);
			if(name.equals("id")){
				where =where+"id='"+field.get(t)+"'";
				continue;
			}
			if(tableId!=null){
				where =where+tableId.value()+"'"+field.get(t)+"'";
				continue;
			}
			TableField tableField = field.getAnnotation(TableField.class);
			if (tableField != null){
				name=tableField.value();
			}
			
			String value ="'"+field.get(t)+"'";
			sql.append(name+"="+value+",");
		}
		String sql2=sql.toString().substring(0,sql.length()-1)+where;
		//执行SQL
		Connection connection = DbUtil.getConnection();
		PreparedStatement ps = connection.prepareStatement(sql2);
		int i = ps.executeUpdate();
		return i;
	}
	
	//删除方法
	public int delete(Object id) throws Exception {
		StringBuffer sql = new StringBuffer("delete from ");
		TableName annotation = clazz.getAnnotation(TableName.class);
		String tableName = clazz.getSimpleName();
		if (annotation!=null){
			tableName=annotation.value();
		}
		sql.append(tableName+" where ");
		Field[] fields = clazz.getDeclaredFields();
		for (Field field : fields){
			TableId tableId = field.getAnnotation(TableId.class);
			if (tableId!=null){
				sql.append(tableId.value()+"='"+id+"'");
				continue;
			}
		}
		//执行sql
		Connection connection = DbUtil.getConnection();
		PreparedStatement ps = connection.prepareStatement(sql.toString());
		int i = ps.executeUpdate();
		return i;
	}
	
	//查询方法
	public T selectById(Object id) throws Exception {
		StringBuffer sql = new StringBuffer("select * from ");
		TableName annotation = clazz.getAnnotation(TableName.class);
		String tableName = clazz.getSimpleName();
		if (annotation != null) {
			tableName = annotation.value();
		}
		sql.append(tableName + " where ");
		Field[] fields = clazz.getDeclaredFields();
		for (Field field : fields){
			TableId tableId = field.getAnnotation(TableId.class);
			if (tableId!=null){
				sql.append(tableId.value()+"='"+id+"'");
				continue;
			}
		}
		//执行SQL
		Connection connection = DbUtil.getConnection();
		PreparedStatement ps = connection.prepareStatement(sql.toString());
		ResultSet resultSet = ps.executeQuery();
		T t=null;
		while (resultSet.next()) {
			t = clazz.newInstance();
			Field[] fields1 = clazz.getDeclaredFields();
			for (Field field:fields1) {
				field.setAccessible(true);
				String name = field.getName();
				TableField tableField = field.getAnnotation(TableField.class);
				TableId tableId = field.getAnnotation(TableId.class);
				if (tableField != null){
					name=tableField.value();
				}
				if (tableId!=null){
					name=tableId.value();
				}
				Object v = resultSet.getObject(name);
				field.set(t,v);
			}
		}
		return t;
	}
	
	//查询方法
	public List<T> select() throws Exception {
		StringBuffer sql = new StringBuffer("select * from ");
		TableName annotation = clazz.getAnnotation(TableName.class);
		String tableName = clazz.getSimpleName();
		if (annotation != null) {
			tableName = annotation.value();
		}
		sql.append(tableName);
		//执行SQL
		Connection connection = DbUtil.getConnection();
		PreparedStatement ps = connection.prepareStatement(sql.toString());
		ResultSet resultSet = ps.executeQuery();
		T t=null;
		List<T> list=new ArrayList<T>();
		while (resultSet.next()) {
			t = clazz.newInstance();
			Field[] fields1 = clazz.getDeclaredFields();
			for (Field field:fields1) {
				field.setAccessible(true);
				String name = field.getName();
				TableField tableField = field.getAnnotation(TableField.class);
				TableId tableId = field.getAnnotation(TableId.class);
				if (tableField != null){
					name=tableField.value();
				}
				if (tableId!=null){
					name=tableId.value();
				}
				Object v = resultSet.getObject(name);
				field.set(t,v);
			}
			list.add(t);
		}
		return list;
	}
}

5.提供继承类

public class DeptDao extends BaseDao<TblDept>{
}

6.提供测试类

public class CRUD {
	DeptDao deptDao=new DeptDao();
	TblDept tblDept = new TblDept();
	@Test
	public void insert() throws Exception {
		tblDept.setName("技术部");
		tblDept.setLoc("北京");
		deptDao.insert(tblDept);
	}
	
	@Test
	public void update() throws Exception {
		tblDept.setId(5);
		tblDept.setName("会计部");
		tblDept.setLoc("北京");
		deptDao.update(tblDept);
	}
	
	@Test
	public void delete() throws Exception {
		deptDao.delete(5);
	}
	
	@Test
	public void selectById() throws Exception {
		TblDept tblDept1 = deptDao.selectById(4);
		System.out.println(tblDept1);
	}
	
	@Test
	public void select() throws Exception {
		System.out.println(deptDao.select());
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值