Spring Boot - XML配置的方式整合MyBatis

上篇Spring Boot - 注解的方式整合MyBatis中,我们知道怎么利用注解的方式整合MyBatis,可以说是很方便了。当然对应一个微服务来说,因为功能性单一,需要编写的SQL数量不会很多,各个SQL的复杂度相对也不会很大。

但如果是用于企业应用上,项目一般都会比较庞大,SQL的量会比较多,对应的一个SQL也可能会比较复杂。这个时候如果我们还是用注解的方式,会使得程序的可度性变差。这样交接或者新同事接手的话,一定程度的会影响效率。因此,XML配置的方式也是有存在的必要的。

学习这篇教程最好先学习下上篇教程,这样才好连贯起来。

MyBatis配置

相比注解(annotation)的方式,需要修改application.properties文件MyBatis的配置如下:

# MyBatis配置
## MyBatis配置文件路径
mybatis.config-location=classpath:mybatis/mybatis-config.xml
## MyBatis的mapper xml文件路径
mybatis.mapper-locations=classpath:mybatis/mapper/*-mapper.xml

mybatis-config.xml配置

如上面配置的,在项目的resource包下面创建mybatis包,创建mybatis-config.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <!--下划线风格自动转驼峰风格-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

    <typeAliases>
        <!--设置别名-->
        <package name="com.roachfu.tutorial.entity"/>
    </typeAliases>
</configuration>

demo-mapper.xml配置

根据application.properties
配置需要在mybatis下面新建mapper包,并在包下面创建demo-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.roachfu.tutorial.mapper.DemoMapper">
    <select id="selectList" resultType="Demo">
        select id, demo_name, demo_value, demo_status, create_time, update_time from t_demo
    </select>

    <select id="selectOne" resultType="Demo">
        select id, demo_name, demo_value, demo_status, create_time, update_time from t_demo where id = #{id}
    </select>

    <insert id="insert" parameterType="Demo">
        insert into t_demo(id, demo_name, demo_value) values (#{id}, #{demoName}, #{demoValue})
    </insert>

    <update id="update" parameterType="Demo">
        update t_demo set demo_name = #{demoName}, demo_value=#{demoValue}, update_time=#{updateTime} where id = #{id}
    </update>

    <delete id="delete" parameterType="int">
        delete from t_demo where id = #{id}
    </delete>
</mapper>

DemoMapper

注解(annotation)的方式在Mapper的方法之上写SQL语句,现在 SQL已经放到了XML里,那么就只剩接口了,当然不要忘了在接口之上的注解。

@Mapper
public interface DemoMapper {
    
    List<Demo> selectList();
    
    Demo selectOne(@Param("id") Integer id);
    
    int insert(Demo demo);
    
    int update(Demo demo);
    
    int delete(@Param("id") Integer id);
}

测试

测试和注解方式的测试是一样的,具体请看源码。

项目源码

参考

springboot(六):如何优雅的使用mybatis

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容