Home >Java >javaTutorial >How SpringBoot integrates Mybatis to implement addition, deletion, modification and query
First we should create a database to operate our CRUD data (you can use visual tools to create it, or you can use SQL commands to create it), the name of the database You can define it yourself. After creating the database, we have to create a table to store the data. The name of the table is the 'user' table. The fields can be set by ourselves, as long as they correspond to the entities we create later.
CREATE TABLE `user` ( `userId` bigint NOT NULL AUTO_INCREMENT, `userName` varchar(255) COLLATE utf8mb4_bin NOT NULL, `userAddress` varchar(255) COLLATE utf8mb4_bin NOT NULL, PRIMARY KEY (`userId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
Create a SpringBoot project using IDEA:
1. Select Spring Initializr to create, and then select JDK 1.8, Java8 version.
2. Select Spring Web, JDBC API, Mybatis Framework, MySQL Driver, and Lombok for initialization components, which may be used.
3. After selecting, click Finish to create.
4. After creating SpringBoot, check whether your Maven is configured properly. If not, check how to configure Maven. Otherwise, your pom dependencies will not be loaded. Just download Maven, how to change the Alibaba source image address and local warehouse, and then select Maven's xml file and local warehouse address in IDEA.
Above are If you forget to introduce the required dependency packages, you can add them directly without re-creating the project.
First you need to Create four folders, namely: Entity (user entity), Controller, Service, Dao, and then you need to create a new Mapper directory under the resource directory. This Mapper directory is used to store SQL statements. At this point, I think we need to understand the MVC model. Since our access is called one layer at a time, and then returns to the past after querying the data, our level should be: Controller (the control layer, which is also the layer that receives the parameters passed by the front end) -> Service (business layer, all our business, such as judgments and some loop statements need to be written in this layer) -> Dao (persistence layer, this layer mainly deals with the database, and is mainly responsible for data operations. That is, CRUD operation) -> Database,
is as shown in the figure below:
There is no good drawing tool, just I just drew it casually. Anyway, the flow of data is like this. You can take a look at it.
Create a yml file in the resources folder and enter the following content:
server: port: 8080 //本机的端口号 spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/自己数据库的名称?useUnicode=true & characterEncoding=utf-8 & useSSL=true & serverTimezone=Asia/Shanghai username: root //数据库的用户名 password: xxxxxx //数据库的密码 mybatis: mapper-locations: classpath:/Mapper/*.xml type-aliases-package: com.example.test.Entity //这个是扫描到Entity实体包的路径,可根据自己的配置
After configuring the yml file, we go to the Databases on the right to see if we can connect to our local MySQL database:
##Fill in the data table name (our table here is the user table), user name and password, and database nameFourth: Write the Entity, Dao, Service, and Controller layers in sequence , and create the mapper.xml fileEntity package: create a UserEntity class, the content is as follows:
public class UserEntity { private Integer userId; private String userName; private String userAddress; public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserAddress() { return userAddress; } public void setUserAddress(String userAddress) { this.userAddress = userAddress; } }
Dao package: create a UserDao interface, the content As follows:import com.example.test.Entity.UserEntity; import org.apache.ibatis.annotations.Mapper; import java.util.List; @Mapper public interface UserDao { List<UserEntity> queryLimit(Integer currentPage, Integer pageSize); Integer addUser(UserEntity user); Integer updateUser(UserEntity user); Integer deleteUser(UserEntity user); }
Service package: Create a UserService class with the following content:import com.example.test.Dao.UserDao; import com.example.test.Entity.UserEntity; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service("UserService") public class UserService { @Autowired private UserDao userDao; public List<UserEntity> queryLimit(Integer currentPage,Integer pageSzie){ return userDao.queryLimit(currentPage,pageSzie); } public Integer addUser(UserEntity user){ return userDao.addUser(user); } public Integer updateUser(UserEntity user){ return userDao.updateUser(user); } public Integer deleteUser(UserEntity user){ return userDao.deleteUser(user); } }
Controller package: Create a UserController class with the following content:import com.example.test.Entity.UserEntity; import com.example.test.Service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("user") public class UserController { @Autowired private UserService userService; String message = ""; @RequestMapping("/queryLimit") public List<UserEntity> queryLimit(@RequestParam("currentPage") Integer currentPage,@RequestParam("pageSize") Integer pageSize){ return userService.queryLimit(currentPage,pageSize); } @PostMapping("/addUser") public String addUer(@RequestBody UserEntity user){ //用Mybatis执行insert语句的时候,插入成功会返回1,不成功则会抛出异常,捕获一下异常就好 try { userService.addUser(user); message = "增加用户成功"; }catch (Exception exception){ message = "增加用户异常"; } return message; } @PutMapping("/updateUser") public String updateUser(@RequestBody UserEntity user){ //Mybatis的更新操作成功返回1,用户不存在返回0,失败则抛异常 try { message = userService.updateUser(user) == 1?"更新用户成功":"用户不存在,更新失败"; }catch (Exception exception){ message = "更新异常"; } return message; } @DeleteMapping("/deleteUser") public String deleteUser(@RequestBody UserEntity user){ //Mybatis的删除操作和更新返回值一样,成功返回1,用户不存在返回0,失败则抛异常 try { message = userService.deleteUser(user) == 1?"删除用户成功":"用户不存在,删除失败"; }catch (Exception exception){ message = "删除异常"; } return message; } }
After writing the above content, we need to create the mapper.xml file in the Mapper folder, as shown below:
mapper.xml文件内容如下:需要注意的地方是namespace:这个路径是你的UserDao接口的路径,因为你传过来的数据需要和xml进行一个绑定,这样你编写的SQL语句才能接收到你前端传过来的数据(大体意思可以这么理解),而id则是和你UserDao中的接口方法相对应,比如我的UserDao接口中的查找方法命名是queryLimit,那么我在xml文件中的查询语句的id就应该和queryLimit想对应,即:id=“queryLimit”。
resultType是返回数据的类型
parameterType则是传入的数据类型
<?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.example.test.Dao.UserDao"> <select id="queryLimit" resultType="UserEntity"> select * from user limit #{currentPage},#{pageSize}; </select> <insert id="addUser" parameterType="UserEntity"> insert into user(userName,userAddress) values(#{userName},#{userAddress}); </insert> <update id="updateUser" parameterType="UserEntity"> update user set userName=#{userName},userAddress=#{userAddress} where userId=#{userId}; </update> <delete id="deleteUser" parameterType="UserEntity"> delete from user where userId=#{userId}; </delete> </mapper>
最后我们需要在启动类加一点东西(MapperScan扫描的是我们Dao包的地址,填写自己的就好)
查询用户数据->地址为:http://localhost:8080/user/queryLimit?currentPage=0&pageSize=5
添加用户数据-> 地址为:http://localhost:8080/user/addUser
数据库也能看到数据:
更新用户数据-> 地址为:http://localhost:8080/user/updateUser
更新之后数据库数据为:
删除用户数据-> 地址为:http://localhost:8080/user/deleteUser
查看数据库数据已经删除:
The above is the detailed content of How SpringBoot integrates Mybatis to implement addition, deletion, modification and query. For more information, please follow other related articles on the PHP Chinese website!