亲宝软件园·资讯

展开

Mybatis如何通过接口实现sql执行原理解析

myboy 人气:0

使用过 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、动态代理类的生成

加载全部内容

相关教程
猜你喜欢
用户评论