mybatis框架仿写

读取properties文件连接数据库

  • properties文件内容
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/user?characterEncoding=utf8
username=root
password=Lixinyu.1

  • 读取properties内容
 ResourceBundle pro = ResourceBundle.getBundle("application");
        String url = pro.getString("url");
        String username = pro.getString("username");
        String pwd = pro.getString("password");
  • 注意如果properties文件中不存在你要get的字段吗,就会报错。
    此时应该使用containskey
if (pro.containsKey("LineToHump")){
            if (Boolean.parseBoolean( pro.getString("LineToHump")) == false){
                Configuration.setLineToHump(false);
            }
        }

mapper层

通过LMapper判断是不是注入了。然后获取方法上面的注解的sql值。即values。

@LMapper
public interface UserMapper {
     @Select("select * from user where id = 1")
     User select();
     @Select("select * from user")
     List<User> selectAll();
     @Update("update user set username = '是啥' where id = 1 ")
     int update();
     @Delete("delete from user where id = 2 ")
     int delete();
     @Insert("insert into user(username,nick_name,birthday,sex,address)values('水水水水','卡','2021-09-10 14:56:56',1,'啥的') ")
     int insert();
}

代理对象工厂类,用来创造一个代理对象

public class MapperProxyFactory {
    public static UserMapper getMapper(Class mapper) {
    
        Annotation annotation = mapper.getAnnotation(LMapper.class);
        if(annotation==null){
            return null;
        }
        InvocationHandler invocationHandler = new MapperProxy();
        UserMapper userMapper = (UserMapper) Proxy.newProxyInstance(mapper.getClassLoader(), new Class[]{mapper}, invocationHandler);
        return userMapper;
    }
}

代理逻辑类

先判断方法上面的注解是什么类型,在执行对应的查询或者修改的方法。

public class MapperProxy implements InvocationHandler {


    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        Annotation[] annotations = method.getAnnotations();
        Annotation annotation = annotations[0];
        if (annotation instanceof Select) {
            String sql = ((Select) annotation).value();
            List list = JDBCUtil.select(sql, method);
            Class<?> type = method.getReturnType();
            if (!type.equals(List.class)) {
                return list.get(0);
            }
            return list;
        } else if (annotation instanceof Update) {
            String sql = ((Update) annotation).value();
            int result = JDBCUtil.update(sql);
            return result;
        } else if (annotation instanceof Delete) {
            String sql = ((Delete) annotation).value();
            int result = JDBCUtil.update(sql);
            return result;
        }else if(annotation instanceof Insert){
            String sql = ((Insert) annotation).value();
            int result = JDBCUtil.update(sql);
            return result;
        }

        return null;
    }
}

查询方法

public static List select(String sql, Method method) throws SQLException, InstantiationException, IllegalAccessException, InvocationTargetException {
        Class<?> returnType = method.getReturnType();
        if (returnType.equals(List.class)) {
            Type genericReturnType = method.getGenericReturnType();
            if (null != genericReturnType && genericReturnType instanceof ParameterizedType) {
                ParameterizedType pt = (ParameterizedType) genericReturnType;
                Class<?> actualTypeArgument = (Class<?>) pt.getActualTypeArguments()[0];
                returnType = actualTypeArgument;
            }
        }
        Method[] methods = returnType.getMethods();
        Object o = returnType.newInstance();
        Connection connection =null;
        try {
            connection = JDBCUtil.getConnection(); //连接数据库
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(sql); //执行sql获取结果集
            ResultSetMetaData metaData = resultSet.getMetaData();
            int count = metaData.getColumnCount(); //获取字段数量
            List list = new ArrayList<>();
            while (resultSet.next()) { //遍历结果集
                for (int i = 0; i < count; i++) {//遍历每个字段
                    String columnName = metaData.getColumnName(i + 1); //获取字段名字
                    Object object = resultSet.getObject(columnName);//获取字段值
                    if(Configuration.LineToHump){  //如果开启了自动转驼峰,就把下划线转驼峰
                        columnName = LineToHump.lineToHump(columnName);
                    }
                    for (Method method1 : methods) {   //获取返回对象的所有方法,遍历。
                        String name = method1.getName();
                        if (name.equals("set" + columnName.substring(0, 1).toUpperCase() + columnName.substring(1))) { //根据set方法赋值
                            method1.invoke(o, object); //执行set方法
                            break;
                        }
                    }
                }
                list.add(o);
            }
            return list;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            connection.close();
        }
        return null;
    }

增删改方法

都用 statement.executeUpdate(sql)就能解决

 public static int update(String sql) throws SQLException {

        Connection connection = null;
        try {
            connection = JDBCUtil.getConnection();
            Statement statement = connection.createStatement();
            int result = statement.executeUpdate(sql);
            return result;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            connection.close();
        }

       return 0;
    }

下划线和驼峰互转

package demo.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LineToHump {

        private static Pattern linePattern = Pattern.compile("_(\\w)");

        /** 下划线转驼峰 */

        public static String lineToHump(String str) {

            str = str.toLowerCase();

            Matcher matcher = linePattern.matcher(str);

            StringBuffer sb = new StringBuffer();

            while (matcher.find()) {

                matcher.appendReplacement(sb, matcher .group(1).toUpperCase());

            }

            matcher.appendTail(sb);

            return sb.toString();

        }

        /** 驼峰转下划线 */

        public static String humpToLine(String str) {

            return str.replaceAll("[A-Z]", "_$0").toLowerCase();

        }

        private static Pattern humpPattern = Pattern.compile("[A-Z]");

        /** 驼峰转下划线 */

        public static String humpToLine2(String str) {

            Matcher matcher = humpPattern.matcher(str);

            StringBuffer sb = new StringBuffer();

            while (matcher.find()) {

                matcher.appendReplacement(sb, "_" + matcher .group(0).toLowerCase());

            }

            matcher.appendTail(sb);

            return sb.toString();

        }

        public static void main(String[] args) {

            String lineToHump = lineToHump("hello_guys");

            System.out.println(lineToHump);

            System.out.println(humpToLine(lineToHump));

            System.out.println(humpToLine2(lineToHump));

        }

}

测试执行

   @Test
    public  void demo()  {
        UserMapper mapper = MapperProxyFactory.getMapper(UserMapper.class);
        List<User> users = mapper.selectAll();
        User select = mapper.select();
        int update = mapper.update();
        int delete = mapper.delete();
        int insert = mapper.insert();
        System.out.println(select.toString());
    }

配置类 可通过properties修改覆盖

public class Configuration {
    public static  Boolean LineToHump = true;

    public static void setLineToHump(Boolean lineToHump) {
        LineToHump = lineToHump;
    }
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值