1.导入依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
2.配置数据信息
spring:
datasource:
url: jdbc:mysql://localhost:3306/mybatis
password: 2811085093
username: root
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
type-aliases-package: com.hui.springbootmybatis.pojo
mapper-locations: classpath:mybatis/mapper/*.xml
3.编写测试
package com.hui.springbootmybatis.mapper;
import com.hui.springbootmybatis.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
@Mapper
@Repository
public interface UserMapper {
int add(User user);
}
映射文件
<?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.hui.springbootmybatis.mapper.UserMapper">
<insert id="add" parameterType="User">
insert into user(id ,name, pwd) values(#{id},#{name},#{pwd})
</insert>
</mapper>
访问:
@RestController
public class UserController {
@Autowired
UserMapper userMapper;
@RequestMapping("/adduser")
public User add(){
User user = new User(122,"xiaohui","we");
userMapper.add(user);
return user;
}
}
重点是mapper文件和sql映射文件分离了
需要我们手动的指定
mybatis:
type-aliases-package: com.hui.springbootmybatis.pojo
mapper-locations: classpath:mybatis/mapper/*.xml