官方参考文档:http://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/
当前版本说明:SpringBoot : 2.6.2
导入依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
使用方法一
通过 @Mapper 注解标注使用的文件,通过 @Select、@Update、@Delete、@Insert等注解实现简单的语法操作,举个例子:
Mapper 文件:
@Mapper
public interface UserMapper {
@Select("select * from `user` where username=#{username} and password = #{password}")
User getUserByUsernamePassword(String username, String password);
}
调用方式
@Service
public class UserServiceImpl {
@Resource
private UserMapper userMapper;
@Override
public User getUserByUsernamePassword(String username, String password) {
return userMapper.getUserByUsernamePassword(username, password);
}
}
使用方法二
通过@MapperScan配置扫描的文件夹,通过xml文件来处理复杂的SQL
在启动文件中配置@MapperScan
@MapperScan("com.yituomao.blog.back.mapper")
@SpringBootApplication
Mapper文件
public interface UserMapper {
void updateUser(User user);
}
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.yituomao.blog.back.mapper.UserMapper">
<update id="updateUser" parameterType="com.yituomao.blog.back.pojo.User">
update `user`
set username = #{username}, password = #{password}, email = #{email}
where id = #{id}
</update>
</mapper>
调用方式与“方法一”一致