SpringBoot整合Mybatis
1、添加依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
2、创建实体类
//使用了lombok,依赖自己添加
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
private String name;
private String passwd;
}
3、创建mapper
@Mapper //在接口类上添加了@Mapper,在编译之后会生成相应的接口实现类
@Repository
public interface UserMapper {
//查询所有的用户信息
List<User> queryUserList();
//根据用户id查询用户
User queryUserById(int id);
}
4、MyBatis相关配置
mybatis:
type-aliases-package: com.comple.mybatis.bean # 注意:对应实体类的路径
mapper-locations: classpath:mapper/*.xml #注意:一定要对应mapper映射xml文件的所在路径
5、编写接口对应的xml文件
<!--接口对应的xml文件放在resources目录下-->
<?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.comple.mybatis.mapper.UserMapper">
<select id="queryUserList" resultType="com.comple.mybatis.bean.User">
select * from user
</select>
<select id="queryUserById" resultType="com.comple.mybatis.bean.User">
select * from user where id = #{id}
</select>
</mapper>
6、控制器
略
来源:oschina
链接:https://my.oschina.net/duanqwei/blog/3164271