Mybatis核心原理简单实现

1、导入一个依赖

点击查看代码
     <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>
2、有一个mapper.xml文件
点击查看代码
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.bh.dao.IStudentDAO">
    <select id="findAll" resultType="com.bh.po.Student2" >
        select * from student
    </select>

    <insert id="save" parameterType="com.bh.po.Student">
        insert into student values(#{id}, #{name})
    </insert>

    <delete id="remove" parameterType="com.bh.po.Student">
        delete from student where id=#{id}
    </delete>

    <update id="modify" parameterType="com.bh.po.Student">
        update student set name=#{name} where id=#{id}
    </update>

</mapper>
3、封装jdbc中execute文件
点击查看代码
 public List executeQuery(String sql,String resultType){
        PreparedStatement ps = null;
        ResultSet rs = null;
        List list = new ArrayList();

        try {
            ps = DbManager.getConnection().prepareStatement(sql);
             rs = ps.executeQuery();
             //根据检索结果,放到resultType的po中
            ResultSetMetaData metaData = rs.getMetaData();//得到结果集(rs)的结构
            //检索结果的所有列数个数
            int columnCount = metaData.getColumnCount();
       /*     for (int i = 1; i < columnCount; i++) {
                //获取检索列名
                String columnLabel = metaData.getColumnLabel(i);
                System.out.println(columnLabel);
                //获取列名字段类型
                String columnTypeName = metaData.getColumnTypeName(i);
                System.out.println(columnTypeName);
            }*/
            //根据resultType,获得类对象
            Class clz = Class.forName(resultType);
            while (rs.next()){
                //po
                Object po = clz.newInstance();
                for (int i = 1; i < columnCount; i++) {
                    //取得第i列的列名
                    String columnName = metaData.getColumnLabel(i);
                    //根据列名取内容
                    String value = rs.getString(columnName);

                    //根据列名获得成员属性
                    Field declaredField = clz.getDeclaredField(columnName);
                    //获得成员属性的类型
                    Class type = declaredField.getType();

                    String methodName = "set" + columnName.substring(0,1).toUpperCase() +columnName.substring(1);
                    //根据类对象取得方法
                    Method setMethod = clz.getMethod(methodName, type);

                    //执行set方法,将db中的值放到po中去
                    if ("int".equals(type.getName())){
                        setMethod.invoke(po,Integer.valueOf(value));

                    }else if ("java.lang.String".equals(type.getName())){
                        setMethod.invoke(po,value);
                    }




                }
                list.add(po);
                System.out.println("==============");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                rs.close();
                ps.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }


        return list;
    }
5、测试调用
点击查看代码
package com.bh.test;

import com.bh.jdbc.Execute;
import com.bh.po.Student2;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class TestDom {
    public static void main(String[] args) {
        System.out.println("start============");
        //读取配置文件
        InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("mapper/StudentMapper.xml");
        //解析xml格式的配置文件
        SAXReader reader = new SAXReader();
        try {
            Document doc = reader.read(in);
            //获得xml文件根节点
            Element rootElement = doc.getRootElement();
            /*System.out.println(rootElement.getName());//根节点为mapper*/
            //获取root节点获得所有的子节点
            List<Element> elements = rootElement.elements();
            //遍历所有子节点
            for (Element e:elements) {
                String idValue = e.attributeValue("id");
                String parameterType = e.attributeValue("parameterType");
                String resultType = e.attributeValue("resultType");
                String sql = e.getText().trim();
              /*  System.out.println(sql);
                System.out.println(idValue);
                System.out.println(parameterType);
                System.out.println(resultType);
                System.out.println("===============");*/


                //模拟检索查询
                if ("findAll".equals(idValue)){
                    Execute execute = new Execute();
                    List<Student2> list = execute.executeQuery(sql, resultType);
                    for (Student2 st:list) {
                        System.out.println(st.getId()+st.getName()+st.getSex()+st.getScore()+st.getPhone());
                    }

                }
            }
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }


        System.out.println("end============");
    }
}

posted @ 2023-05-27 09:46  liangkuan  阅读(17)  评论(0)    收藏  举报