首頁 > 軟體

Mybatis如何通過介面實現sql執行原理解析

2023-01-24 14:01:31

使用過 mybatis 框架的小夥伴們都知道,mybatis 是個半 orm 框架,通過寫 mapper 介面就能自動實現資料庫的增刪改查,但是對其中的原理一知半解,接下來就讓我們深入框架的底層一探究竟

1、環境搭建

首先引入 mybatis 的依賴,在 resources 目錄下建立 mybatis 核心組態檔 mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <!-- 環境、事務工廠、資料來源 -->
    <environments default="dev">
        <environment id="dev">
            <transactionManager type="JDBC"/>
            <dataSource type="UNPOOLED">
                <property name="driver" value="org.apache.derby.jdbc.EmbeddedDriver"/>
                <property name="url" value="jdbc:derby:db-user;create=true"/>
            </dataSource>
        </environment>
    </environments>

    <!-- 指定 mapper 介面-->
    <mappers>
        <mapper class="com.myboy.demo.mapper.user.UserMapper"/>
    </mappers>

</configuration>

在 com.myboy.demo.mapper.user 包下新建一個介面 UserMapper

public interface UserMapper {
    UserEntity getById(Long id);
    void insertOne(@Param("id") Long id, @Param("name") String name, @Param("json") List<String> json);
}

在 resources 的 com.myboy.demo.mapper.user 包下建立 UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.myboy.demo.mapper.user.UserMapper">

    <select id="getById" resultType="com.myboy.demo.db.entity.UserEntity">
        select * from demo_user where id = #{id}
    </select>

    <insert id="insertOne">
        insert into demo_user (id, name, json) values (#{id}, #{name}, #{json})
    </insert>
</mapper>

建立 main 方法測試

try(InputStream in = Resources.getResourceAsStream("com/myboy/demo/sqlsession/mybatis-config.xml")){
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
    sqlSession = sqlSessionFactory.openSession();
    # 拿到代理類物件
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    # 執行方法
    UserEntity userEntity = mapper.getById(2L);
    System.out.println(userEntity);
    sqlSession.close();
}catch (Exception e){
    e.printStackTrace();
}

2、動態代理類的生成


IT145.com E-mail:sddin#qq.com