手写ORM(对象关系映射)增删改查

目录

 自定义注解

package com.jxy.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @Author Jin XueYang
 * @Date 2022/6/23 10:29
 * @Description
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TableField {
    String value();
}


/**
 * @Author Jin XueYang
 * @Date 2022/6/23 9:29
 * @Description
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TableId {
    String value();
}



/**
 * @Author Jin XueYang
 * @Date 2022/6/22 19:11
 * @Description
 */

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

实体

package com.jxy.entity;

import com.jxy.annotation.TableField;
import com.jxy.annotation.TableId;
import com.jxy.annotation.TableName;

/**
 * @Author Jin XueYang
 * @Date 2022/6/22 18:57
 * @Description
 */

@TableName(name = "tab_stu")
public class Student {
    @TableId(value = "id")
        private Integer id;
        private String sno;
        private String sname;
        private String sex;
        private String phone1;
        private String privince;



    public Student() {
    }

    public Student(Integer id,String sno, String sname, String sex, String phone1, String privince) {
        this.id = id;
        this.sno = sno;
        this.sname = sname;
        this.sex = sex;
        this.phone1 = phone1;
        this.privince = privince;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", sno='" + sno + '\'' +
                ", sname='" + sname + '\'' +
                ", sex='" + sex + '\'' +
                ", phone1='" + phone1 + '\'' +
                ", privince='" + privince + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getSno() {
            return sno;
        }

        public void setSno(String sno) {
            this.sno = sno;
        }


        public String getSname() {
            return sname;
        }

        public void setSname(String sname) {
            this.sname = sname;
        }


        public String getSex() {
            return sex;
        }

        public void setSex(String sex) {
            this.sex = sex;
        }


        public String getPhone1() {
            return phone1;
        }

        public void setPhone1(String phone1) {
            this.phone1 = phone1;
        }


        public String getPrivince() {
            return privince;
        }

        public void setPrivince(String privince) {
            this.privince = privince;
        }
}

DButil

package com.jxy.utils;

import java.sql.*;

/**
 * @Author Jin XueYang
 * @Date 2022/6/22 18:34
 * @Description
 */
public class DBUtil {
    public static Connection getConnection() throws SQLException {
        String url = "jdbc:mysql://localhost:3307/lesdb?useSSL=false&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&allowPublicKeyRetrieval=true";
        String driverName = "com.mysql.cj.jdbc.Driver";
        String username = "root";
        String password = "123456";
        Connection connection = DriverManager.getConnection(url,username,password);
        return connection;

    }

    public static void closeAll(ResultSet rs, PreparedStatement ps,Connection con){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if(ps!=null){
            try {
                ps.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if(con!=null){
            try {
                con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }



}

BaseDao(主写增删改查操作)

package com.jxy.utils;

import com.jxy.annotation.TableField;
import com.jxy.annotation.TableId;
import com.jxy.annotation.TableName;
import com.jxy.dao.StudentDao;
import com.jxy.entity.Student;

import java.lang.annotation.Annotation;
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.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author Jin XueYang
 * @Date 2022/6/22 18:54
 * @Description
 */
public class BaseDao<T> {
    ResultSet rs = null;
    Connection connection = null;
    PreparedStatement ps = null;
    //BaseDao泛型T的反射类
    private Class cla;

    public BaseDao() {
        //此时反射类就是BaseDao的子类
        Class<? extends BaseDao> studentClass = this.getClass();
        //获取子类继承父类的反射对象 并得到父类的泛型
        Type type = studentClass.getGenericSuperclass();
        ParameterizedType pt = (ParameterizedType) type;
        Type[] actualType = pt.getActualTypeArguments();
        //得到父类BaseDao的泛型<student>
        cla = (Class) actualType[0];
    }

    /**
     * 全表查询
     * @return
     */
    public List<T> selectAll(){
        StringBuffer sql = new StringBuffer("select * from ");
        TableName tableName = (TableName) cla.getAnnotation(TableName.class);
        if(tableName == null){
            throw new RuntimeException("未使用表名注解");
        }
        String name = tableName.name();
        sql.append(name);
        System.out.println(sql);

        return selectCondition(sql.toString());

    }

    public List<T> selectCondition(String sql){
        List<T> list = new ArrayList<>();



        try {
            connection = DBUtil.getConnection();
            ps = connection.prepareStatement(sql);
            rs = ps.executeQuery();
            //每循环一次找到一条记录
            //记录装到实体 实体交给集合
            while (rs.next()){
                T t = (T) cla.newInstance();
                Field[] declaredFields = cla.getDeclaredFields();
                for(Field field:declaredFields){
                    field.setAccessible(true);
                    TableId tableId = field.getAnnotation(TableId.class);
                    if(tableId!=null){
                        field.set(t,rs.getObject(tableId.value()));
                    }else{
                        TableField tableField = field.getAnnotation(TableField.class);
                        if(tableField!=null){
                            //列名与属性不一致
                            //set()将指定对象变量上此属性对象表示的字段设置为指定的新值
                            //通过set(Object obj,value)重新设置新的属性值
                            //getObject()获取此 ResultSet 对象的当前列中指定列的值
                            field.set(t,rs.getObject(tableField.value()));
                        }else{
                            //列名与属性一致
                            field.set(t,rs.getObject(field.getName()));
                        }
                    }
                }
                list.add(t);

            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }finally {
            DBUtil.closeAll(rs,ps,connection);
        }

        return list;
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */

    public T selectById(Object id){
        StringBuffer sql = new StringBuffer("select * from ");
        TableName tableName = (TableName) cla.getAnnotation(TableName.class);
        if(tableName == null){
            throw new RuntimeException("未使用表名注解");
        }
        String name = tableName.name();
        sql.append(name+" where ");
        Field[] declaredFields = cla.getDeclaredFields();
        for(Field field:declaredFields){
            TableId tableId = field.getAnnotation(TableId.class);
            if(tableId!=null){
                sql.append(tableId.value()+"="+id);
                break;
            }
        }
        System.out.println(sql);

        List<T> list = selectCondition(sql.toString());
        if(list!=null&&list.size()>0){
            return list.get(0);
        }else{
            return null;
        }


    }

    /**
     *
     * @param id
     * @return
     * 删除
     */
    public int delete(Object id){
        StringBuffer sql = new StringBuffer("delete from ");
        TableName tableName = (TableName) cla.getAnnotation(TableName.class);
        if(tableName == null){
            throw new RuntimeException("未使用表名注解");
        }
        String name = tableName.name();
        sql.append(name+" where ");
        Field[] declaredFields = cla.getDeclaredFields();
        for(Field field:declaredFields){
            TableId tableId = field.getAnnotation(TableId.class);
            if(tableId!=null){
                sql.append(tableId.value()+"="+id);
                System.out.println(sql);
            }
        }

        try {
            connection = DBUtil.getConnection();
            ps = connection.prepareStatement(sql.toString());
            int i = ps.executeUpdate();
            return i;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DBUtil.closeAll(rs,ps,connection);
        }



        return 0;
    }

    /**
     *
     * @param t
     * @return
     * 修改
     */
    public int update(T t){
        StringBuffer sq = new StringBuffer("update ");
        Class<?> tClass = t.getClass();
        TableName tableName = tClass.getAnnotation(TableName.class);
        if(tableName==null){
            throw new RuntimeException("未使用TableName注解标记表名");
        }

        String name = tableName.name();
        sq.append(name+" set ");

        Field[] fields = tClass.getDeclaredFields();
        String where = " where ";
        for(Field f:fields){
            f.setAccessible(true);
            //主键列
            TableId id = f.getAnnotation(TableId.class);
            if(id!=null){
                try {
                    where += id.value() + "=" +f.get(t);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }else{
                //不是主键列
                TableField field = f.getAnnotation(TableField.class);
                if(field!=null){
                    try {
                        //针对列名属性名不一样的情况
                        sq.append(field.value() + "='" + f.get(t) + "',");
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }else{
                    try {
                        //针对列名属性名一样的情况
                        sq.append(f.getName() + "='" + f.get(t) +"',");
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        String str = sq.substring(0, sq.lastIndexOf(","));
        String sql = str + where;
        try{
            System.out.println(sql);
            connection = DBUtil.getConnection();
            ps = connection.prepareStatement(sql);
            int i = ps.executeUpdate();
            return i;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DBUtil.closeAll(rs,ps,connection);
        }
        return 0;

    }


    /**
     *
     * @param t
     * @return
     * 添加
     */
    public int insert(T t){
        StringBuffer sql = new StringBuffer("insert into ");
        Class<?> tClass = t.getClass();
        TableName tableName = tClass.getAnnotation(TableName.class);
        if(tableName==null){
            throw new RuntimeException("没有使用TableName注解标记表名");
        }
        String name = tableName.name();
        sql.append(name+" values ");



        //集合封装值
        ArrayList<Object> values = new ArrayList<>();
        Field[] fields = tClass.getDeclaredFields();
        for(Field f:fields){
            f.setAccessible(true);
            try {
                Object value = f.get(t);
                System.out.println("{{{{{{{{{{{{{{"+value);
                values.add("'"+value+"'");
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        /*System.out.println(values);*/
        String replace = values.toString().replace("[", "(").replace("]", ")");
        sql.append(replace);
        System.out.println(sql);

        try {
            connection = DBUtil.getConnection();
            ps = connection.prepareStatement(sql.toString());
            int i = ps.executeUpdate();
            return i;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DBUtil.closeAll(rs,ps,connection);
        }
        return 0;
    }

    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        StudentDao studentDao = new StudentDao();
//        studentDao.insert(new Student(3,"206319","小方","男","139","河南郑州"));
//        studentDao.update(new Student(3,"222","小明","男","11125","河南郑州"));
//        studentDao.delete(2);
        System.out.println(studentDao.selectAll());
//        System.out.println(studentDao.selectById(1));
    }

}

查询所有

查询单个

 插入

 修改

删除

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值