学习Mybatis(4):结合Spring Boot

1.创建一个Spring Boot项目(略)

2.添加相关依赖:

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.38</version>
</dependency>

3.添加application.properties的配置(数据源配置、mapper位置等)

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
mybatis.mapper-locations=classpath:xml/*.xml

4.编写Service、Mapper、POJO

POJO和之前的一样

和独立使用Mybatis时不同,这里需要增加Service层来调用Mapper层的方法:

UserService:内容和UserMapper一样,这里增加了一个addUser方法

public interface UserService {
    User getUser(int id);
    void addUser(User user);
}

UserServiceImpl:UserService的实现类(可不写@Transactional)

@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    public UserMapper userMapper;

    public User getUser(int id){
        return userMapper.getUser(id);
    }

    public void addUser(User user){
        userMapper.addUser(user);
    }
}

此处可能会报 Could not autowire. No beans of 'UserMapper' type found. 不用管它,没有影响

5.在Controller调用:

@RestController
public class TestController {
    @Autowired
    UserServiceImpl mapper;

    @PostMapping("/addUser/{userName}/{age}")
    public String add(@PathVariable String userName, @PathVariable int age){
        mapper.addUser(new User(userName,age));
        return "success";
    }

    @GetMapping("/getUser/{id}")
    public String get(@PathVariable int id){
        return mapper.getUser(id).toString();
    }
}

6.测试:(端口配置为2222)

GET localhost:2222/getUser/1

User{id=1, userName='zhangsan', age=1}

POST localhost:2222/addUser/lisi/2

查看数据库,数据已经插入

猜你喜欢

转载自blog.csdn.net/u010670411/article/details/84572646