序言
在我们很熟知的SSM框架中,MyBatis的配置相当繁琐,相比较而言使用SpringBoot极其简洁。SSM框架中有Sring-mybatis配置,又有mybatis-config配置,并且要写很多配置文件。既然SpringBoot简单易用,它如何配置整合MyBatis呢。
MyBatis-Spring-Boot-Starter
MyBatis-Spring-Boot-Starter类似一个中间件,链接Spring Boot和MyBatis,构建基于Spring Boot的MyBatis应用程序。
MyBatis-Spring-Boot-Starter 当前版本是 2.1.2,发布于2020年3月10日
MyBatis-Spring-Boot-Starter是个集成包,因此对MyBatis、MyBatis-Spring和SpringBoot的jar包都存在依赖,如下所示:
MyBatis-Spring-Boot-Starter | MyBatis-Spring | Spring Boot | Java |
---|---|---|---|
2.1 | 2.0 (need 2.0.2+ for enable all features) | 2.1 or higher | 8 or higher |
1.3 | 1.3 | 1.5 | 6 or higher |
步骤一:添加相关 Maven 文件
<!--引入整合MyBatis的核心依赖mybatis-spring-boot-starter-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
步骤二:application.properties
添加相关配置
#数据库连接池
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
propertiesspring.thymeleaf.cache=false
#mybatis
mybatis.typeAliasesPackage=com.inchlifc.infoworkshop.entity
mybatis.mapperLocations=classpath:mybatis/mapper/*.xml
步骤三:编写Mapper文件
<?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.inchlifc.infoworkshop.mapper.UserMapper" >
<resultMap id="BaseResultMap" type="com.inchlifc.infoworkshop.entity.User" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result column="age" property="age" jdbcType="INTEGER" />
</resultMap>
<select id="getUserList" resultMap="BaseResultMap" >
SELECT * FROM USER WHERE NAME LIKE concat(concat('%',#{0}),'%')
limit #{1},#{2}
</select>
<select id="getUserCount" resultType="java.lang.Integer">
select count(id) count from user
</select>
<select id="getUserById" parameterType="java.lang.Integer" resultMap="BaseResultMap" >
SELECT * FROM user WHERE id = #{id}
</select>
<insert id="add" parameterType="com.inchlifc.infoworkshop.entity.User" >
INSERT INTO user
(name,age) VALUES (#{name}, #{age})
</insert>
<update id="update" parameterType="com.inchlifc.infoworkshop.entity.User" >
UPDATE user SET name = #{name},age = #{age}
WHERE id = #{id}
</update>
<delete id="delete" parameterType="java.lang.Integer" >
DELETE FROM user WHERE id = #{id}
</delete>
</mapper>