MyBatis+SpringMVC+SpringBootspringbootSpringBoot极简教程 · Spring Boot

spring-boot系列之整合Mybatis

2019-04-27  本文已影响2人  Zftttttt

开发环境

开发工具

相关依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.2.0</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.37</version>
</dependency>

数据源配置

application.properties中进行如下配置

spring.datasource.url=jdbc:mysql://localhost:3306/blog?useUnicode=true&useSSL=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

实体类

public class User {

    private Long id;

    private String username;

    private String password;

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public User(Long id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

Mapper接口

@Repository
@Mapper
public interface UserMapper {

    @Select("select id,username,password from user where username = #{username}")
    User getUser(@Param("username") String username);
}

单元测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void testGetUser() {

        User user = userMapper.getUser("root");
        //之前数据库中已有一条数据,username="root",password="root"
        Assert.assertEquals("root", user.getUsername());
        Assert.assertEquals("root", user.getPassword());
    }
}
上一篇下一篇

猜你喜欢

热点阅读