Java高级-反射+注解实现 JDdbcUtils(对象和表的映射)

使用注解和反射实现 对象和表的映射

1.注解

1.@Entity

package com.ooyhao.jdbc.annotation;

import java.lang.annotation.*;

@Target(ElementType.TYPE)
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface Entity {
    public String value();//tableName
}

2.@Column

package com.ooyhao.jdbc.annotation;

import java.lang.annotation.*;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Column {
    public String value();//列名
}

3.@IsExist

package com.ooyhao.jdbc.annotation;


import java.lang.annotation.*;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface IsExist {
    public boolean value();//是否存在
}

2.User Bean

package com.ooyhao.jdbc.bean;

import com.ooyhao.jdbc.annotation.Column;
import com.ooyhao.jdbc.annotation.Entity;
import com.ooyhao.jdbc.annotation.IsExist;

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

@Entity("sys_user")
public class User implements Serializable {

    @Column("id")
    private Long id;

    @Column("username")
    private String username;

    @Column("password")
    private String password;

    @Column("create_time")
    private Date createTime;

    @Column("create_user")
    private String createUser;

    @Column("modify_time")
    private Date modifyTime;

    @Column("modify_user")
    @IsExist(true)
    private String modifyUser;

    public User() {}

    public Long getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public String getCreateUser() {
        return createUser;
    }

    public void setCreateUser(String createUser) {
        this.createUser = createUser;
    }

    public Date getModifyTime() {
        return modifyTime;
    }

    public void setModifyTime(Date modifyTime) {
        this.modifyTime = modifyTime;
    }

    public String getModifyUser() {
        return modifyUser;
    }

    public void setModifyUser(String modifyUser) {
        this.modifyUser = modifyUser;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", createTime=" + createTime +
                ", createUser='" + createUser + '\'' +
                ", modifyTime=" + modifyTime +
                ", modifyUser='" + modifyUser + '\'' +
                '}';
    }
}

3.DBHelper

package com.ooyhao.jdbc.helper;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class DbHelper {

    public static final String URL = "jdbc:mysql://120.79.167.XXX:3306/GD?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&autoReconnect=true&useSSL=false";
    public static final String USERNAME = "root";
    public static final String PASSWORD = "XXXXXXXX";
    public static final String DRIVER = "com.mysql.jdbc.Driver";


    public static Connection getConnection(){
        try{
            Class.forName(DRIVER);
            Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
            return connection;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }


    public static void close(Connection connection, Statement statement, ResultSet resultSet){
        try{
            if (connection != null){
                connection.close();
            }
            if (statement != null){
                statement.close();
            }
            if (resultSet != null){
                resultSet.close();
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }

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

}

4.IJdbcDao

package com.ooyhao.jdbc.jdbc;

import com.ooyhao.jdbc.annotation.Column;
import com.ooyhao.jdbc.annotation.Entity;
import com.ooyhao.jdbc.annotation.IsExist;
import com.ooyhao.jdbc.helper.DbHelper;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class IJdbcDao {

    public <T> List<T> selectDataToBean(Class<T> tClass) {
        List<T> list = new ArrayList<>();
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            String simpleName = tClass.getSimpleName();
            String tableName = String.valueOf(simpleName.charAt(0)).toLowerCase() + simpleName.substring(1);
            boolean annotationPresent = tClass.isAnnotationPresent(Entity.class);
            if (annotationPresent){
                Entity entity = tClass.getAnnotation(Entity.class);
                tableName = entity.value();
            }
            String sql = " select * from "+tableName;

            connection = DbHelper.getConnection();

            preparedStatement = connection.prepareStatement(sql);
            resultSet = preparedStatement.executeQuery();

            Field[] fields = tClass.getDeclaredFields();

            Map<String,Field> map = new HashMap<>();
            for (Field field : fields){

                String columnValue = null;
                if (field.isAnnotationPresent(Column.class)){
                    Column column = field.getAnnotation(Column.class);
                    columnValue = column.value();
                }
                boolean isExistValue = true;
                if (field.isAnnotationPresent(IsExist.class)){
                    IsExist isExist = field.getAnnotation(IsExist.class);
                    isExistValue = isExist.value();
                }
                if (isExistValue){
                    map.put(columnValue,field);
                }
            }
            int colCount = resultSet.getMetaData().getColumnCount();
            while (resultSet.next()){

                T t = tClass.newInstance();
                for (int i = 1; i <= colCount; i++) {
                    String columnLabel = resultSet.getMetaData().getColumnLabel(i);
                    Field field = map.get(columnLabel);
                    if (field != null){
                        field.setAccessible(true);
                        field.set(t,resultSet.getObject(i));
                    }
                }
                list.add(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            DbHelper.close(connection,preparedStatement,resultSet);
        }
        return list;
    }
}

5.测试及结果

public class App {
    public static void main(String[] args) {
        IJdbcDao iJdbcDao = new IJdbcDao();
        List<User> users = iJdbcDao.selectDataToBean(User.class);
        for (User user : users){
            System.out.println(user);
        }
    }
}

结果:
User{id=1, username='admin', password='1', createTime=2019-01-23 17:24:24.0, createUser='admin', modifyTime=2019-01-23 17:24:24.0, modifyUser='admin'}
User{id=2, username='jack', password='1', createTime=2019-01-23 17:24:28.0, createUser='admin', modifyTime=2019-01-23 17:24:24.0, modifyUser='admin'}
User{id=8, username='23', password='null', createTime=2019-01-25 10:51:57.0, createUser='admin', modifyTime=2019-01-25 10:51:57.0, modifyUser='admin'}
User{id=3, username='林黛玉', password='123456', createTime=2019-01-23 17:29:56.0, createUser='admin', modifyTime=2019-01-23 17:29:56.0, modifyUser='admin'}
User{id=4, username='贾宝玉', password='123456', createTime=2019-01-23 17:30:24.0, createUser='admin', modifyTime=2019-01-23 17:30:24.0, modifyUser='admin'}
User{id=6, username='ouYang', password='123456', createTime=2019-01-23 17:30:47.0, createUser='admin', modifyTime=2019-01-23 17:30:47.0, modifyUser='admin'}

关注小编微信公众号获取更多资源


你可能感兴趣的:(Java)