In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article shows you how to carry out Spring Boot 2.x integrated MyBatis data layer development, the content is concise and easy to understand, it will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.
Introduction to MyBatis Overview
MyBatis is an excellent persistence layer framework that supports customized SQL, stored procedures, and advanced mapping. It uses object-oriented programming to CRUD the database, which makes the operation of the relational database more convenient and simple. It supports both XML descriptor configuration files and annotations to execute SQL statements. "simple and flexible" is its biggest advantage in object-relational mapping tools.
Mybatis-spring-boot-starter
In the past, developing with MyBatis required a variety of configuration files, entity classes, Dao layer mapping associations, and a host of other configurations. After constant optimization, finally he came, mybatis-spring-boot-starter can do without configuration only annotated development, but also can use simple configuration to easily get started. Of course, both methods require the introduction of mybatis-spring-boot-starter in the POM file:
Org.mybatis.spring.boot mybatis-spring-boot-starter 2.1.0 Integration MyBatis preparation work 1. Build a Spring Boot project 2. Set up the MySQL database (db_test), create the table (t_user) and add some test data SET NAMES utf8mb4;SET FOREIGN_KEY_CHECKS = 0PortMub-Table structure for tweak userRose-DROP TABLE IF EXISTS `tuser` CREATE TABLE `tuser` (`id` int (8) NOT NULL AUTO_INCREMENT COMMENT 'ID', `user_ name` varchar (20) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT' user name', `user_ sex` char (1) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT 'user gender', PRIMARY KEY (`id`) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8 -Records of tweak user VALUES-BEGIN;INSERT INTO `t _ user` VALUES (1, 'Liu Bei', 'male'); INSERT INTO `t _ user` VALUES (2, 'Sun Shangxiang', 'female') INSERT INTO `t _ user`VALUES (3, 'Zhou Yu', 'male'); INSERT INTO `tuser` VALUES (4, 'Xiao Qiao', 'female'); INSERT INTO `tuser`VALUES (5, 'Zhuge Liang', 'male'); INSERT INTO `tuser`User`VALUES (7, 'Guan Yu', 'male'); INSERT INTO `tuser`User` VALUES (8, 'Zhang Fei', 'male') INSERT INTO `tuser`VALUES (9, 'Zhao Yun', 'male'); INSERT INTO `tuser` VALUES (10, 'Mr. Huang', 'male'); INSERT INTO `tuser`VALUES (11, 'Cao Cao', 'male'); INSERT INTO `tuser`VALUES (12, 'Sima Yi', 'male'); INSERT INTO `tuser`VALUES (13, 'Diao Chan', 'female'); INSERT INTO `tuser`VALUES (14,'Lv Bu', 'male') INSERT INTO `t _ user`VALUES (15,'Ma Chao', 'male'); INSERT INTO `tuser` VALUES (16, 'Wei Yan', 'male'); INSERT INTO `tuser` VALUES (17, 'Meng Huo', 'male'); INSERT INTO `tuser` VALUES (18, 'Big Joe', 'female'); INSERT INTO `tuser`VALUES (19, 'Liu Chan', 'male'); INSERT INTO `tuser`VALUES (20, 'Jiang Wei', 'male') INSERT INTO `t _ user` VALUES (21, 'Liao Hua', 'male'); INSERT INTO `t _ user` VALUES (22, 'Guanping', 'male'); COMMIT;SET FOREIGN_KEY_CHECKS = 1 3. Create a new user entity class UserEntity.javapublic class UserEntity {private Long id; private String userName; private String userSex; public Long getId () {return id;} public void setId (Long id) {this.id = id;} public String getUserName () {return userName } public void setUserName (String userName) {this.userName = userName;} public String getUserSex () {return userSex;} public void setUserSex (String userSex) {this.userSex = userSex;}} annotation mode 1. Add related Maven dependency org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test Org.springframework.boot spring-boot-starter-jdbc org.springframework.boot spring-boot -devtools true mysql mysql-connector-java runtime Org.mybatis.spring.boot mybatis-spring-boot-starter 2.1.0 2.application.properties add related configuration # datasourcespring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.url=jdbc:mysql://127.0.0. 1:3306/db_test?useUnicode=true&characterEncoding=UTF-8&useSSL=truespring.datasource.username=rootspring.datasource.password=root
Add @ MapperScan to scan mapper packages in the startup class
@ SpringBootApplication@MapperScan ("cn.zwqh.springboot.dao") public class SpringBootMybatisApplication {public static void main (String [] args) {SpringApplication.run (SpringBootMybatisApplication.class, args);}}
Or add the annotation @ Mapper directly to the Mapper class. It is recommended to use the one above, otherwise it will be troublesome to add an annotation to each mapper.
3.Mapper developer public interface UserDao {/ / use annotations / * get all users * @ return * / @ Select ("select * from t_user") @ Results ({@ Result (property = "userName", column = "user_name"), @ Result (property = "userSex") Column = "user_sex")}) List getAll2 () / * * obtain users according to id * @ param id * @ return * / @ Select ("select * from t_user where id=# {id}") @ Results ({@ Result (property = "userName", column = "user_name"), @ Result (property = "userSex") Column = "user_sex")}) List getOne2 (Long id) / * * New user * @ param user * / @ Insert ("insert into t_user (user_name,user_sex) values (# {userName}, # {userSex})") void insertUser2 (UserEntity user) / * modify user * @ param user * / @ Update ("update t_user set user_name=# {userName}, user_sex=# {userSex} where id=# {id}") void updateUser2 (UserEntity user) / * * Delete user * @ param id * / @ Delete ("delete from t_user where id=# {id}") void deleteUser2 (Long id);}
Note: @ Select is the annotation of the query class. All queries use this @ Result to modify the returned result set. The attribute of the associated entity class corresponds to the database field one by one. If the attribute of the entity class is consistent with the attribute name of the database, this attribute is not needed. @ Insert is inserted into the database. Passing the entity class directly will automatically parse the attribute to the corresponding value @ Update to modify it, or you can directly pass in the object @ delete to delete it.
4. Restful interface test
UserController
@ RestController@RequestMapping ("/ user") public class UserController {@ Autowired private UserDao userDao; / / get all users * @ return * / @ RequestMapping ("/ getAll2") public List getAll2 () {return userDao.getAll2 () } / * get the user * @ return * / @ RequestMapping ("/ getOne2") public List getOne2 (Long id) {return userDao.getOne2 (id) according to id } / * New user * @ param user * @ return * / @ RequestMapping ("/ insertUser2") public String insertUser2 (UserEntity user) {userDao.insertUser2 (user); return "insert success" } / * modify user * @ param user * @ return * / @ RequestMapping ("/ updateUser2") public String updateUser2 (UserEntity user) {userDao.updateUser2 (user); return "update success" } / * * Delete user * @ param user * @ return * / @ RequestMapping ("/ deleteUser2") public String deleteUser2 (Long id) {userDao.deleteUser2 (id); return "delete success";}}
After starting the project, you can visit http://127.0.0.1:8080/user/getOne2?id=1 through the browser for testing, and others are the same. You can also write unit tests for testing.
XML mode 1.pom file as above 2.application.properties add related configuration # datasourcespring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.url=jdbc:mysql://127.0.0.1:3306/db_test?useUnicode=true&characterEncoding=UTF-8&useSSL=truespring.datasource.username=rootspring.datasource.password=root#mybatismybatis.mapper-locations=classpath:/mapper/*.xml3.Mapper layer development public interface UserDao {/ / mapper.xml mode / * * * get all users * @ return * / List getAll () / * * obtain users according to id * @ return * / List getOne (Long id); / * add users * @ param user * / void insertUser (UserEntity user) / * modify user * @ param user * / void updateUser (UserEntity user); / * delete user * @ param id * / void deleteUser (Long id) } 4.xml mapping file select * from t_user select * from t_user where id=# {id} insert into t_user (user_name User_sex) values (# {userName}, # {userSex}) update t_user set user_name=# {userName}, user_sex=# {userSex} where id=# {id} delete from t_user where id=# {id} how to choose to use
Personally, the annotation method is suitable for lightweight projects, and the current micro-service projects are more suitable for this mode; for large projects, xml is more suitable for complex multi-table union query sql.
Extension: use the MyBatis paging plug-in pagehelper1. Pom.xml adds dependency com.github.pagehelper pagehelper-spring-boot-starter 1.2.12 2. Pagehelper uses @ RestController@RequestMapping ("/ user") public class UserController {@ Autowired private UserDao userDao / * * use the pagehelper paging plug-in * @ param pageNum * @ param pageSize * @ return * / @ RequestMapping ("/ pagehelperTest") public List pagehelperTest (int pageNum,int pageSize) {PageHelper.startPage (pageNum, pageSize); return userDao.getAll (); / / directly use the mapper}} 3 above. test
The browser accesses http://127.0.0.1:8080/user/pagehelperTest?pageNum=1&pageSize=10 directly and try changing the parameters.
The above content is how to develop the Spring Boot 2.x integrated MyBatis data tier. Have you learned the knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are 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.