开发环境
- JDK1.8
- spring-boot 2.1.4.RELEASE
- Apache Maven 3.6.0
- MySQL 5.0.22
开发工具
- IDEA
相关依赖
<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());
}
}
网友评论