1.导入包
导入依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
2.配置文件
注意:编写mapper接口的时候添加@mapper注解。
在resource目录下创建mapper映射文件,userMapper.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.liuqing.springbootmybaties.mapper.UserMapper">
</mapper>
3.配置mybatis
application.xml文件中
spring:
datasource:
username: root
password: liuqing.1998
url: jdbc:mysql://localhost:3306/jdbc?serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
type-aliases-package: com.liuqing.springbootmybaties.pojo
mapper-locations: classpath:mybatis/mapper/*.xml
4.编写sql
<?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.liuqing.springbootmybaties.mapper.UserMapper">
<select id="queryList" resultType="User">
SELECT * FROM USER
</select>
<select id="queryUserById" resultType="User">
SELECT * FROM USER WHERE id =#{id}
</select>
<insert id="addUser" parameterType="User">
insert into USER (id,name,pwd) values (#{id},#{name},#{pwd});
</insert>
<delete id="deleteUser" parameterType="int">
DELETE FROM USER WHERE id =#{id}
</delete>
</mapper>
5.调用mapper方法
@Autowired
private UserMapper userMapper;
@GetMapping("/queryList")
public List<User> queryList(){
List<User> users = userMapper.queryList();
for (User user :
users) {
System.out.println(user);
}
return users;
}