In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly shows you "SpringBoot framework how to integrate Mybatis", the content is easy to understand, clear, hope to help you solve doubts, the following let the editor lead you to study and learn "SpringBoot framework how to integrate Mybatis" this article.
Step 1 add mybatis-starter dependency
Visit: https://mvnrepository.com/
Search mybatis, find MyBatis Spring Boot Starter, click in, copy to pom.xml
Org.mybatis.spring.boot mybatis-spring-boot-starter 2.2.0
We can just use the latest one.
Step 2 how to configure the mybatis to SpringBoot project mybatis: mapper-locations: classpath:mybatis/*.xml type-aliases-package: com.java18.vipmgr.pojo
Mapper-locations is the directory where the xml file is defined.
We put it under resources, that is, in classpath.
UserMapper.xml
Select * from users
There is a method written in it, pay attention to the configuration of namespace= "com.java18.vipmgr.mapper.UserMapper". This indicates that the xml file is bound to UserMapper.java.
The code is as follows
@ Mapperpublic interface UserMapper {public List getAllUsers ();}
Next, let's take a look at the configuration of resultType= "User". Why does the return type know it is a User object?
The User class is here:
@ Datapublic class User {private Integer id; private String username; private String password; private Integer points;}
That's because we did a binding in application.yml, and that's it:
Mybatis: mapper-locations: classpath:mybatis/*.xml type-aliases-package: com.java18.vipmgr.pojo
So, when we write resultType= "User", we automatically match to the User class under the com.java18.vipmgr.pojo package.
At this point, the configuration of the mybatis to SpringBoot project is successful!
Step 3 Test query
Or do the test in controller, first introduce Mapper
@ AutowiredUserMapper userMapper
Then write the query method
@ GetMapping ("getAllViaMybatis") public List getAllViaMybatis () {return userMapper.getAllUsers ();}
Start the service, access http://localhost:8888/user/getAllViaMybatis, and get
[{"id": 1, "username": "zhangsan", "password": "123"," points ": 1000}, {" id ": 2," username ":" lisi "," password ":" 123", "points": 1000}]
Step 4 mybatis Annotation method
In addition to xml, we can also use mybatis annotations
UserMapper.java
@ Mapperpublic interface UserMapper {public List getAllUsers (); @ Select ("select * from users where id = # {param1}") User findById (String id);}
Added a method, annotated @ Select, accepted ID as a parameter, and here uses the sequential parameter passing method of mybatis.
Corresponding Controller method
@ GetMapping ("findById") public User findById (String id) {return userMapper.findById (id);}
Test url: http://localhost:8888/user/findById?id=2
Return {"id": 2, "username": "lisi", "password": "123"," points ": 200}
The advantage of this is that there is no need to write xml, which is very convenient, but the disadvantage is that it is not flexible enough.
Step 5 do a new operation with annotations
Mapper code
@ Update ("insert into users values (null,# {username}, # {password}, # {points})") void addUser (User user)
Controller code
@ GetMapping ("addUser") public boolean addUser () {User user = new User (); user.setUsername ("wangwu"); user.setPassword ("123"); user.setPoints (1000); userMapper.addUser (user); return true;}
Test effect
PS: because id grows automatically, you can insert null.
Step 6 integrate the PageHelper paging plug-in
Pom.xml
Com.github.pagehelper pagehelper-spring-boot-starter 1.3.1
Just import this dependency, you can configure nothing.
UserController, the original query method is changed to this
@ GetMapping ("getAllViaMybatis") public PageInfo getAllViaMybatis (int page,int rows) {PageHelper.startPage (page,rows); PageInfo pageInfo = new PageInfo (userMapper.getAllUsers ()); return pageInfo;}
Receive page and rows as paging parameters
Test url http://localhost:8888/user/getAllViaMybatis?page=1&rows=10
Remember to get more data in the database before testing.
Step 7 expand knowledge: four ways to transfer parameters to mybatis
Passing parameters through object
Insert into emp (ename,job,hiredate,sal) values (# {ename}, # {job}, # {hiredate}, # {sal}); select last_insert_id ()
Mode 1: sequential parameter transfer method
Update emp set ename=# {param1} where empno=# {param2}
Mode 2:@Param annotation transfer parameter method
Is to top the parameter to be passed in the parameter list of the method, and then write it directly in sql
Public void updateEmpByNo2 (@ Param ("name") String ename,@Param ("no") Integer empno) throws IOException; update emp set ename=# {name} where empno=# {no}
Mode 3:Map parameter transfer method
The point is that the phrase parameterType= "hashmap" public void updateEmpByNo3 (Map argMap) throws IOException; update emp set ename=# {name} where empno=# {no}
Mode 4:Java Bean parameter transfer method
Public User selectUser (Emp emp); select * from user where user_name = # {userName} and dept_id = # {deptId} what is the difference between # {} and ${} in step 8 Mybatis?
KaTeX parse error: Expected 'EOF', got' #'at position 10: {} is string substitution, # substitution {} is preprocessing; Mybatis … When {}, you replace ${} directly with the value of the variable.
When Mybatis processes # {}, it preprocesses the sql statement and replaces # {} in sql with? Number, call the set method of PreparedStatement to assign the value
Using # {} can effectively prevent SQL injection and improve the security of the system.
How to write the fuzzy query like statement in step 9 Mybatis?
Type 1: add the sql wildcard to the Java code, that is, write the wildcard in the string and bring it in. (recommended).
String wildcardname = "% smi%"; list names = mapper.selectlike (wildcardname)
Corresponding xml:
Select * from foo where bar like # {value}
Type 2: concatenating wildcards in sql statements will cause sql injection (not recommended)
String wildcardname = "smi"; list names = mapper.selectlike (wildcardname); corresponding xml: select * from foo where bar like "%" ${value} "%" step 10 SpringBoot integrate Mybatis-plus
MyBatis-Plus (opens new window) (MP for short) is an enhancement tool of MyBatis (opens new window), which is only enhanced but not changed on the basis of MyBatis, in order to simplify development and improve efficiency.
Official website document address: https://mp.baomidou.com/guide/
The first step is to add dependencies, which is essential.
Com.baomidou mybatis-plus-boot-starter 3.3.1.tmp step 11 how does Mybatis-plus coexist with Mybatis?
Because the above code is based on Mybatis, we need to make them coexist. The solution is to modify the application.yml
Mybatis-plus: mapper-locations: classpath:mybatis/*.xml type-aliases-package: com.java18.vipmgr.pojo
Just change mybayis to mybatis-plus, and none of the previous functions will be affected!
Step 12 get started with Mybatis-plus quickly
Because our class name and indication are inconsistent, we need to make a configuration
User.java
@ Data@TableName ("users") public class User {private Integer id; private String username; private String password; private Integer points;}
UserMapper.java
Public interface UserMapper extends BaseMapper {/ / omit the previous code}
Inheriting from BaseMapper, you can have a lot of CRUD methods, much like JPA.
UserController.java
@ GetMapping ("getAllViaMybatisPlus") public IPage getAllViaMybatisPlus (Integer page,Integer rows) {IPage pageInfo = new Page (page, rows); / / Parameter 1 is the current page, and parameter 2 is the number of pages per page QueryWrapper wrapper = new QueryWrapper (); pageInfo = userMapper.selectPage (pageInfo,wrapper); return pageInfo;}
Test URL: http://localhost:8888/user/getAllViaMybatisPlus?page=1&rows=10
{"records": [{"id": 1, "username": "zhangsan", "password": "123"," points ": 1000}, {" id ": 2," username ":" lisi "," password ":" 123", "points": 200}, {"id": 3, "username": "wangwu", "password": "id": 1000}, {"id": 4, "username": "Tsai Mutual listening", "password": "123"," points ": 1000} {"id": 5, "username": "Xun Pangzhi", "password": "123"," points ": 1000}, {" id ": 6," username ":" raising embroidery "," password ":" 123,123 "," points ": 1000}, {" id ": 7," username ":" confused tune "," password ":" 123", "points": 1000}, {"id": 8, "username": "Rong Yuexia", "password": "123"," points ": 1000} {"id": 9, "username": "current", "password": "123"," points ": 1000}, {" id ": 10," username ":" Ludao tune "," password ":" 123", "points": 1000}], "total": 22, "size": 10, "current": 1, "orders": [], "hitCount": false, "searchCount": true, "pages": 3}
The above is all the content of the article "how the SpringBoot Framework integrates Mybatis". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.