SpringBoot整合MyBatis
Posted dxj1016
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot整合MyBatis相关的知识,希望对你有一定的参考价值。
整合步骤:
- 新建springboot项目springboot-mybatis-study,选择模块
- 导入 MyBatis 所需要的依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
- 配置数据库连接信息
spring:
datasource:
username: root
password: root
#?serverTimezone=UTC解决时区的报错
url: jdbc:mysql://localhost:3306/test1?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.jdbc.Driver
- 测试数据库是否连接成功!
package com.spring;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.sql.DataSource;
import java.sql.SQLException;
@SpringBootTest
class SpringbootMybatisStudyApplicationTests {
@Autowired
DataSource dataSource;
@Test
void contextLoads() throws SQLException {
System.out.println(dataSource.getClass());
System.out.println(dataSource.getConnection());
}
}
- 启动项目如果报如下错误,那么看看你一开始创建项目的时候是用的阿里云还是spring官网,我这里用到阿里云,所以创建项目的时候就给properties配置文件配置好了数据库,所以再自己写个yml配置数据库的时候,如果没有指定使用哪个,那么默认是使用properties中的,因为properties中的是阿里云自动创建的,用户名和密码没有对应上我们本地的,所以连接失败了
- 没有报错
- 导入lombok,如果之前没有下lombok要先在idea中下载lombok插件然后再导入lombok依赖
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
- 创建数据库表user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`password` varchar(8) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 10 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = 'password' ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of a
-- ----------------------------
INSERT INTO `user` VALUES (4, '1016', '1016');
INSERT INTO `user` VALUES (5, '1', NULL);
INSERT INTO `user` VALUES (6, '2', NULL);
INSERT INTO `user` VALUES (7, 'dxj1016', 'dxj1016');
INSERT INTO `user` VALUES (8, 'dxj1016', 'dxj1016');
INSERT INTO `user` VALUES (9, 'dxj1016', 'dxj1016');
- 创建实体类User.java
package com.spring.pojo;
import lombok.Data;
@Data
@AllArgsConstructor
public class User {
private Integer id;
private String name;
private String password;
public User(String name, String password) {
this.name = name;
this.password = password;
}
}
- 创建mapper目录以及对应的 Mapper 接口UserMapper.java
package com.spring.mapper;
import com.spring.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
//@Mapper : 表示本类是一个 MyBatis 的 Mapper
@Mapper
@Repository
public interface UserMapper {
// 获取所有部门信息
List<User> queryUserList();
// 通过id获得部门
User queryUserById(Integer id);
// 添加用户
int addUser(User user);
// 修改用户
int updateUser(User user);
// 删除用户
int deleteUser(int id);
}
- 在resources文件夹下建mybatis文件夹,再在mybatis文件夹下建mapper文件夹,在里面建对应的Mapper映射文件UserMapper.xml
<?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.spring.mapper.UserMapper">
<select id="queryUserList" resultType="User">
select * from user;
</select>
<select id="queryUserById" resultType="User" parameterType="int">
select * from user where id = #{id};
</select>
<insert id="addUser" parameterType="User">
insert into user (name,password) values (#{name},#{password});
</insert>
<update id="updateUser" parameterType="User">
update user set name=#{name},password=#{password} where id=#{id};
</update>
<delete id="deleteUser" parameterType="int">
delete from user where id=#{id};
</delete>
</mapper>
- 配置文件yml中整合mybatis
# 整合mybatis
mybatis:
type-aliases-package: com.spring.pojo
# 这个路径是映射文件的路径,对应自己路径下的映射文件,否则测试找不到这个映射文件。
mapper-locations: classpath:mybatis/mapper/*.xml
- 编写controller层测试
package com.spring.controller;
import com.spring.mapper.UserMapper;
import com.spring.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class UserController {
@Autowired
UserMapper userMapper;
// 查询全部部门
@GetMapping("/queryUserList")
public List<User> queryUserList() {
return userMapper.queryUserList();
}
// 根据id查询用户
@GetMapping("/queryUserById/{id}")
public User queryUserById(@PathVariable("id") Integer id) {
return userMapper.queryUserById(id);
}
// 添加用户
@GetMapping("/addUser")
public String addUser() {
userMapper.addUser(new User("阿毛", "34334"));
return "add OK";
}
// 修改用户
@GetMapping("/updateUser")
public String updateUser() {
userMapper.updateUser(new User(6, "小红", "490333"));
return "udpate OK";
}
// 删除用户
@GetMapping("/deleteUser")
public String deleteUser() {
userMapper.deleteUser(5);
return "delete OK";
}
}
总结整合mybatis过程:
- 导入依赖
- 配置文件
- mybatis配置
- 编写sql
- 业务层(service)调用dao层
- controller层调用service层
注意:上面步骤中省略了service层
以上是关于SpringBoot整合MyBatis的主要内容,如果未能解决你的问题,请参考以下文章