反射——CRUD小工具 第二版本

一、描述

这里对12月16日用反射写的crud工具进行了功能扩展,新开发了三个注解@Column、@Entity、@Id用来做关系映射,dataSource的配置信息通过xml配置文件配置。

二、依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.xsl</groupId>
    <artifactId>crud-utils</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency> <!-- junit 4.7 -->
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <type>jar</type>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.25</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.10</version>
        </dependency>
    </dependencies>

</project>

三、目录结构

在这里插入图片描述

四、注解开发

1、@Entity

package com.xsl.anno;

import java.lang.annotation.*;

/**
 * @Description 标记该实体类是一个entity并做关系映射;
 * @Author xsl
 * @Date 2020/1/10 16:31
 **/
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Entity {
    /**
     * 表名
     * @return
     */
    String value();
}

2、@Column

package com.xsl.anno;

import java.lang.annotation.*;

/**
 * @Description 声明这个列是一个表字段并做关系映射
 * @Author xsl
 * @Date 2020/1/10 16:33
 **/
@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Column {
    /**
     * 域名与表字段名关系映射
     * @return
     */
    String value();
}

3、Id

package com.xsl.anno;

import java.lang.annotation.*;

/**
 * @Description 声明该字段为主键
 * @Author xsl
 * @Date 2020/1/10 16:30
 **/
@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Id {

}

五、配置文件crud-util.xml

<?xml version="1.0" encoding="UTF-8"?>
<crud>
    <dataSource>
        <driver>com.mysql.jdbc.Driver</driver>
        <url>jdbc:mysql://192.168.25.131:3306/crud</url>
        <username>root</username>
        <password>root</password>
    </dataSource>
</crud>

六、工具类

package com.xsl.util;

import com.xsl.anno.Column;
import com.xsl.anno.Entity;
import com.xsl.anno.Id;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.net.URL;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description 一个Crud的小工具类, 可以单表增删改查简单实体类,这里添加了对象关系映射与配置文件
 * @param <T>实体类
 * @param <K>主键
 * @Author xsl
 * @Date 2020/1/10 16:26
 **/
public class CrudUtil<T, K> {
    /**
     * 驱动
     */
    private static String DRIVER = null;
    /**
     * 数据库url
     */
    private static String URL = null;
    /**
     * 用户名
     */
    private static String USERNAME = null;
    /**
     * 密码
     */
    private static String PASSWORD = null;

    /**
     * 初始化配置信息
     * 注册驱动
     */
    static {
        URL resource = Thread.currentThread().getContextClassLoader().getResource("crud-util.xml");
        String path = resource.getPath();
        File file = new File(path);
        //获得解析器DocumentBuilder的工厂实例DocumentBuilderFactory  然后拿到DocumentBuilder对象
        DocumentBuilder newDocumentBuilder = null;
        try {
            newDocumentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        //与磁盘文件关联的非空Document对象
        Document doc = null;
        try {
            doc = newDocumentBuilder.parse(file);
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //通过文档对象获得该文档对象的根节点
        Element root = doc.getDocumentElement();
        //通过根节点获得子节点
        NodeList personList = root.getElementsByTagName("dataSource");
        //这里获取第1个节点
        Node item = personList.item(0);
        Element element = (Element)item;
        //这里获取第1个节点下 name节点值
        NodeList driver = element.getElementsByTagName("driver");
        DRIVER = driver.item(0).getTextContent();
        NodeList url = element.getElementsByTagName("url");
        URL = url.item(0).getTextContent();
        NodeList username = element.getElementsByTagName("username");
        USERNAME = username.item(0).getTextContent();
        NodeList password = element.getElementsByTagName("password");
        PASSWORD = password.item(0).getTextContent();
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取connection
     * @return Connection
     * @throws SQLException
     */
    private  Connection getConnection() throws SQLException {
        Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        return connection;
    }

    /**
     * 查找数据库中所有此实体类对应的数据封装实体对象
     * @param cls 实体类对应的字节码对象
     * @return 所有的实体类
     * @throws Exception
     */
    public List<T> findAll(Class cls) throws Exception {
        String tableName = getTableName(cls);
        String sql = "select * from " + tableName;
        Connection connection = getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        List<T> list = new ArrayList<>();
        while (resultSet.next()) {
            list.add(resultTransferEntity(resultSet, cls));
        }
        connection.close();
        return list;
    }


    /**
     * 根据id查找该实体类对象的对应数据封装
     * @param cls 实体类字节码
     * @param id  要查找的id
     * @return 实体类对象
     * @throws Exception
     */
    public T findById(Class cls, K id) throws Exception {
        String tableName = getTableName(cls);
        String idName = getTableIdName(cls);
        String sql = "select * from " + tableName + " where "+idName+" = ?";
        Connection connection = getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatementSetValue(preparedStatement, id, 1);
        ResultSet resultSet = preparedStatement.executeQuery();
        T t = null;
        while (resultSet.next()) {
            t = resultTransferEntity(resultSet, cls);
        }
        return t;
    }

    /**
     * 根据id删除
     * @param cls 要删除的对象的字节码对象
     * @param id  要删除的对象的id
     * @throws Exception
     */
    public void deleteById(Class cls, K id) throws Exception {
        String tableName = getTableName(cls);
        String idName = getTableIdName(cls);
        String sql = "delete from " + tableName + " where "+idName+" = ?";
        Connection connection = getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatementSetValue(preparedStatement, id, 1);
        preparedStatement.executeUpdate();
    }

    /**
     * 将实体类持久化到数据库
     * @param t   实体类对象
     * @throws Exception
     */
    public void save(T t) throws Exception {
        Class<?> cls = t.getClass();
        String tableName = getTableName(cls);
        StringBuilder firstSql = new StringBuilder(" insert into " + getTableName(cls) + " ( ");
        StringBuilder lastSql = new StringBuilder(" values ( ");
        Field[] fields = cls.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            if (field.isAnnotationPresent(Column.class)){
                if (!isNull(field, t)) {
                    firstSql.append(field.getAnnotation(Column.class).value()).append(" ,");
                    lastSql.append(" ? ,");
                }
            }
        }
        firstSql.replace(firstSql.length() - 1, firstSql.length(), " ").append(" ) ");
        lastSql.replace(lastSql.length() - 1, lastSql.length(), " ").append(" ) ");
        Connection connection = getConnection();
        String sql = new String(firstSql.append(lastSql));
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        for (int i = 0; i < fields.length; i++) {
            if (!isNull(fields[i], t) && fields[i].isAnnotationPresent(Column.class)) {
                preparedStatementSetValue(preparedStatement, fields[i].get(t), i + 1);
            }
        }
        preparedStatement.executeUpdate();
    }


    /**
     * 修改对象,该对象必须要id
     * @param t
     */
    public void update(T t) throws Exception {
        Class<?> cls = t.getClass();
        StringBuilder firstSql = new StringBuilder(" update ").append(getTableName(t.getClass())).append(" set ");
        StringBuilder lastSql = new StringBuilder(" where "+getTableIdName(cls)+" = ? ");
        Field[] declaredFields = cls.getDeclaredFields();
        int index = 0;
        for (Field field : declaredFields) {
            field.setAccessible(true);
            if (!isNull(field,t) && field.isAnnotationPresent(Column.class)){
                firstSql.append(field.getAnnotation(Column.class).value()).append(" = ?,");
                index++;
            }
        }
        firstSql.replace(firstSql.length() - 1, firstSql.length(), " ");
        StringBuilder sql = firstSql.append(lastSql);
        System.out.println(new String(sql));
        Connection connection = getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(new String(sql));
        for (Field field : declaredFields) {
            field.setAccessible(true);
            if (!isNull(field, t) && field.isAnnotationPresent(Column.class)) {
                preparedStatementSetValue(preparedStatement,field.get(t),index);
            }
        }
        for (int i = 0; i < declaredFields.length ; i++) {
            if (!isNull(declaredFields[i], t)) {
                preparedStatementSetValue(preparedStatement, declaredFields[i].get(t), i + 1);
            }
        }
        Field id = getEntityIdFiled(cls);
        preparedStatementSetValue(preparedStatement,id.get(t),index+1);
        preparedStatement.executeUpdate();
    }



    /**
     * @param preparedStatement 由Connection预编译sql语句得到的preparedStatement
     * @param value             给preparedStatement设置的值
     * @param index             preparedStatement的索引
     * @throws SQLException
     */
    private void preparedStatementSetValue(PreparedStatement preparedStatement, Object value, int index) throws SQLException {
        switch (value.getClass().getName()) {
            case "int":
            case "java.lang.Integer":
                preparedStatement.setInt(index, (Integer) value);
                break;
            case "java.lang.String":
                preparedStatement.setString(index, (String) value);
                break;
            case "long":
            case "java.lang.Long":
                preparedStatement.setLong(index, (Long) value);
                break;
            default:
                throw new RuntimeException("id别乱用类型了别闹");
        }
    }


    /**
     * @param cls 实体类的字节码对象
     * @return 获取这个实体类对应的表名
     */
    private String getTableName(Class cls) throws Exception {
        String  tableName = null;
        if (cls.isAnnotationPresent(Entity.class)){
            Entity annotation = (Entity) cls.getAnnotation(Entity.class);
            tableName = annotation.value();
        }else {
            throw new Exception(cls.getName()+"类没有被com.xsl.anno.Entity注解标注");
        }
        return tableName;
    }

    /**
     * 获取主键的表名
     * @param cls
     * @return
     * @throws Exception
     */
    private String getTableIdName(Class cls) throws Exception {
        String idName = null;
        boolean flag = true;
        Field[] declaredFields = cls.getDeclaredFields();
        for (Field f : declaredFields) {
            f.setAccessible(false);
            if (f.isAnnotationPresent(Id.class)){
                flag = false;
                if (f.isAnnotationPresent(Column.class)){
                    Column column = f.getAnnotation(Column.class);
                    idName = column.value();
                }else {
                    throw new Exception("主键域"+f.getName()+"没有做关系映射");
                }
            }
        }
        if (flag){
            throw new Exception("这个实体没有主键,不能通过主键做任何操作!");
        }
        return  idName;
    }


    private boolean isNull(Field field, T t) throws IllegalAccessException {
        boolean flag = false;
        if (field.get(t) == null) {
            flag = true;
        }
        return flag;
    }



    private T resultTransferEntity(ResultSet resultSet, Class cls) throws Exception {
        Constructor<T> constructor = cls.getConstructor();
        T t = constructor.newInstance();
        Field[] declaredFields = cls.getDeclaredFields();
        for (Field filed : declaredFields) {
            filed.setAccessible(true);
            Class<?> type = filed.getType();
            String filedName = filed.getAnnotation(Column.class).value();
            switch (type.getName()) {
                case "int":
                case "java.lang.Integer":
                    filed.set(t, resultSet.getInt(filedName));
                    break;
                case "java.lang.String":
                    filed.set(t, resultSet.getString(filedName));
                    break;
                case "long":
                case "java.lang.Long":
                    filed.set(t, resultSet.getLong(filedName));
                    break;
                case "short":
                case "java.lang.Short":
                    filed.set(t, resultSet.getShort(filedName));
                    break;
                case "byte":
                case "java.lang.Byte":
                    filed.set(t, resultSet.getByte(filedName));
                    break;
                case "float":
                case "java.lang.Float":
                    filed.set(t, resultSet.getFloat(filedName));
                    break;
                case "double":
                case "java.lang.Double":
                    filed.set(t, resultSet.getDouble(filedName));
                    break;
                default:
                    throw new RuntimeException("功能有限敬请原谅");
            }
        }
        return t;
    }

    /**
     * 获取entity的主键Field
     * @param cls
     * @return
     */
    private Field getEntityIdFiled(Class cls) throws Exception {
        Field[] declaredFields = cls.getDeclaredFields();
        for (Field f : declaredFields) {
            f.setAccessible(true);
            if (f.isAnnotationPresent(Id.class)){
                return f;
            }
        }
        throw new Exception("该entity没有设置主键");
    }

}

七、demo用户类

package com.xsl.entity;

import com.xsl.anno.Column;
import com.xsl.anno.Entity;
import com.xsl.anno.Id;
import lombok.*;

/**
 * @Description 用户实体类
 * @Author xsl
 * @Date 2020/1/10 17:37
 **/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity("SM_USER")
public class User {

    /**
     * 主键
     */
    @Id
    @Column("SM_ID")
    private int id;

    /**
     * 姓名
     */
    @Column("SM_NAME")
    private String name;

}

八、测试

package com.xsl.entity.test;

import com.xsl.entity.User;
import com.xsl.util.CrudUtil;
import org.junit.Test;

import java.util.List;

/**
 * @Description 测试工具类
 * @Author xsl
 * @Date 2020/1/10 18:12
 **/
public class TestMyUtil {
    CrudUtil<User,Integer> util = new CrudUtil<>();

    @Test
    public void testFindAll() throws Exception {
        List<User> all = util.findAll(User.class);
        System.out.println(all);
    }

    @Test
    public void testFindById() throws Exception {
        User user = util.findById(User.class, 4);
        System.out.println(user);
    }

    @Test
    public void testDeleteById() throws Exception {
        util.deleteById(User.class,1);
    }

    @Test
    public void testSave() throws Exception {
        User user = new User();
        user.setId(4);
        user.setName("肖生亮");
        util.save(user);
    }

    @Test
    public void testUpdate() throws Exception {
        User user = new User(1,"张海");
        util.update(user);
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值