(1)、添加依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
(2)、编写Mapper接口类
package cn.coreqi.mapper; import cn.coreqi.entities.User;
import org.apache.ibatis.annotations.Mapper; @Mapper
public interface UserMapper { public User getUserById(Integer id); public int addUser(User user); public int modifyUser(User user); public int delUserById(Integer id);
}
(3)、编写Mybatis配置文件
<?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>
</configuration>
(4)、编写Mapper接口对应的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="cn.coreqi.mapper.UserMapper">
<select id="getUserById" resultType="cn.coreqi.entities.User">
select * from users where Id = #{id}
</select> <insert id="addUser" useGeneratedKeys="true" keyProperty="Id">
insert into users(UserName,PassWord,Enabled) values(#{UserName},#{PassWord},#{Enabled})
</insert> <update id="modifyUser">
update users set UserName = #{UserName},PassWord = #{PassWord},Enabled = #{Enabled} where Id = #{Id}
</update> <delete id="delUserById">
delete from users where Id = #{id}
</delete>
</mapper>
(5)、在配置文件中配置mybatis
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/JdbcDemo?serverTimezone=UTC
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource mybatis.config-location=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml