概述
建表
创建spring boot工程
创建susert实体类
编写mapper接口
编写mapper配置文件
编写Service接口以及实现类
编写Controller测试
在application.properties配置数据库等信息
运行测试
概述
我们开发项目时经常用到spring boot框架,而spring boot框架经常与第三方框架整合。因此学习如何整合第三方框架变得很重要。本篇介绍spring boot如何整合mybatis。接下来我们就一起来看吧!
建表
创建springboot工程
使用idea创建spring boot工程并加入相关依赖
org.springframework.boot spring-boot-starter-weborg.mybatis.spring.boot mybatis-spring-boot-starter2.2.2 mysql mysql-connector-javaruntime org.springframework.boot spring-boot-starter-testtest
创建user实体类
package com.yss.entity;
public class User {
private Integer id;
private String name;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + ''' +
", age=" + age +
'}';
}
}
编写mapper接口
package com.yss.mapper;
import com.yss.entity.User;
import org.springframework.stereotype.Repository;
@Repository
public interface UserMapper {
//添加一个根据id查询对象的方法
User selectUserById(Integer id);
}
编写mapper配置文件
mapper文件的位置
- 编写service接口及其实现类
package com.yss.service;
import com.yss.entity.User;
public interface UserService {
User queryUserById(Integer id);
}
package com.yss.service;
import com.yss.entity.User;
import com.yss.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserMapper userMapper;
@Override
public User queryUserById(Integer id) {
return userMapper.selectUserById(id);
}
}
编写controller测试
package com.yss.controller;
import com.yss.entity.User;
import com.yss.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/getUser")
public String getUser(Integer id){
User user = userService.queryUserById(id);
return user.toString();
}
}
在application.yaml文件配置数据库信息
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
url: jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
mybatis:
#指定映射文件的路径
mapper-locations: classpath:mapping/*.xml
type-aliases-package: com.yss.entity
#添加日志输出
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
运行测试
如果要看日志输出的话,就配置日志信息,如下图所示。



