Mybatis
1 创建项目记得勾选web 、JDBC API、MySQL Driver
2 整合包
导入依赖
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
3yaml(推荐)或者properties配置文件
yaml
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
type-aliases-package: com.xxr.pojo
mapper-locations: classpath:com/xxr/mapper/*.xml
properties
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring.datasource.diver-class-name= com.mysql.cj.jdbc.Driver
4创建实体类(记得引入lombok依赖)
根据数据库创建对应的实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
}
5写mapper接口
注意加上注解@mapper相当于表示了这是一个mybatis的mapper类
@Mapper
@Repository
public interface UserMapper {
@Select("select * from user")
List<User> selectUser();
}
6写对应接口的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.xxr.mapper.UserMapper">
<select id="selectUser" resultType="User">
select *from user
</select>
</mapper>
在properties和yaml文件加入扫描包和配置文件
yaml
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
type-aliases-package: com.xxr.pojo
mapper-locations: classpath:mybatis/mapper/*.xml
properties
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring.datasource.diver-class-name= com.mysql.cj.jdbc.Driver
mybatis.type-aliases-package= com.xxr.pojo
mybatis. mapper-locations= classpath:mybatis/mapper/*.xml
测试一下
@RestController
public class test01 {
@Autowired
private UserMapper userMapper;
@RequestMapping("/list")
public List<User> test() {
List<User> users = userMapper.selectUser();
return users;
}
}
直接用controller层调一下测试真正的业务代码不会这样的要写service层
通过测试发现不用增加事务,会自己开启。
总结一下就简单几步
1 导入依赖
2 配置文件
3 mybatis配置
4 编写sql
5 service层调用dao层
6 controller调用service层