Spring Boot is a rapid development framework that can help developers quickly build WEB applications. MyBatis is an excellent ORM framework that can simplify data access and persistence between Java and databases. This article will introduce how to use MyBatis to implement data access and persistence in Spring Boot.
1. Spring Boot integrates MyBatis
- Add dependencies
Add MyBatis and MySQL dependencies in the pom.xml file:
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.42</version> </dependency>
Here we use mybatis-spring-boot-starter to integrate MyBatis.
- Configure the data source
Add the database connection properties in application.properties:
spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driverClassName=com.mysql.jdbc.Driver
Here we use the MySQL database and connect using the root account, The password is 123456.
- Configuring MyBatis
Spring Boot will automatically scan the mapper path by default. We only need to configure the mapper path in application.properties:
mybatis.mapper-locations=classpath:mapper/*.xml
This configuration indicates that the mapper file is in the mapper folder under the project's classpath.
After completing the above configuration, Spring Boot has completed the integration of MyBatis.
2. Writing entity classes and Mapper
- Writing entity classes
Define a User class to represent a user table in the database:
public class User { private Long id; private String name; private Integer age; // 省略getter和setter方法 }
- Writing Mapper
Define a UserMapper interface to define the addition, deletion, modification and query operations of the User table:
public interface UserMapper { void saveUser(User user); void updateUser(User user); void deleteUser(Long id); User findUserById(Long id); List<User> findAllUsers(); }
Here we define the addition, deletion, modification and query as well as Method to query all users.
3. Write Mapper.xml
Next, we need to write the UserMapper.xml file to implement the operations defined in UserMapper:
<?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.demo.mapper.UserMapper"> <insert id="saveUser" parameterType="com.example.demo.entity.User"> insert into user(name, age) values (#{name}, #{age}) </insert> <update id="updateUser" parameterType="com.example.demo.entity.User"> update user set name = #{name}, age = #{age} where id = #{id} </update> <delete id="deleteUser" parameterType="java.lang.Long"> delete from user where id = #{id} </delete> <select id="findUserById" parameterType="java.lang.Long" resultType="com.example.demo.entity.User"> select * from user where id = #{id} </select> <select id="findAllUsers" resultType="com.example.demo.entity.User"> select * from user </select> </mapper>
In this file, we implement All methods defined in UserMapper, where parameterType represents the parameter type and resultType represents the return value type.
4. Writing Service classes and controllers
- Writing Service classes
Define a UserService class to encapsulate operations on the User table:
@Service public class UserService { @Autowired private UserMapper userMapper; public void saveUser(User user) { userMapper.saveUser(user); } public void updateUser(User user) { userMapper.updateUser(user); } public void deleteUser(Long id) { userMapper.deleteUser(id); } public User findUserById(Long id) { return userMapper.findUserById(id); } public List<User> findAllUsers() { return userMapper.findAllUsers(); } }
In this class, we use the @Autowired annotation to inject UserMapper, that is, you can use the methods defined in UserMapper.
- Writing Controller
Define a UserController class to implement addition, deletion, modification and query operations for users:
@RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @PostMapping("/") public String saveUser(@RequestBody User user) { userService.saveUser(user); return "success"; } @PutMapping("/") public String updateUser(@RequestBody User user) { userService.updateUser(user); return "success"; } @DeleteMapping("/{id}") public String deleteUser(@PathVariable Long id) { userService.deleteUser(id); return "success"; } @GetMapping("/{id}") public User getUserById(@PathVariable Long id) { return userService.findUserById(id); } @GetMapping("/") public List<User> findAllUsers() { return userService.findAllUsers(); } }
In this class, we use @ The RestController annotation indicates that the current class is a controller, and the access path is specified using the @RequestMapping annotation. At the same time, UserService is injected using the @Autowired annotation, that is, the methods defined in UserService can be used.
5. Test
Now, we have completed the construction and coding of the entire project. Next, we can use tools such as Postman to test the API defined in the controller.
Use POST request to save user information, the request body is:
{ "name": "张三", "age": 18 }
Use PUT request to update user information, the request body is:
{ "id": 1, "name": "李四", "age": 20 }
Use DELETE request to delete the user Information, the URL is:
http://localhost:8080/user/1
Use GET request to obtain user information, the URL is:
http://localhost:8080/user/1
Use GET request to obtain all user information, the URL is:
http://localhost:8080/user/
Six , Summary
This article introduces how to use MyBatis to implement data access and persistence in Spring Boot, and uses a simple example to illustrate the entire process. MyBatis can make Java programs' database operations more efficient and concise. If you need to implement database operations in Spring Boot, you can consider using MyBatis.
The above is the detailed content of Using MyBatis to implement data access and persistence in Spring Boot. For more information, please follow other related articles on the PHP Chinese website!

缓存的概述和分类概述缓存就是一块内存空间.保存临时数据为什么使用缓存将数据源(数据库或者文件)中的数据读取出来存放到缓存中,再次获取的时候,直接从缓存中获取,可以减少和数据库交互的次数,这样可以提升程序的性能!缓存的适用情况适用于缓存的:经常查询但不经常修改的(eg:省市,类别数据),数据的正确与否对最终结果影响不大的不适用缓存的:经常改变的数据,敏感数据(例如:股市的牌价,银行的汇率,银行卡里面的钱)等等MyBatis缓存类别一级缓存:它是sqlSession对象的缓存,自带的(不需要配置)不

MyBatis允许使用插件来拦截的方法Executor(update,query,flushStatements,commit,rollback,getTransaction,close,isClosed)ParameterHandler(getParameterObject,setParameters)ResultSetHandler(handleResultSets,handleOutputParameters)StatementHandler(prepare,parameterize,ba

mybatis分页的方式:1、借助数组进行分页,首先查询出全部数据,然后再list中截取需要的部分。2、借助Sql语句进行分页,在sql语句后面添加limit分页语句即可。3、利用拦截器分页,通过拦截器给sql语句末尾加上limit语句来分页查询。4、利用RowBounds实现分页,需要一次获取所有符合条件的数据,然后在内存中对大数据进行操作即可实现分页效果。

简介今天开发时想将自己写好的代码拿来优化,因为不想在开发服弄,怕搞坏了到时候GIT到生产服一大堆问题,然后把它分离到我轮子(工具)项目上,最后运行后发现我获取List的时候很卡至少10秒,我惊了平时也就我的正常版本是800ms左右(不要看它很久,因为数据量很大,也很正常。),前提是我也知道很慢,就等的确需要优化时,我在放出我优化的plus版本,回到10秒哪里,最开始我刚刚接到这个app项目时,在我用PageHelper.startPage(page,num);(分页),还没等查到的数据封装(Pa

当某些sql因为不知名原因堵塞时,为了不影响后台服务运行,想要给sql增加执行时间限制,超时后就抛异常,保证后台线程不会因为sql堵塞而堵塞。一、yml全局配置单数据源可以,多数据源时会失效二、java配置类配置成功抛出超时异常。importcom.alibaba.druid.pool.DruidDataSource;importcom.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;importorg.apache.

mybatis调用mysql存储过程并获取返回值1、mysql创建存储过程#结束符号默认;,delimiter$$语句表示结束符号变更为$$delimiter$$CREATEPROCEDURE`demo`(INinStrVARCHAR(100),outourStrVARCHAR(4000))BEGINSETourStr='01';if(inStr=='02')thensetourStr='02';en

SpringBoot打印mybatis的执行sql1、使用场景应为在开发过程之中跟踪后端SQL语句,因什么原因导致的错误。需要在Debug过程之中打印出执行的SQL语句。所以需要配置一下SpringBoot之中,Mybatis打印SQL语句。2、具体实现application.properties(yml)中配置的两种方式:1.logging.level.dao包名(daopackage)=debug2.mybatis.configuration.log-impl=org.apache.ibat

一、什么是缓存缓存是内存当中一块存储数据的区域,目的是提高查询效率。MyBatis会将查询结果存储在缓存当中,当下次执行相同的SQL时不访问数据库,而是直接从缓存中获取结果,从而减少服务器的压力。什么是缓存?存在于内存中的一块数据。缓存有什么作用?减少程序和数据库的交互,提高查询效率,降低服务器和数据库的压力。什么样的数据使用缓存?经常查询但不常改变的,改变后对结果影响不大的数据。MyBatis缓存分为哪几类?一级缓存和二级缓存如何判断两次Sql是相同的?查询的Sql语句相同传递的参数值相同对结


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version
Visual web development tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
