Attach mybatis plus At the beginning of the official website
1, Introduction
MyBatis-Plus (opens new window) (MP for short) is a MyBatis (opens new window) On the basis of MyBatis, the enhancement tool of MyBatis only makes enhancements without changes, and is born to simplify development and improve efficiency
2, Characteristics
- No invasion: only enhance without change, and the introduction of it will not affect the existing project, as smooth as silk
- Low loss: the basic CURD will be automatically injected upon startup, with basically no loss of performance, and direct object-oriented operation
- Powerful crud operation: built in general Mapper and general Service, most CRUD operations of a single table can be realized through only a few configurations, and there is a more powerful condition builder to meet various use needs
- Support Lambda form calls: through Lambda expressions, you can easily write various query conditions without worrying about wrong fields
- Support automatic generation of primary key: support up to four primary key strategies (including distributed unique ID generator Sequence), which can be freely configured to perfectly solve the primary key problem
- Support ActiveRecord mode: support ActiveRecord formal calls. Entity classes only need to inherit Model classes to perform powerful CRUD operations
- Support custom global general operations: support global general method injection (Write once, use anywhere)
- Built in code generator: code or Maven plug-in can be used to quickly generate Mapper, Model, Service, Controller layer code, support template engine, and have more customized configurations for you to use
- Built in paging plug-in: Based on MyBatis physical paging, developers do not need to care about specific operations. After configuring the plug-in, writing paging is equivalent to ordinary List query
- The paging plug-in supports a variety of databases: MySQL, MariaDB, Oracle, DB2, H2, HSQL, SQLite, Postgre, SQLServer and other databases
- Built in performance analysis plug-in: it can output SQL statements and their execution time. It is recommended to enable this function during development and testing to quickly find out slow queries
- Built in global interception plug-in: it provides intelligent analysis and blocking of full table delete and update operations, and can also customize interception rules to prevent misoperation
3, Partial configuration
1. Configure the application.yml file
spring: # Configure data source information datasource: # Configure data source type type: com.zaxxer.hikari.HikariDataSource # Configure connection database information driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf- 8&useSSL=false username: root password: 123456
2. Configure log output in application.yml
# Configure MyBatis logs mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
4, Basic CRUD
1.BaseMapper
The built-in basic CRUD of mybatis plus can be realized by inheriting BaseMapper<t> through the interface in dao. The BaseMapper code is as follows:
public interface BaseMapper<T> extends Mapper<T> { /** * Insert a record * * @param entity Entity object */ int insert(T entity); /** * Delete by ID * * @param id Primary key ID */ int deleteById(Serializable id); /** * Delete records according to columnMap conditions * * @param columnMap Table field map object */ int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap); /** * Delete records according to entity conditions * * @param queryWrapper Entity object encapsulates operation class (null able, and entity in it is used to generate where statement) */ int delete(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /** * Delete (batch delete according to ID) * * @param idList List of primary key ID S (cannot be null and empty) */ int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList); /** * Modify according to ID * * @param entity Entity object */ int updateById(@Param(Constants.ENTITY) T entity); /** * Update records according to whereEntity conditions * * @param entity Entity object (set condition value, nullable) * @param updateWrapper Entity object encapsulates operation class (null able, and entity in it is used to generate where statement) */ int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper); /** * Query by ID * * @param id Primary key ID */ T selectById(Serializable id); /** * Query (batch query according to ID) * * @param idList List of primary key ID S (cannot be null and empty) */ List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList); /** * Query (according to columnMap condition) * * @param columnMap Table field map object */ List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap); /** * Query a record according to the entity condition * * @param queryWrapper Entity object encapsulates operation class (null able) */ T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /** * Query the total number of records according to the Wrapper condition * * @param queryWrapper Entity object encapsulates operation class (null able) */ Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /** * Query all records according to entity conditions * * @param queryWrapper Entity object encapsulates operation class (null able) */ List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /** * Query all records according to Wrapper conditions * * @param queryWrapper Entity object encapsulates operation class (null able) */ List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /** * Query all records according to Wrapper conditions * <p>Note: only the value of the first field is returned</p> * * @param queryWrapper Entity object encapsulates operation class (null able) */ List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /** * Query all records (and turn the page) according to the entity condition * * @param page Paging query criteria (can be RowBounds.DEFAULT) * @param queryWrapper Entity object encapsulates operation class (null able) */ <E extends IPage<T>> E selectPage(E page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /** * Query all records (and turn the page) according to the Wrapper conditions * * @param page Paging query criteria * @param queryWrapper Entity object encapsulation operation class */ <E extends IPage<Map<String, Object>>> E selectMapsPage(E page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper); }
2. insert() as an example:
@Test public void testInsert(){ User user = new User(null, "Zhang San", 20, "zhangsan@qq.com"); int result = userMapper.insert(user); System.out.println("The number of inserts is:"+result); }
The returned result is 1, where null is the id field, and mybatis plus will generate id through the snowflake algorithm
3.IService
userService.count() / / total number of records
In addition, record the basic java mistakes made today
Arrays.asList() is a method that converts an array into a set and returns a fixed length List set
Note: the list after creation aggregate The operation of changing the set, such as add and remove, is not supported, and an error will be reported. Traversal is supported because its length is fixed and cannot be changed.
If you want to change the list set, use the conventional method list<t> list = new ArrayList < >;
V. common notes
1.@TableName
The table name of the default operation is consistent with the entity class name. If it is inconsistent, an error will be reported.
@TableName is used to annotate the entity class, which can solve the problem that the class name of the entity class type is inconsistent with the table name of the table to be operated
It can also be solved through yml global configuration
2.@TableId
@TableId identifies the attribute in the entity class as the primary key
3.@TableField
@TableField is used for annotation on attributes in entity classes to solve the inconsistency between attributes and fields in database tables
4.@TableLogic
@TableLogic logical deletion, unlike real deletion, will delete the values in the database. The real implementation behind the test deletion function is modification. Modify the annotated fields, and then test the query function, and you will find that the modified data will not be queried.
@TableLogic @ApiModelProperty(value = "Delete tag,1:Deleted,0:normal") private String isDeleted;
6, Common constructors
1.AbstractWrapper
Official note: the parent classes of QueryWrapper(LambdaQueryWrapper) and UpdateWrapper(LambdaUpdateWrapper) are used to generate the where condition of sql, and the entity attribute is also used to generate the where condition of sql
Note: the where condition generated by entity has no associated behavior with the where condition generated by each api
Such details can be found in official documents
2.QueryWrapper
Official description:
Inherited from AbstractWrapper, its internal attribute entity is also used to generate where conditions
And LambdaQueryWrapper. You can use new querywrapper () Lambda() method get