1. Introduction
In the MybatisPlus framework, the IService interface plays an important role.
As a general service interface, IService defines a series of methods, including query, insertion, update, delete, etc.
The definition of these methods makes it easier and more efficient to perform database operations at the service layer.
- The IService interface is a generic interface that defines a set of common basic methods, including common additions, deletions, modifications and search operations.
- For example, it provides signatures for methods such as inserting data, updating data based on primary keys, deleting data based on primary keys, querying data based on primary keys, etc.
- Users can inherit the IService interface in the customized service interface according to their own needs and business logic and implement the methods therein.
usage:
public interface UserService extends IService<User> {}
- The ServiceImpl class is the default implementation class of the IService interface, providing basic implementation details of the addition, deletion, modification and search operations.
- It uses generic parameters to standardize entity class and primary key types and implements methods defined in the IService interface.
- Users can inherit the ServiceImpl class and add or override more specific business logic in their own implementation class.
usage:
@Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {}
2. IService usage
1. Add data
// Insert a record (select field, policy insertion)boolean save(T entity); // Insert (batch)boolean saveBatch(Collection<T> entityList); // Insert (batch, limit quantity)boolean saveBatch(Collection<T> entityList, int batchSize); // There is an update record in TableId annotation, otherwise a record will be insertedboolean saveOrUpdate(T entity); // Try to update according to updateWrapper, otherwise continue to execute the saveOrUpdate(T) methodboolean saveOrUpdate(T entity, Wrapper<T> updateWrapper); // Batch modification insertionboolean saveOrUpdateBatch(Collection<T> entityList); // Batch modification insertionboolean saveOrUpdateBatch(Collection<T> entityList, int batchSize);
Can be turned onrewriteBatchedStatements=true
Parameters to improve the execution efficiency of batch processing.
2. Delete data
// Delete the record according to entity conditionsboolean remove(Wrapper<T> queryWrapper); // Delete by IDboolean removeById(Serializable id); // Delete the record according to the columnMap conditionboolean removeByMap(Map<String, Object> columnMap); // Delete (batch deletion according to ID)boolean removeByIds(Collection<? extends Serializable> idList);
3. Modify the data
// Update records according to UpdateWrapper conditions, you need to set sqlsetboolean update(Wrapper<T> updateWrapper); // Update records according to whereWrapper conditionsboolean update(T updateEntity, Wrapper<T> whereWrapper); // Select Modify according to IDboolean updateById(T entity); // Batch updates according to IDboolean updateBatchById(Collection<T> entityList); // Batch updates according to IDboolean updateBatchById(Collection<T> entityList, int batchSize);
4. Query data
Query a data
// Query by IDT getById(Serializable id); // According to Wrapper, query a record. If there are multiple results sets, an exception will be thrown, and one will be randomly taken plus a limit condition ("LIMIT 1")T getOne(Wrapper<T> queryWrapper); // According to Wrapper, query a record. This method returns more than one result and will throw an exception. If you want to get the first result by default, you can pass the second parameter to this method as false.T getOne(Wrapper<T> queryWrapper, boolean throwEx); // According to Wrapper, query a recordMap<String, Object> getMap(Wrapper<T> queryWrapper); // According to Wrapper, query a record// mapper: Conversion function, used to convert each object in the query result to the specified object type.<V> V getObj(Wrapper<T> queryWrapper, Function<? super Object, V> mapper);
Query multiple data
// Query allList<T> list(); // Query listList<T> list(Wrapper<T> queryWrapper); // Query (batch query based on ID)Collection<T> listByIds(Collection<? extends Serializable> idList); // Query (according to columnMap conditions)Collection<T> listByMap(Map<String, Object> columnMap); // Query all listsList<Map<String, Object>> listMaps(); // Query listList<Map<String, Object>> listMaps(Wrapper<T> queryWrapper); // Query all recordsList<Object> listObjs(); // Query all records<V> List<V> listObjs(Function<? super Object, V> mapper); // Query all records according to Wrapper conditionsList<Object> listObjs(Wrapper<T> queryWrapper); // Query all records according to Wrapper conditions// mapper: Conversion function, used to convert each object in the query result to the specified object type.<V> List<V> listObjs(Wrapper<T> queryWrapper, Function<? super Object, V> mapper);
Query records count()
// Query the total number of recordsint count(); // According to Wrapper conditions, query the total number of recordsint count(Wrapper<T> queryWrapper);
Page
// Unconditional pagination queryIPage<T> page(IPage<T> page); // Conditional pagination queryIPage<T> page(IPage<T> page, Wrapper<T> queryWrapper); // Unconditional pagination queryIPage<Map<String, Object>> pageMaps(IPage<T> page); // Conditional pagination queryIPage<Map<String, Object>> pageMaps(IPage<T> page, Wrapper<T> queryWrapper);
IPage is a pagination-related interface provided by MyBatis-Plus. It has an implementation class Page, which defines multiple pagination-related parameters.
- size (The number of pieces displayed per page): This parameter is usually passed to us by the front end and then encapsulated into the Page object for pagination query;
- current (Which page of data should be displayed): This parameter is usually passed to us by the front end and then encapsulated into the Page object for pagination query;
- orders(Sorting Rules Collection): Which fields are sorted by? It can be multiple, for example, if the time is the same, it can be sorted in descending order according to the user ID, and multiple fields can be added;
- total (Total number of records): refers to the total number of records in the database returned after the query is completed, and note that it does not contain data that has been logically deleted;
- records(Query paging result set data): Multiple pieces of data obtained by paging query will be stored in records. It can be seen that the object is a collection and a generic can be passed, which is the entity generic corresponding to the query data;
public class Page<T> implements IPage<T> { private static final long serialVersionUID = 8545996863226528798L; protected List<T> records; protected long total; protected long size; protected long current; protected List<OrderItem> orders; protected boolean optimizeCountSql; protected boolean searchCount; protected boolean optimizeJoinOfCountSql; protected String countId; protected Long maxLimit; /* The following omitted */ }
Page object usage demonstration:
@SpringBootTest public class ProductMapperTest { // Automatically inject the implementation class object corresponding to the productMapper interface @Autowired private ProductMapper productMapper; @Test public void testPageQuery(){ // Create a page related to the page of the page, the generic is Product, indicating that the entity class corresponding to the query result is Product Page<Product> page = new Page<>(); // Set up paging query to display the data on the second page. During the actual development process, this parameter is passed on front-end. (2); // Set up paging query to display four pieces of data per page. During the actual development process, this parameter is passed on front-end. (4); // Create a sorting field collection, and don't add it if you don't want to sort it. In actual development, you generally require sorting in descending order in time. List<OrderItem> orders = new ArrayList<>(); // Sort by price, the sorting method is descending, ASC is True for ascending order, false for descending order, and the first parameter represents the column name in the database (new OrderItem("price",false)); // Sort by production time, the sorting method is descending (new OrderItem("production_date",false)); // Add the sorted object collection to the page query object (orders); // Execute pagination query, you can create a Page object to accept the query results. // You can also use query conditional parameters page, but in fact, the final result is the same page = (page, null); // You can create a new Page object, just like the following Page<Product> productPage = (page,null); // Output the page query results to display which page is currently displayed (()); // Total number of data strips output from the page query result (()); // Data collection of output page query results (()); // Output the number of pages displayed for each page of the page query results (()); // Determine whether the two result objects in the pagination query just now are the same (page == productPage); // Output the memory address of the first page query object (page); // Output the memory address of the second paging query object (productPage); } }
Chain
Chain query demonstration:
// Chain query NormalQueryChainWrapper<T> query(); // Chain query lambda style. Note: Kotlin is not supportedLambdaQueryChainWrapper<T> lambdaQuery(); // Example:// eq Specify the conditionsquery().eq("column", value).one(); lambdaQuery().eq(Entity::getId, value).list();
Chain update demonstration:
// Chain change NormalUpdateChainWrapper<T> update(); //Chain change lambda style. Note: Kotlin is not supportedLambdaUpdateChainWrapper<T> lambdaUpdate(); // Example:// eq Specify the conditionsupdate().eq("column", value).remove(); lambdaUpdate().eq(Entity::getId, value).update(entity);
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.