Java篇--反射和注解综合使用

自定义简单版ORMapping框架:
1、在mysql中创建相应的表
create table t_user(
    id int not null auto_increment,
    name varchar(10) not null,
    age int not null,
    birth_day date,
    primary key(id)
);

在这里插入图片描述
我的mysql版本:
在这里插入图片描述

2、框架代码

在这里插入图片描述
HuiqBean.java:

package com.xiaoqiang.interview.framework.annotation;

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

/**
 * Created by Huiq on 2021/4/11.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface HuiqBean {

    String value();
}

HuiqField.java:

package com.xiaoqiang.interview.framework.annotation;

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

/**
 * Created by Huiq on 2021/4/11.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface HuiqField {

    String value();
}

BaseDAOImpl.java:

package com.xiaoqiang.interview.framework.dao.impl;

import com.xiaoqiang.interview.framework.dao.BaseDAO;
import com.xiaoqiang.interview.framework.utils.DBUtils;
import com.xiaoqiang.interview.framework.utils.Tools;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * Created by Huiq on 2021/4/11.
 */
public class BaseDAOImpl implements BaseDAO {

    /**
     * 入参是T:User
     *
     * insert into t_user(name,age,birth_day) values(?,?,?);
     */
    @Override
    public <T> Serializable save(T t) {
        StringBuilder builder = new StringBuilder("insert into ");
        String table = Tools.getTable(t.getClass());
        builder.append(table).append("(");

        Class<?> clazz = t.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if (!field.getName().equals("id")) {
                String colum = Tools.getColum(field);
                builder.append(colum).append(",");
            }
        }
        builder.deleteCharAt(builder.toString().length()-1)
                .append(") values (");

        for (Field field : fields) {
            if (!field.getName().equals("id")) {
                builder.append("?,");
            }
        }
        builder.deleteCharAt(builder.toString().length()-1)
                .append(")");
        System.out.println(builder.toString());

        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        int index = 1;
        try {
            connection = DBUtils.getConnection();
            pstmt = connection.prepareStatement(builder.toString(), new String[]{"id"});

            for (Field field : fields) {
                if (!field.getName().equals("id")) {
                    String getMethod = Tools.getMethod(field);
                    Method method = clazz.getDeclaredMethod(getMethod);
                    Object obj = method.invoke(t);
                    pstmt.setObject(index++, obj);
                }
            }

            int rowCount = pstmt.executeUpdate();
            System.out.println("rowCount: " + rowCount);

            if (rowCount > 0) {
                rs = pstmt.getGeneratedKeys();
                rs.next();
                return (Serializable)rs.getObject(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}

BaseDAO.java:

package com.xiaoqiang.interview.framework.dao;

import java.io.Serializable;

/**
 * Created by Huiq on 2021/4/11.
 */
public interface BaseDAO {

    /**
     * insert into xxx(col1,col2,col3...) values(?,?,?...)
     */
    <T> Serializable save(T t);
}

User.java:

package com.xiaoqiang.interview.framework.domain;

import com.xiaoqiang.interview.framework.annotation.HuiqBean;
import com.xiaoqiang.interview.framework.annotation.HuiqField;

import java.util.Date;

/**
 * Created by Huiq on 2021/4/11.
 */
@HuiqBean("t_user")
public class User {

    private Integer id;

    private String name;

    private Integer age;

    @HuiqField("birth_day")
    private Date birthday;

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", birthday=" + birthday +
                '}';
    }

    public User(String name, Integer age, Date birthday) {
        this.name = name;
        this.age = age;
        this.birthday = birthday;
    }

    public User() {
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
}

DBUtils.java:

package com.xiaoqiang.interview.framework.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * Created by Huiq on 2021/4/12.
 */
public class DBUtils {

    public static Connection getConnection() {
        String url = "jdbc:mysql://localhost:3306/database1?useSSL=false";
        String user = "root";
        String password = "123456";
        Connection connection = null;

        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(url, user, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }

    public static void close(Connection connection) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

Tools.java:

package com.xiaoqiang.interview.framework.utils;

import com.xiaoqiang.interview.framework.annotation.HuiqBean;
import com.xiaoqiang.interview.framework.annotation.HuiqField;

import java.lang.reflect.Field;

/**
 * Created by Huiq on 2021/4/11.
 */
public class Tools {

    /**
     * 根据注解获取表名
     */
    public static String getTable(Class<?> clazz) {
        String tableName = "";
        HuiqBean huiqBean = clazz.getAnnotation(HuiqBean.class);
        if (huiqBean != null) {
            tableName = huiqBean.value();
        } else {
            tableName = clazz.getSimpleName();
        }
        return tableName;
    }

    /**
     * 根据注解获取属性名称
     */
    public static String getColum(Field field) {
        String colum = "";
        HuiqField huiqField = field.getAnnotation(HuiqField.class);
        if (huiqField != null) {
            colum = huiqField.value();
        } else {
            colum = field.getName();
        }
        return colum;
    }

    public static String getMethod(Field field) {
        String fieldName = field.getName();

        // id==>getId  name==>getName
        String name = fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);
        return "get" + name;
    }
}
3、测试代码

BaseDAOImplTest.java:

package com.xiaoqiang.interview.framework.dao.impl;

import com.xiaoqiang.interview.framework.dao.BaseDAO;
import com.xiaoqiang.interview.framework.domain.User;
import org.junit.Test;

import java.io.Serializable;
import java.util.Date;

/**
 * Created by Huiq on 2021/4/12.
 */
public class BaseDAOImplTest {

    @Test
    public void test02() {
        BaseDAO dao = new BaseDAOImpl();
        for (int i=0; i<10; i++) {
            User user = new User("xiaoqiang" + i, 18+i, new Date());

            Serializable id = dao.save(user);
            System.out.println("id: " + id);
        }
    }

    @Test
    public void test01() {
        BaseDAO dao = new BaseDAOImpl();
        User user = new User("xiaoqiang", 18, new Date());

        Serializable id = dao.save(user);
        System.out.println("id: " + id);
    }
}

DBUtilsTest.java:

package com.xiaoqiang.interview.framework.utils;

import org.junit.Test;

/**
 * Created by Huiq on 2021/4/12.
 */
public class DBUtilsTest {

    @Test
    public void test01() {
        System.out.println(DBUtils.getConnection());
    }
}

ToolsTest.java:

package com.xiaoqiang.interview.framework.utils;

import com.xiaoqiang.interview.framework.domain.User;
import org.junit.Test;

import javax.tools.Tool;
import java.lang.reflect.Field;

/**
 * Created by Huiq on 2021/4/11.
 */
public class ToolsTest {

    @Test
    public void test03() throws Exception {
        Class<?> clazz = Class.forName("com.xiaoqiang.interview.framework.domain.User");
        Field field = clazz.getDeclaredField("name");
        System.out.println(Tools.getMethod(field));

        field = clazz.getDeclaredField("birthday");
        System.out.println(Tools.getMethod(field));
    }

    @Test
    public void test02() throws Exception {
        Class<?> clazz = Class.forName("com.xiaoqiang.interview.framework.domain.User");
        Field field = clazz.getDeclaredField("birthday");
        System.out.println(Tools.getColum(field));
    }

    @Test
    public void test01() throws Exception {
        System.out.println(Tools.getTable(User.class));
    }
}
4、插入数据

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小强签名设计

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值