利用反射和自定义注解写一个Basedao,dao类继承它就可以完成简单的增删改,需要写简单的dbutil读取资源包的工具类,需要写entity

package com.ydj.dao;

import com.ydj.annotation.TableField;
import com.ydj.annotation.TableId;
import com.ydj.annotation.TableName;
import com.ydj.util.DBUtil;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;

public class BaseDao<T> {
    public int insert(T t) throws Exception {
        /*思路:字符串拼接。sql语句:insert into 表名(列名1,列名2,列名3...) values(值1,值2,值3...)
        *表名注解和属性字段注解根据是否与数据库相同,选择加或不加,如果加按注解为准(换言之,加注解需要保证正确。)
        * 主键注解必须加,以标识主键字段。
        * 以字符串数组接列名123和值123的内容,然后将数组转为字符串,将其中的中括号换为括号
        * 增强遍历部分的判断条件注意:先判断主键注解是否存在,以及设置属性可访问性。
        * 此方法有sql注入的风险。(暂未试验) */
        StringBuffer sql = new StringBuffer("INSERT INTO ");
        Class<?> clazz = t.getClass();
        String tableName = clazz.getSimpleName();
        TableName annotation = clazz.getAnnotation(TableName.class);
        if(annotation != null){
            tableName = annotation.value();
        }
        sql.append(tableName+" ");
        // 获取属性
        List<String> columns = new ArrayList<>();
        List<String> values = new ArrayList<>();
        Field[] fields = clazz.getDeclaredFields();
        for(Field field : fields){
            String columnName = field.getName();
            TableId idAnnotation = field.getAnnotation(TableId.class);
            TableField fieldAnnotation = field.getAnnotation(TableField.class);
            if(idAnnotation != null){
                continue;
            }
            if(fieldAnnotation != null){
                columnName = fieldAnnotation.value();
            }
            field.setAccessible(true);
            Object value = field.get(t);
            values.add("'"+value+"'");
            columns.add(columnName);
        }
        String repalce=columns.toString().replace("[", "(").replace("]", ")");
        String replace2=values.toString().replace("[", "(").replace("]", ")");
        sql.append(repalce+" value "+replace2);
        Connection conn = DBUtil.getConnection();
        PreparedStatement ps = conn.prepareStatement(sql.toString());
        int rows = ps.executeUpdate();
        return rows;
    }
    /*public int update(T t) throws Exception {
        //update 表名 set 列名=值,列名=值,列名=值 where 条件
        *//*注意:*//*
        StringBuffer sql = new StringBuffer("UPDATE ");
        Class<?> clazz = t.getClass();
        String tableName = clazz.getSimpleName();
        TableName annotation = clazz.getAnnotation(TableName.class);
        if(annotation != null){
            tableName = annotation.value();
        }
        sql.append(tableName+" ");
        // 获取属性
        List<String> columns = new ArrayList<>();
        Field[] fields = clazz.getDeclaredFields();
        StringBuffer where = new StringBuffer(" WHERE ");
        for(Field field : fields) {
            String columnName = field.getName();
            TableField fieldAnnotation = field.getAnnotation(TableField.class);
            TableId idAnnotation = field.getAnnotation(TableId.class);
            // 获取条件
            if(idAnnotation != null) {
                String idName = idAnnotation.value();
                Field idField = clazz.getDeclaredField(idName);
                idField.setAccessible(true);
                Object idValue = idField.get(t);
                where.append(idName+"='"+idValue+"'");
            }
            if(idAnnotation != null){continue;}
            if(fieldAnnotation != null){
                columnName = fieldAnnotation.value();
            }
            field.setAccessible(true);
            Object value = field.get(t);
            columns.add(columnName+"='"+value+"'");
        }
        String repalce=columns.toString().replace("[", "").replace("]", "");
        sql.append(" SET "+repalce);
        sql.append(where);
        System.out.println(sql.toString());
        Connection conn = DBUtil.getConnection();
        PreparedStatement ps = conn.prepareStatement(sql.toString());
        return ps.executeUpdate();
        }*/
    /*public  int insert(T t) throws Exception {
        //insert into 表名(列名1,列名2,列名3) values(值1,值2,值3)
        StringBuffer sql=new StringBuffer("INSERT INTO ");
        Class<?> aClass = t.getClass();
        String tableName = aClass.getSimpleName();
        Field[] declaredFields = aClass.getDeclaredFields();
        ArrayList<String> columns=new ArrayList<>();
        ArrayList<String> values=new ArrayList<>();
        for (Field declaredField : declaredFields){
            TableField fieldAnnotation = declaredField.getAnnotation(TableField.class);
            TableId idAnnotation = declaredField.getAnnotation(TableId.class);
            declaredField.setAccessible(true);
            Object value = declaredField.get(t);
            String columnName = declaredField.getName();
            if (idAnnotation != null) {
                continue;
            }
            if (fieldAnnotation!=null) {
                columnName=fieldAnnotation.value();
            }
            values.add("'"+value+"'");
            columns.add(columnName);
        }
        sql.append(tableName+" ");
        String replace1=columns.toString().replace("[", "(").replace("]", ")");
        String replace2=values.toString().replace("[", "(").replace("]", ")");
        sql.append(replace1+" values "+replace2);
        System.out.println(sql.toString());
        Connection conn = DBUtil.getConnection();
        PreparedStatement ps = conn.prepareStatement(sql.toString());
        return ps.executeUpdate();
    }*/
    public  int update(T t) throws Exception {
        //update 表名 set 列名1=值1,列名2=值2,列名3=值3 where 条件
        /*注意:末尾逗号去除,deleteCharAt() */
        StringBuffer sql=new StringBuffer("UPDATE ");
        Class<?> aClass = t.getClass();
        String tableName = aClass.getSimpleName();
        TableName tableAnnotation = aClass.getAnnotation(TableName.class);
        if (tableAnnotation != null) {
            tableName=tableAnnotation.value();
        }
        sql.append(tableName+" set ");
        Field[] declaredFields = aClass.getDeclaredFields();
        String where=" where ";
        for (Field declaredField : declaredFields){
            TableField fieldAnnotation = declaredField.getAnnotation(TableField.class);
            TableId idAnnotation = declaredField.getAnnotation(TableId.class);
            declaredField.setAccessible(true);
            if (idAnnotation != null){
                where+= idAnnotation.value()+"='"+declaredField.get(t)+"'";
                continue;
            }
            if (fieldAnnotation!=null){
                sql.append(fieldAnnotation.value()+"='"+declaredField.get(t)+"',");
            }
            sql.append(declaredField.getName()+"='"+declaredField.get(t)+"',");
        }
        sql.deleteCharAt(sql.length()-1);
        sql.append(where);
        System.out.println(sql.toString());
        Connection conn = DBUtil.getConnection();
        PreparedStatement ps = conn.prepareStatement(sql.toString());
        return ps.executeUpdate();
    }
    public  int delete(Object id) throws Exception {
        //delete from 表名 where 条件
        /*获取表名:this指调用方法的那个Dao,得到其反射类后获取其含泛型的父类BaseDao<T>,强转为ParameterizedType
        * 再获取其实际类型的参数列表的第一个的类型,将类型对象强转为Class泛型
        * 方法字面化的简化描述,this起手,得反射类,获取其家族父类,转参数化类型,得实际参数类型数组的第一个,转反射类。
        * */
        StringBuffer sql=new StringBuffer("DELETE FROM ");
        Class<? extends BaseDao> aClass = this.getClass();
        ParameterizedType genericSuperclass = (ParameterizedType) aClass.getGenericSuperclass();
        Type actualTypeArgument = genericSuperclass.getActualTypeArguments()[0];
        Class<?> clazz = (Class<?>) actualTypeArgument;
        String tname = clazz.getName();
        TableName tableAnnotation = clazz.getAnnotation(TableName.class);
        if (tableAnnotation != null) {
            tname=tableAnnotation.value();
        }
        sql.append(tname+" where ");
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field declaredField : declaredFields){
            TableId idAnnotation = declaredField.getAnnotation(TableId.class);
            if (idAnnotation != null) {
                sql.append(idAnnotation.value()+"='"+id+"'");
            }
        }
        System.out.println(sql.toString());
        Connection conn = DBUtil.getConnection();
        PreparedStatement ps = conn.prepareStatement(sql.toString());
        return ps.executeUpdate();
    }


}

  • 17
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值