精通 Spring Boot 系列文(11)
阅读全文,约 14 分钟
Spring Boot 整合 MyBatis
MyBatis 是目前优秀的 ORM 框架,支持普通的数据库操作,几乎消除了常规的 JDBC 操作,极大简化我们的开发操作。
1)编辑 pom.xml 文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.nxgroupId>
<artifactId>springbootdataartifactId>
<version>1.0-SNAPSHOTversion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.2.6.RELEASEversion>
<relativePath/>
parent>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
<java.version>1.8java.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-thymeleafartifactId>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
dependency>
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>1.3.1version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<scope>testscope>
dependency>
dependencies>
project>
2)编辑 application.properties 文件
####################
### 数据源信息配置 ###
####################
# 数据库地址
spring.datasource.url=jdbc:mysql://localhost:3306/springbootdata?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true
# 用户名
spring.datasource.username=root
# 密码
spring.datasource.password=1234
# 数据库驱动
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
# 指定连接池中最大的活跃连接数.
spring.datasource.max-active=20
# 指定连接池最大的空闲连接数量.
spring.datasource.max-idle=8
# 指定必须保持连接的最小值
spring.datasource.min-idle=8
# 指定启动连接池时,初始建立的连接数量
spring.datasource.initial-size=10
3)创建 User 持久化类
public class User implements Serializable{
private static final long serialVersionUID = 1L;
private int id ;
private String loginName ;
private String username ;
private String password;
// setXxx 和 getXxx 方法
}
4)创建 UserRepository 数据访问接口
public interface UserRepository {
@Insert("insert into tb_user(login_name ,username ,password) "
+ "values (#{loginName},#{username},#{password})")
public int insertUser(User user);
// 插入数据获取主键
@Insert("insert into tb_user(login_name ,username ,password) "
+ "values (#{loginName},#{username},#{password})")
@Options(useGeneratedKeys=true,keyProperty="id",keyColumn="id")
public void insertGetKey(User user);
@Select("select * from tb_user where username = #{username}")
// 引用id="userResult"的@Results
@ResultMap("userResult")
public User selectByUsername(@Param("username")String username);
@Select("select * from tb_user")
// @Results用于映射对象属性和数据库列,常用于对象属性和数据库列不同名情况
@Results(id="userResult",value={
@Result(id=true,column="id",property="id"),
@Result(column="login_name",property="loginName"),
@Result(column="password",property="password"),
@Result(column="username",property="username")
})
public List findAll() ;
@Delete("delete from tb_user where id=#{id}")
public void delete(final Integer id);
@Select("select * from tb_user where id=#{id}")
// 引用id="userResult"的@Results
@ResultMap("userResult")
public User findUserById(int id);
@Update("update tb_user set username=#{username}, login_name=#{loginName} where id=#{id}")
public void update(final User user);
}
5)创建 UserService 业务层类
@Service
public class UserService {
// 注入UserRepository
@Resource
private UserRepository userRepository;
public int insertUser(User user){
return userRepository.insertUser(user);
}
public User selectByUsername(String username){
return userRepository.selectByUsername(username);
}
public List findAll() {
return userRepository.findAll();
}
public void insertGetKey(User user) {
userRepository.insertGetKey(user);
}
public void update(User user) {
userRepository.update(user);
}
public void delete(Integer id) {
userRepository.delete(id);
}
}
6)创建 UserController 控制器类
@RestController
@RequestMapping("/user")
public class UserController {
// 注入UserService
@Resource
private UserService userService;
@RequestMapping("/insertUser")
public String insertUser(User user){
return "插入数据["+userService.insertUser(user)+"]条";
}
@RequestMapping("/insertGetKey")
public User insertGetKey(User user) {
userService.insertGetKey(user);
return user ;
}
@RequestMapping("/selectByUsername")
public User selectByUsername(String username){
return userService.selectByUsername(username);
}
@RequestMapping("/findAll")
public List findAll() {
return userService.findAll();
}
@RequestMapping("/update")
public void update(User user) {
userService.update(user);
}
@RequestMapping("/delete")
public void delete(Integer id) {
userService.delete(id);
}
}
7)测试
http://localhost:8080/user/insertUser?loginName=shuaishuai&username=小猿&password=123123
未完待续,等我下一篇 ~~~Java后端编程
更多Java推文,关注公众号
评论