1.通用mapper的坐标:
<!-- 通用mapper -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.1.5</version>
</dependency>
注意::一旦引入了通用Mapper的启动器,会覆盖Mybatis官方启动器的功能,因此需要移除对官方Mybatis启动器 的依赖。
2.修改mapper
使用通用mapper必须继承Mapper
import com.sx.pojo.User;
import tk.mybatis.mapper.common.Mapper;
public interface UserMapper extends Mapper<User> {
}
3.修改启动类上注解的包
4.在实体类中添加jpa注解
@Data
@Table(name = "tb_user")
public class User {
@Id
//主键回填
@KeySql(useGeneratedKeys = true)
private Long id;
private String userName;
private String password;
private String name;
private Integer age;
private Integer sex;
private Date birthday;
private String note;
private Date created;
private Date updated;
}
5.编写UserService
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User queryUserById(Long id) {
return userMapper.selectByPrimaryKey(id);
}
@Transactional
public void SaveUser(User user) {
//选择性新增
userMapper.insertSelective(user);
}
}
6.编写UserControlller
@RestController
public class UserController {
@Autowired
private UserService userService;
/**
* 根据用户id查询用户
*
* @param id userId
* @return User
*/
@GetMapping("/user/{id}")
public User queryUserById(@PathVariable Long id) {
return userService.queryUserById(id);
}
}