依赖原理
pom只引入mysql
再引入org.mybatis.springboot包
MybatisAutoConfiguration.java
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.41</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<!-- lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
Springboot使用注解版mybatis
As any other Spring Boot application a MyBatis-Spring-Boot-Application configuration parameters are stored inside the application.properties
(or application.yml
).
MyBatis uses the prefix mybatis for its properties.
使用MapperScan批量扫描所有的mapper接口
在每个mapper加上注解,或者在@SpringBootApplication或者@Configuration上添加注解
@MapperScan(value = "com.kcl.mapper")
spring:
datasource:
url: jdbc:mysql://rm-bp18jitlw9a952i5x3o.mysql.rds.aliyuncs.com:3306/mybatis02?userSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
driver-class-name: com.mysql.jdbc.Driver
username: root
password: 123456
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
private String username;
private String sex;
private String birthday;
private String address;
}
//指定这是一个操作数据库的mapper
@Mapper
public interface UserMapper {
@Select("select * from user")
List<User> getUsers();
@Select("select * from user where id = #{id}")
User getById(Integer id);
@Insert("insert into user(username,sex,birthday,address) values(#{username},#{sex},#{birthday},#{address})")
void addUser(User user);
@Delete("delete from user where username = #{username}")
void deleteByUserName(String username);
@Update("update user set username = #{username},sex = #{sex},address=#{address},birthday=#{birthday} where id = #{id}")
void updateUser(User user);
}
@Controller
public class UserController {
@Autowired
UserMapper mUserMapper;
@GetMapping("/users")
@ResponseBody
public List<User> getUsers(){
return mUserMapper.getUsers();
}
@GetMapping("/user/{id}")
@ResponseBody
public User getUser(@PathVariable("id")Integer id){
return mUserMapper.getById(id);
}
@GetMapping("/addUser")
@ResponseBody
public User addUser(User user){
mUserMapper.addUser(user);
return user;
}
@GetMapping("/delete/user/{username}")
public void deleteUser(@PathVariable("username")String username){
mUserMapper.deleteByUserName(username);
}
@GetMapping("/update/user")
public void updateUser(User user){
mUserMapper.updateUser(user);
}
}
配置文件的方式 application.yml和mybatisConfig
配置数据源必须在application.yml文件中配置!!
注解的方式和在mapper.xml文件中实现,二者可以同时存在,然而在单独的mybatis项目中只能存在一个
配置方式总结
- 数据源的配置一定写在application.yml中
- 可以在yml中配置,也可以在mybatis-config.xml中配置
- mapper的指定位置可以在yml中指定,也可以在xml中指定,二者不冲突
- 如果指定了
config-location
属性,那么yml中的configruation
就会发生冲突