I. Introduction to MP
1, a brief introduction
MybatisPlus on the basis of Mybatis only do enhancement, do not change, just like red and blue people in Contra.
It’s official: Designed to simplify development
2. The characteristics of MP
3. Supported databases
- Mysql, Mariadb, Oracle, DB2, H2, HSQL, SQLite, PostgresQL, SQLServer, Presto
- Dream database, Virtual valley database, da Jincang database
MybatisPlus is easy to use
1. Introduce Maven dependencies
2. Write the application.yml file
3. Write the entity class User
-
Lombok is used here to simplify get, set, and construction
-
@tablename annotation: specifies the TableName of the entity class, usually added in the core configuration file
mybatis-plus: global-config: db-config: table-prefix: tb_
TableId Comment: Set the ID generation policy.
@Data @NoArgsConstructor @AllArgsConstructor @TableName("tb_user") public class User { @TableId(type = IdType.AUTO) private Long id; private String userName; @tableField (select * from TableField) private String password; private String name; private Integer age; @tableField (value = "email") private String mail; @TableField(exist = false) private String address; SQL > select * from db;Copy the code
BaseMapper< entity class >
@Repository
public interface UserMapper extends BaseMapper<User> {
}
Copy the code
This is similar to SpringDataJpa, except that the primary key type is no longer passed in
BaseMapper can look at the method: have to say that the plug-in is easy to use, annotations are Chinese, do not worry about not understand
Public interface BaseMapper<T> extends Mapper<T> {/** ** inserts a record ** @param entity */ int insert(T entity); /** * @param ID Primary key ID */ int deleteById(Serializable ID); /** * Based on the columnMap condition, * * @param columnMap columnMap Object */ int deleteByMap(@param (Constants.COLUMN_MAP) map <String, Object> columnMap); /** * according to entity condition, Int delete(@param (Constants. Wrapper) Wrapper<T> wrapper); int delete(@param (Constants. Wrapper) wrapper <T> wrapper); ** @param idList Primary key ID list (can't be null and empty) */ int deleteBatchIds(@param (Constants.COLLECTION)) Collection<? extends Serializable> idList); /** * Change based on ID ** @param entity Entity object */ int updateById(@param (Constants. Entity) T entity); /** * according to whereEntity condition, Update record * * @param Entity entity object (set conditional value, can be null) * @param updateWrapper entity object encapsulates the action class (can be null, the entity inside is used to generate where statement) */ int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper); @param ID Primary key ID */ T selectById(Serializable ID); /** List<T> selectBatchIds(@param (Constants.COLLECTION)) /** @param idList primary key ID List (can't be null and empty) */ List<T> selectBatchIds(@param (Constants.COLLECTION) Collection<? extends Serializable> idList); List<T> selectByMap(@param (Constants.COLUMN_MAP)) ** @param (Constants. Map<String, Object> columnMap); /** * according to entity condition, Query a record * * @param queryWrapper Entity object encapsulates the operation class (which can be null) */ T selectOne(@param (Constants.WRAPPER) WRAPPER <T> queryWrapper); /** * according to the Wrapper condition, * * @param queryWrapper Entity object encapsulates operation class (can be null) */ Integer selectCount(@param (Constants.WRAPPER) WRAPPER <T> queryWrapper); /** * according to entity condition, * * @param queryWrapper Entity object encapsulates operation class (can be null) */ List<T> selectList(@param (Constants.WRAPPER) WRAPPER <T> queryWrapper); /** * according to the Wrapper condition, * * @param queryWrapper entity object encapsulates operation class (can be null) */ List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /** * query all records from the Wrapper condition * <p> Return only the value of the first field </p> * * @param queryWrapper Entity Object encapsulates the operation class (can be null) */ List<Object> selectObjs(@param (Constants.wrapper)) Wrapper<T> queryWrapper); /** * according to entity condition, * * @param Page paging query criteria (can be rowbound.default) * @param queryWrapper entity object (can be null) */ IPage<T> selectPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /** * according to the Wrapper condition, * * @param queryWrapper */ IPage<Map<String, Object>> selectMapsPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper); }Copy the code
5. Write test classes to test CRUD operations
@RunWith(SpringRunner.class) @SpringBootTest public class TestUserMapper { @Autowired private UserMapper userMapper; @Test public void testInsert() { User user = new User(); user.setMail("[email protected]"); user.setAge(12); User. Elegantly-named setName (" zhang SAN's 123 "); user.setPassword("123"); user.setUserName("zahngsan"); int insert = this.userMapper.insert(user); System.out.println(insert); System.out.println(user.getid ())); } @Test public void testSelectById() { User user = this.userMapper.selectById(1L); System.out.println(user); }Copy the code
Summary:
1. Added:
Insert () is used to pass in the entity-class object, which returns the number of affected rows. The newly added data is reencapsulated into the User object, and the id value can be directly obtained
2. Delete:
There are four methods of deletion provided by MP
Delete (Wrapper Wrapper) : Deletes according to the conditions set in Wrapper
DeleteBatchIds: deletes data in batches by ID
DeleteById: Deletes data by ID
DeleteByMap: deletes data based on the map. The relationship between conditions is and
3. Modification:
Update: Pass in the User entity and wrapper rules for modification
UpateById: The user entity is passed in and deleted according to the ID in the entity
4, the query
- SelectList: Queries based on incoming Wrapper rules
- SelectPage: Paging queries based on incoming Ipage objects, wrapper rules
- SelectOne: Returns a single object based on the query criteria passed in
- SelectBatchIds: Queries ids in batches based on incoming IDS
- SelectById: Returns a single object based on the id passed in
Three: Advanced integration of MybatisPlus
1, paging
1.1. Simple paging
With MP’s built-in paging plug-in, it’s no longer necessary to write your own limit business logic, making paging easier and just focusing on the data
Paging uses the selectPage method, passing in the Page object and the criteria for the query
Page class constructor parameters: current: current Page number, size: Page size
1.2. Paging + sorting
You only need to define the collation rules in the Wrapper
2, sorting,
You only need to customize the collation rules in the Wrapper
Here’s a look at the source rules in the Wrapper:
/** * ignore */ default Children orderByAsc(R column) { return orderByAsc(true, column); } /** * ignore */ default Children orderByAsc(R... columns) { return orderByAsc(true, columns); } /** * ORDER BY... ASC * < P > example: orderByAsc("id", "Name ")</p> * * @param condition Execution condition * @param columns array * @return children */ default children orderByAsc(Boolean) condition, R... columns) { return orderBy(condition, true, columns); } /** * ignore */ default Children orderByDesc(R column) { return orderByDesc(true, column); } /** * ignore */ default Children orderByDesc(R... columns) { return orderByDesc(true, columns); } /** * ORDER BY... DESC * <p> orderByDesc("id", "Name ")</p> * * @param condition Execution condition * @param columns array * @return children */ default children orderByDesc(Boolean) condition, R... columns) { return orderBy(condition, false, columns); } /** * ORDER BY... * < p > example: orderBy(true, "id", "Name ")</p> * * @param condition Condition * @param isAsc is an ASC sort * @param columns array * @return children */ children orderBy(boolean condition, boolean isAsc, R... columns);Copy the code
3. Logical query
@Test public void testOr() { QueryWrapper<User> wrapper = new QueryWrapper<>(); Wrapper.eq ("name", "wang Five ").or().eq("age", 21); //SELECT id,user_name,password,name,age,email FROM tb_user ORDER BY age DESC List<User> users = this.userMapper.selectList(wrapper); for (User user : users) { System.out.println(user); }}Copy the code
4, Select
In MP, all data is queried by default. Select can be used to specify which field value is required
@Test public void testSelect() { QueryWrapper<User> wrapper = new QueryWrapper<>(); / / the specified query field wrapper. Eq (" name ", "detective".) or (.) eq (" age ", 21). Select (" id ", "name", "age"); List<User> users = this.userMapper.selectList(wrapper); for (User user : users) { System.out.println(user); }}Copy the code
Four: MybatisPlus super easy to use plug-in
MybatisX is a quick development plugin based on IDEA, designed for efficiency. Setup method: Open IDEA, go to File -> Settings -> Plugins -> Browse Repositories, enter MyBatisx search and install.
Function:
- Java and XML jump back
- The Mapper method automatically generates XML
Today is the first to share here, remember to like + follow oh ~