在SpringBoot中访问数据库有多种方式,一般我们可以使用jdbctemplate、Mybatis、JPA。本文总结使用Mybatis的方式
准备工作
建立数据库
建立表users
CREATE TABLE `users` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`user_name` varchar(45) NOT NULL DEFAULT '',
`password` varchar(45) NOT NULL DEFAULT '',
`role` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=74 DEFAULT CHARSET=utf8;
建立Package
我们建立一个mybatis包用于存放和mybatis相关的内容
下面再建立两个包,一个是entity存放实体类,另一个是mapper,存放操作的接口
建立实体类
在entity下建立UserEntity实体类
import java.io.Serializable;
public class UserEntity implements Serializable {
private static final long serialVersionUID = -1L;
private int userid;
private String userName;
private String password;
private int role;
public void setUserid(int userid) {
this.userid = userid;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setPassword(String password) {
this.password = password;
}
public void setRole(int role) {
this.role = role;
}
public int getUserid() {
return userid;
}
public String getUserName() {
return userName;
}
public String getPassword() {
return password;
}
public int getRole() {
return role;
}
}
建立测试接口
同其它测试一样,我们为Mybatis的测试建立一个测试接口MybatisController
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/mybatis")
public class MybatisController {
@Autowired
private UserService userService;
@GetMapping("")
public String index()
{
return "";
}
}
目前接口内处理函数是空的,随着下面的实验,逐渐会填写实验代码
建立其它类
还需要建立Service类和Service的接口类
public interface UserService {
}
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserMapper userMapper;
}
加入依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
写配置
在application.properties中添加如下配置
#数据库相关配置
spring.datasource.url=jdbc:mysql://localhost:3306/world?autoReconnect=true&failOverReadOnly=false&useSSL=false
spring.datasource.username=root
spring.datasource.password=Pass@word1
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
加入扫描
Mybatis的操作是依靠写在mapper包中的各个mapper实现的,我们需要要springboot加载这些mapper,加载这些mapper有两种方式
1、在每个mapper类上面加上注解@Mapper
2、在启动类上加上注解@MapperScan(“com.gl.springbootapi.mybatis.mapper”)
我们这里采用第二种方式
实现操作
在mapper包下建立User的接口UserMapper
public interface UserMapper {
}
Insert
实现一个操作需要修改四个文件分别添加的内容如下
1、UserMapper接口添加的内容
@Insert("INSERT INTO users(user_name,password,role) VALUES(#{userName}, #{password}, #{role})")
int insert(UserEntity userEntity);
2、UserService接口添加的内容
int insert(UserEntity userEntity);
3、UserServiceImpl类添加的内容
@Override
public int insert(UserEntity userEntity) {
return userMapper.insert(userEntity);
}
4、MybatisController类添加的内容
@GetMapping("/insert")
public String insert()
{
UserEntity userEntity = new UserEntity();
userEntity.setPassword("password");
userEntity.setRole(1);
userEntity.setUserName("name");
int result= userService.insert(userEntity);
return String.valueOf(result);
}
5、结果
通过测试可以看出返回了1,这个是影响的行数,另外到数据库中也可以看出来新插入了一条数据
每个操作都需要修改这几个文件,但是核心修改内容在UserMapper中,为了简单起见下面的内容只贴出UserMapper的实现
Delete
@Delete("DELETE FROM users WHERE user_id =#{userid}")
int delete(int userid);
Update
@Update("UPDATE users SET user_name=#{userName},password=#{password},role=#{role} WHERE user_id =#{userid}")
int update(UserEntity userEntity);
Select One
@Select("SELECT * FROM users WHERE user_id = #{userid}")
@Results({
@Result(property = "userid", column = "user_id"),
@Result(property = "userName", column = "user_name"),
})
UserEntity getOne(int userid);
@Result指定实体类字段与数据库字段不一致的映射,如果一致则不用写
Select List
@Select("SELECT * FROM users")
@Results({
@Result(property = "userid", column = "user_id"),
@Result(property = "userName", column = "user_name"),
})
List<UserEntity> getAll();
Insert获取自增ID
@Insert("INSERT INTO users(user_name,password,role) VALUES(#{userName}, #{password}, #{role})")
@Options(useGeneratedKeys = true, keyProperty = "userid", keyColumn = "user_id")
int insertAuto(UserEntity userEntity);
标记了@Options后,自增的user_id会被赋值到userid字段,执行完成之后可以在属性中取出来,返回值仍然是影响的行数
事务
1、将UserMapper接口添加注解@Transactional
@Transactional
public interface UserMapper {
......
}
2、在UserService层中调用UserMapper方法,然后触发回滚,在数据库中检查数据是否回滚
@Transactional(rollbackFor = {IllegalArgumentException.class})
@Override
public void testTransactional() {
UserEntity userEntity = new UserEntity();
userEntity.setPassword("password");
userEntity.setRole(1);
userEntity.setUserName("name");
int result= userMapper.insert(userEntity);
throw new IllegalArgumentException("数据将回滚");
}
PageHelper分页插件
//TODO