【干货】Spring Boot 整合 Mybatis
通过在前面的文章中我们已经了解到如何快速构建一个基于 Spring Boot 架构的 Web 服务以及接口开发:
今天这篇文章我们将继续 Spring Boot 开发学习——如何整合 Mybatis。
添加依赖:
<!--mybatis起步依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<!-- MySQL连接驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
数据库配置:
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) DEFAULT NULL,
`password` varchar(50) DEFAULT NULL,
`name` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`) )
ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
INSERT INTO `user` VALUES ('1', 'zhangsan', '123', '张三');
INSERT INTO `user` VALUES ('2', 'lisi', '123', '李四');
创建实体 Bean:
public class User {
private Long id;
private String username;
private String password;
private String name;
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;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", name='" + name + '\'' +
'}';
}
}
编写 Mapper:
@Mapper
public interface UserMapper {
}
配置 Mapper 映射文件:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.testops.mapper.UserMapper">
</mapper>
添加mybatis信息:
在application.properties中添加mybatis的信息
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/testops?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=''
mybatis.type-aliases-package=com.testops.domain
mybatis.mapper-locations=classpath:mapper/*.xml
编写 Mapper 信息:
<select id="queryUserList" resultType="User">
select * from user;
</select>
编写测试Controller:
@Controller
public class GetUserListController {
@Autowired
private UserMapper userMapper;
@RequestMapping(value = "/query",method = RequestMethod.GET)
@ResponseBody
public List<User> queryUserList(){
List<User> users = userMapper.queryUserList();
return users;
}
}
测试:
访问:http://ip:port/query
|
时间 |
课题 |
周一 |
21:00 腾讯课堂 |
《敏捷测试从零开始》 |
周二 |
20:00 腾讯课堂 |
《测试开发从零开始》python篇 |
周六 |
20:00 腾讯课堂 |
《测试开发从零开始》 java篇 |
微信号 : TestOps
知乎:@TestOps云层
赞 (0)