简易实现orm框架

jdbcTemplate

主体代码

package com.test.dao.common;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
	封装jdbc
	
	此代码中,所有的泛型(或者说实体类)都要继承HashMap才行
*/
public class JdbcTemplate {
    private Connection conn;
    private static JdbcTemplate instance;

    // 保存后,在同个线程中(同一次请求中)拿到的数据库连接都是同一个。
    private static ThreadLocal<List<JdbcTemplate>> daosLocal = new ThreadLocal<>();

    private JdbcTemplate() {
        // FIXME 后期改造成读取配置文件
        String url = "jdbc:mysql://192.168.129.15:3306/blog";
        String username = "root";
        String password = "11111";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static JdbcTemplate getInstance() {
        List<JdbcTemplate> daos = daosLocal.get();
        if (null == daos || daos.isEmpty()) {
            instance = new JdbcTemplate();
            daos = new ArrayList<>();
            daos.add(instance);
            daosLocal.set(daos);
            return instance;
        } else {
            return daos.get(0);
        }
    }

    public <T> List<T> findList(String sql, Class<T> cla) {
        List<T> list = new ArrayList<>();
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            if (null != conn) {
                ps = conn.prepareStatement(sql);
            }
            rs = ps.executeQuery();
            while (rs.next()) {
                T obj = cla.newInstance();
                // Obj必须继承自HashMap
                // columnName就是map的key,ColumnValue就是map的value
                // 后期可以改造成通过注解获取columnName,模拟hibernate
                // 也可以改造成xml获取columnName,模拟mybatis
                HashMap<String, Object> rec = (HashMap<String, Object>) obj;
                ResultSetMetaData metaData = rs.getMetaData();
                for (int i = 0; i < metaData.getColumnCount(); i++) {
                    rec.put(metaData.getColumnName(i + 1).toLowerCase(), rs.getObject(metaData.getColumnName(i + 1)));
                }
                list.add(obj);
            }
        } catch (SQLException | InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        } finally {
            close(ps, rs);
        }
        return list;
    }

    public <T extends HashMap<String, Object>> int insert(T obj) {
        int rowCount = 0;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            // Obj必须继承自HashMap
            // columnName就是map的key,ColumnValue就是map的value
            // 后期可以改造成通过注解获取columnName,模拟hibernate
             // 也可以改造成xml获取columnName,模拟mybatis
            HashMap<String, Object> rec = (HashMap<String, Object>) obj;
            StringBuffer buffer = new StringBuffer();
            buffer.append("insert into ");
            buffer.append(getTableName(obj));
            buffer.append(" ( ");
            Set<String> keys = rec.keySet();
            int i = 0;
            for (String key : keys) {
                buffer.append(key);
                i++;
                if (i != keys.size()) {
                    buffer.append(",");
                }
            }
            buffer.append(" ) ");
            buffer.append(" values ( ");
            for (int j = 0; j < keys.size(); j++) {
                buffer.append("?");
                if (j != keys.size() - 1) {
                    buffer.append(",");
                }
            }
            buffer.append(" ) ");
            rowCount = transcation(buffer.toString(), rec, false);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(ps, rs);
        }
        return rowCount;
    }

    public <T extends HashMap<String, Object>> int update(T obj) {
        int rowCount = 0;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            // Obj必须继承自HashMap
             // columnName就是map的key,ColumnValue就是map的value
             // 后期可以改造成通过注解获取columnName,模拟hibernate
             // 也可以改造成xml获取columnName,模拟mybatis
            HashMap<String, Object> rec = (HashMap<String, Object>) obj;
            StringBuffer buffer = new StringBuffer();
            buffer.append("update ");
            buffer.append(getTableName(obj));
            buffer.append(" set ");
            Set<String> keys = rec.keySet();
            int i = 0;
            for (String key : keys) {
                buffer.append(key);
                buffer.append(" = ");
                buffer.append(" ? ");
                i++;
                if (i != keys.size()) {
                    buffer.append(",");
                }
            }
            // FIXME 读取注解,获取主键,暂时写死,后期修改
            buffer.append(" where id = ? ");
            rowCount = transcation(buffer.toString(), rec, true);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(ps, rs);
        }
        return rowCount;
    }

    public <T extends HashMap<String, Object>> int delete(T obj) {
        PreparedStatement ps = null;
        ResultSet rs = null;
        int rowCount = 0;
        try {
            // Obj必须继承自HashMap
                // columnName就是map的key,ColumnValue就是map的value
                // 后期可以改造成通过注解获取columnName,模拟hibernate
                // 也可以改造成xml获取columnName,模拟mybatis
            HashMap<String, Object> rec = (HashMap<String, Object>) obj;
            StringBuffer buffer = new StringBuffer();
            buffer.append("delete from ");
            buffer.append(getTableName(obj));
            buffer.append(" where ");
            Set<String> keys = rec.keySet();
            int i = 0;
            for (String key : keys) {
                buffer.append(key);
                buffer.append(" = ");
                buffer.append(" ? ");
                i++;
                if (i != keys.size()) {
                    buffer.append(" and ");
                }
            }
            rowCount = transcation(buffer.toString(), rec, false);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(ps, rs);
        }
        return rowCount;
    }

    //添加参数
    private int transcation(String sql, Map<String, Object> rec, boolean flag) throws SQLException {
        PreparedStatement ps = null;
        //ResultSet rs = null;
        ps = conn.prepareStatement(sql);
        int rowCount = 0;
        int j = 0;
        Set<String> keys = rec.keySet();
        for (String key : keys) {
            ps.setObject(++j, rec.get(key));
        }
        if (flag) {
            ps.setObject(++j, rec.get("id"));
        }
        conn.setAutoCommit(false);
        rowCount = ps.executeUpdate();
        conn.commit();
        return rowCount;
    }

    //获取tablename,后期改造,通过注解,xml获取
    private <T extends HashMap<String, Object>> String getTableName(T obj) {
        String packageName = obj.getClass().getPackage().getName();
        String className = obj.getClass().getName();
        String name = className.substring(packageName.length() + 1, className.length()).toLowerCase();
        return name;
    }

    //关闭
    public void close(PreparedStatement ps, ResultSet rs) {
        try {
            if (null != rs) {
                rs.close();
            }
            if (null != ps) {
                ps.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void close() {
        try {
            if (null != conn) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            removeConnetion();
        }
    }

    public void closeAllConns() {
        List<JdbcTemplate> daos = daosLocal.get();
        if (null == daos) {
            return;
        }
        for (int i = 0; i < daos.size(); i++) {
            daos.get(i).close();
        }
        daos.clear();
    }

    private void removeConnetion() {
        List<JdbcTemplate> daos = daosLocal.get();
        if (null != daos) {
            for (int i = 0; i < daos.size(); i++) {
                JdbcTemplate dao = daos.get(i);
                if (dao.conn == conn) {
                    daos.remove(i);
                }
                i--;
            }
        }
    }
}

实体类

注意:实体类必须继承HashMap

package com.test.dao.common.test;

import java.util.HashMap;

public class Test extends HashMap<String,Object> {
    public String getId() {
        return super.get("id").toString();
    }

    public void setId(String id) {
        super.put("id", id);
    }

    public String getUsername() {
        return super.get("username").toString();
    }

    public void setUsername(String username) {
        super.put("username", username);
    }

    public String getPassword() {
        return super.get("password").toString();
    }

    public void setPassword(String password) {
        super.put("password", password);
    }

}

测试类

package com.test.dao.common.test;

import com.test.dao.common.JdbcTemplate;

import java.util.List;

public class TestDb {
    public static void main(String[] args) {
        for(int i = 0; i < 500; i ++){
            Runnable fun = new Runnable(){
                @Override
                public void run() {
                    JdbcTemplate dao = JdbcTemplate.getInstance();
                    List<Test> list = dao.findList("select * from test", Test.class);
                    for (Test test : list) {
                        System.out.println(test.getId());
                        System.out.println(test.getUsername());
                        System.out.println(test.getPassword());
                    }
                    Test test = new Test();
                    test.setId("4");
                    test.setUsername("66");
                    test.setPassword("3");
                    int insert = dao.delete(test);
                    System.out.println(insert);
                    list = dao.findList("select * from test", Test.class);
                    for (Test rec : list) {
                        System.out.println(rec.getId());
                        System.out.println(rec.getUsername());
                        System.out.println(rec.getPassword());
                    }
                }
            };
            Thread thread = new Thread(fun);
            thread.start();
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值