In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
Today, the editor will share with you the relevant knowledge points about how to use SpringBoot integration Mybatis-plus. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.
1. Brief introduction to mybatis-plus:
Mybatis-Plus (MP for short) is an enhancement tool of Mybatis, which is only enhanced but not changed on the basis of Mybatis, in order to simplify development and improve efficiency. This is the official definition. For more introduction and features of mybatis-plus, please refer to the official website of mybatis-plus. So how is it enhanced? In fact, it has encapsulated some crud methods, we no longer need to write xml, just call these methods, similar to JPA. And 3.x series support lambda syntax, let me write conditional construction when a lot of "magic value", from the code structure is more concise.
II. Springboot Integration mybatis-plus case
Pom.xml configuration
Org.springframework.boot spring-boot-starter org.springframework.boot spring-boot-starter-test test org.projectlombok lombok 1.16.10 provided org.springframework.boot spring-boot-starter-web com.alibaba druid-spring-boot-starter 1.1.10 mysql mysql-connector-java Com.alibaba druid 1.1.0 com.baomidou mybatis-plus-boot-starter 3.1.0
Application.yml configuration
Server: port: 10100 # configure startup port number mybatis: config-location: classpath:mybatis.cfg.xml # mybatis main configuration file path type-aliases-package: com.demo.drools.entity # define aliases for all operation classes package mapper-locations: # all mapper mapping files-classpath:mapper/*.xml spring: # configuration of springboot datasource: # define the data source # 127.0.0.1 as the ip tested locally 3306 is the port number of mysql. ServerTimezone defines the time zone, just copy it. The high version of mysql needs to define these things. # useSSL is also some high version of mysql. You need to ask if you can use SSL to connect to url: jdbc:mysql://127.0.0.1:3306/test?serverTimezone=GMT%2B8&useSSL=FALSE username: root # database user name Root is administrator password: 123456 # password of the database user # use druid data source type: com.alibaba.druid.pool.DruidDataSource # mybatis-plus related configuration mybatis-plus: # xml scan Separate multiple directories with commas or semicolons (tell Mapper the corresponding XML file location) mapper-locations: classpath:mapper/*.xml # the following configurations have default values, and you can not set global-config: db-config: # primary key type AUTO: "Database ID self-increment" INPUT: "user input ID", ID_WORKER: "globally unique ID (number type unique ID)", UUID: "globally unique ID UUID" Id-type: auto # Field Policy IGNORED: "ignore judgment" NOT_NULL: "non-NULL judgment") NOT_EMPTY: "non-empty judgment" field-strategy: NOT_EMPTY # Database Type db-type: MYSQL configuration: # whether automatic hump naming rule mapping is enabled: similar mapping from database column names to Java attribute hump naming map-underscore- To-camel-case: true # if the query result contains columns with null values Then MyBatis will not map this field call-setters-on-nulls: true # when mapping. This configuration will print out the executed sql. You can use log-impl: org.apache.ibatis.logging.stdout.StdOutImpl during development or testing.
User information entity
Package com.demo.drools.entity; import com.baomidou.mybatisplus.annotation.IdType;import com.baomidou.mybatisplus.annotation.TableId;import com.baomidou.mybatisplus.annotation.TableName;import lombok.Data / * TODO your comment * * @ author Yujiaqi * @ date 19:14 on 2020-12-2 * / @ Data@TableName ("user_info") / / @ TableName corresponds to the table name public class UserInfoEntity {/ * primary key * @ TableId that can determine the type of primary key. If not written, the default value will be taken. The default value can be configured in yml * AUTO: database ID self-increment * INPUT: user input ID * ID_WORKER: globally unique ID Long type primary key * ID_WORKER_STR: string globally unique ID * UUID: globally unique ID,UUID type primary key * NONE: this type is not set primary key type * / @ TableId (type = IdType.AUTO) private Long id / * * name * / private String name; / * * Age * / private Integer age; / * skills * / private String skill; / * Evaluation * / private String evaluate; / * * score * / private Long fraction;}
Config class
Package com.demo.drools.config; import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;import org.springframework.context.annotation.Bean / * TODO your comment * * @ author Yujiaqi * @ date 19:14 on 2020-12-2 * / public class MybatisPlusConfig {/ * mybatis-plus SQL execution efficiency plug-in [production environment can be closed] * / @ Bean public PerformanceInterceptor performanceInterceptor () {return new PerformanceInterceptor () } / * paging plug-in * / @ Bean public PaginationInterceptor paginationInterceptor () {return new PaginationInterceptor ();}}
Spring boot startup class
Package com.demo.drools; import org.mybatis.spring.annotation.MapperScan;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication; / * * @ author adds @ Mapper annotation to Jiaqi * / @ SpringBootApplication//@MapperScan and dao layer means @ MapperScan (basePackages = "com.demo.drools.dao") public class DroolsApplication {public static void main (String [] args) {SpringApplication.run (DroolsApplication.class, args);}}
Dao layer
Package com.demo.drools.dao; import com.baomidou.mybatisplus.core.mapper.BaseMapper;import com.baomidou.mybatisplus.core.metadata.IPage;import com.demo.drools.entity.UserInfoEntity;import org.apache.ibatis.annotations.Mapper;import org.apache.ibatis.annotations.Param; / * user Information DAO * * @ author Yujiaqi * @ date 19:16 on 2020-12-2 * / @ Mapperpublic interface UserInfoDao extends BaseMapper {}
Service layer
Package com.demo.drools.service; import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.extension.service.IService;import com.demo.drools.entity.UserInfoEntity; / * * TODO your comment * * @ author Yujiaqi * @ date 19:17 on 2020-12-2 * / public interface UserInfoService extends IService {}
ServiceImpl implementation class layer
Package com.demo.drools.service.impl; import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import com.demo.drools.dao.UserInfoDao;import com.demo.drools.entity.UserInfoEntity;import com.demo.drools.service.UserInfoService;import org.springframework.stereotype.Service; import javax.annotation.Resource; / * * TODO your comment * * @ author Yujiaqi * @ date 19:18 on 2020-12-2 * / @ Servicepublic class UserInfoSerivceImpl extends ServiceImpl implements UserInfoService {}
Controller control layer
Package com.demo.drools.controller; import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.demo.drools.entity.UserInfoEntity;import com.demo.drools.service.UserInfoService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList;import java.util.Collection;import java.util.HashMap;import java.util.List Import java.util.Map; / * * TODO your comment * * @ author Yujiaqi * @ date 19:20 on 2020-12-2 * / @ RestController@RequestMapping ("/ userInfo") public class UserInfoController {@ Autowired private UserInfoService userInfoService / * * obtain user information according to ID * @ Author Sans * @ CreateTime 16:34 on 2019-6-8 * @ Param userId user ID * @ Return UserInfoEntity user entity * / @ RequestMapping ("/ getInfo") public UserInfoEntity getInfo (String userId) {UserInfoEntity userInfoEntity = userInfoService.getById (userId); return userInfoEntity } / * query all information * @ Author Sans * @ CreateTime on 2019-6-8 16:35 * @ Param userId user ID * @ Return List user entity collection * / @ RequestMapping ("/ getList") public List getList () {List userInfoEntityList = userInfoService.list (); return userInfoEntityList } / * paging query all data * @ Author Sans * @ CreateTime 2019-6-8 16:37 * @ Return IPage paging data * / @ RequestMapping ("/ getInfoListPage") public IPage getInfoListPage () {/ / need to configure the paging plug-in IPage page = new Page () in the Config configuration class; page.setCurrent (5) / / current page page.setSize (1); / / number of entries per page page = userInfoService.page (page); return page } / * query the collection of user information according to the specified field * @ Author Sans * @ CreateTime on 2019-6-8 16:39 * @ Return Collection user entity collection * / @ RequestMapping ("/ getListMap") public Collection getListMap () {Map map = new HashMap (); / / kay is the field name value is the field value map.put ("age", 20) Collection userInfoEntityList = userInfoService.listByMap (map); return userInfoEntityList;} / * * add user information * @ Author Sans * @ CreateTime 16:40 on 2019-6-8 * / @ RequestMapping ("/ saveInfo") public void saveInfo () {UserInfoEntity userInfoEntity = new UserInfoEntity (); userInfoEntity.setName ("Xiaolong"); userInfoEntity.setSkill ("JAVA") UserInfoEntity.setAge (18); userInfoEntity.setFraction (59L); userInfoEntity.setEvaluate ("the student is a programmer who is changing BUG"); userInfoService.save (userInfoEntity) } / * add user information in batch * @ Author Sans * @ CreateTime 16:42 on 2019-6-8 * / @ RequestMapping ("/ saveInfoList") public void saveInfoList () {/ / create object UserInfoEntity sans = new UserInfoEntity (); sans.setName ("Sans"); sans.setSkill ("sleep"); sans.setAge (18) Sans.setFraction (60L); sans.setEvaluate ("Sans is a sleepy, short, fat skeleton"); UserInfoEntity papyrus = new UserInfoEntity (); papyrus.setName ("papyrus"); papyrus.setSkill ("JAVA"); papyrus.setAge (18); papyrus.setFraction (58L) Papyrus.setEvaluate ("Papyrus is a small, confident and attractive skeleton with a loud voice and personality"); / / batch save List list = new ArrayList (); list.add (sans); list.add (papyrus); userInfoService.saveBatch (list) } / * Update user information * @ Author Sans * @ CreateTime 16:47 on 2019-6-8 * / @ RequestMapping ("/ updateInfo") public void updateInfo () {/ / update according to the ID in the entity, other fields will not be updated if the value is null, refer to the yml configuration file UserInfoEntity userInfoEntity = new UserInfoEntity (); userInfoEntity.setId (1L) UserInfoEntity.setAge (19); userInfoService.updateById (userInfoEntity) } / * add or update user information * @ Author Sans * @ CreateTime, 2019-6-8 16:50 * / @ RequestMapping ("/ saveOrUpdateInfo") public void saveOrUpdate () {/ / if ID is null in the entity class userInfoEntity, the entity class ID value will be added (ID self-increment) / / entity class ID will be updated if the ID exists in the database If it does not exist, UserInfoEntity userInfoEntity = new UserInfoEntity () will be added UserInfoEntity.setId (1L); userInfoEntity.setAge (20); userInfoService.saveOrUpdate (userInfoEntity);} / * * Delete user information according to ID * @ Author Sans * @ CreateTime 16:52 on 2019-6-8 * / @ RequestMapping ("/ deleteInfo") public void deleteInfo (String userId) {userInfoService.removeById (userId) } / * bulk delete user information according to ID * @ Author Sans * @ CreateTime 16:55 on 2019-6-8 * / @ RequestMapping ("/ deleteInfoList") public void deleteInfoList () {List userIdlist = new ArrayList (); userIdlist.add ("12"); userIdlist.add ("13"); userInfoService.removeByIds (userIdlist) } / * Delete user information according to the specified field * @ Author Sans * @ CreateTime 16:57 on 2019-6-8 * / @ RequestMapping ("/ deleteInfoMap") public void deleteInfoMap () {/ / kay is the field name value is the field value Map map = new HashMap (); map.put ("skill", "delete"); map.put ("fraction", 10L) UserInfoService.removeByMap (map);}}
Lambda syntax is used in the controller layer
Package com.demo.drools.controller; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.demo.drools.entity.UserInfoEntity;import com.demo.drools.service.UserInfoService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping; import java.util.HashMap;import java.util.List;import java.util.Map / * TODO your comment * * @ author Yujiaqi * @ date 19:28 on 2020-12-2 * / public class UserInfoPlusController {@ Autowired private UserInfoService userInfoService / * MP extension demo * @ Author Sans * @ CreateTime 16:37 on 2019-6-8 * @ Return Map returns data * / @ RequestMapping ("/ getInfoListPlus") public Map getInfoListPage () {/ / initializes the return class Map result = new HashMap () / / query students equal to 18 years old / / equivalent SQL: SELECT id,name,age,skill,evaluate,fraction FROM user_info WHERE age = 18 QueryWrapper queryWrapper1 = new QueryWrapper (); queryWrapper1.lambda () .eq (UserInfoEntity::getAge,18); List userInfoEntityList1 = userInfoService.list (queryWrapper1); result.put ("studentAge18", userInfoEntityList1) / / query students over 5 years old and younger than 18 years old / / equivalent SQL: SELECT id,name,age,skill,evaluate,fraction FROM user_info WHERE age > 5 AND age 18 QueryWrapper queryWrapper4 = new QueryWrapper (); queryWrapper4.lambda (). Like (UserInfoEntity::getName, "small"); queryWrapper4.lambda (). Or (). Gt (UserInfoEntity::getAge,18); List userInfoEntityList4 = userInfoService.list (queryWrapper4) Result.put ("studentOr", userInfoEntityList4); / / query students who are not rated as null, and paging / / equivalent SQL: SELECT id,name,age,skill,evaluate,fraction FROM user_info WHERE evaluate IS NOT NULL LIMIT 0 IPage page 5 IPage page = new Page (); page.setCurrent (1); page.setSize (5); QueryWrapper queryWrapper5 = new QueryWrapper (); queryWrapper5.lambda (). IsNotNull (UserInfoEntity::getEvaluate) Page = userInfoService.page (page,queryWrapper5); result.put ("studentPage", page); return result;}}
The above is a small case of mybatis-plus. Mybatis-plus, like the spring data jpa framework I used before, can achieve simple additions, deletions, changes, queries, batch operations, and paging mybatis-plus without writing sql statements. The function is still relatively powerful, which can reduce us to write a lot of code. Personally, I prefer to use this mybatis-plus.
Mybatis-plus is only an enhanced version of mybatis, it does not affect the use of mybatis, we can write our custom method and sql, let's look at a small case
New method of dao layer
/ * query students greater than this score * @ Author Sans * @ CreateTime 14:28 on 2019-6-9 * @ Param page paging parameter * @ Param fraction score * @ Return IPage paging data * / IPage selectUserInfoByGtFraction (@ Param (value = "page") IPage page, @ Param (value = "fraction") Long fraction)
New method for service
/ * query students greater than this score * @ Author Sans * @ CreateTime 14:27 on 2019-6-9 * @ Param page paging parameter * @ Param fraction score * @ Return IPage paging data * / IPage selectUserInfoByGtFraction (IPage page,Long fraction)
New method of serviceImpl layer
/ * query students greater than this score * @ Author Sans * @ CreateTime 14:27 on 2019-6-9 * @ Param page paging parameter * @ Param fraction score * @ Return IPage paging data * / IPage selectUserInfoByGtFraction (IPage page,Long fraction)
New method of controller layer
/ * * MP Custom SQL * @ Author Sans * @ CreateTime 2019-6-9 14:37 * @ Return IPage paging data * / @ RequestMapping ("/ getInfoListSQL") public IPage getInfoListSQL () {/ / query students with scores greater than 60 and paging IPage page = new Page (); page.setCurrent (1); page.setSize (5) Page = userInfoService.selectUserInfoByGtFraction (page,60L); return page;}
Configure xml for our mybatis
SELECT * FROM user_info WHERE fraction > # {fraction}
The above configuration is our mybatis usage.
Mybatis plus's powerful conditional constructors queryWrapper, updateWrapper
1.QueryWrapper: the Entity object encapsulates the operation class
2.UpdateWrapper: Update conditional encapsulation for Entity object update operations
3. Format and description of each method in the use of the conditional constructor
These are all the contents of the article "how to use SpringBoot Integration Mybatis-plus". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to 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.