Most developers who use Mybatis will encounter a problem, which is to write a large amount of SQL in the xml file. In addition to special business logic SQL, there are also a large number of SQL with similar structures. Moreover, when the database table structure changes, all corresponding SQL and entity classes need to be changed. The impact of this workload and efficiency may be the barrier between adding, deleting, modifying and checking programmers and real programmers. At this time, the general mapper came into being...
What is a universal mapper
General Mapper is a plug-in based on Mybatis to solve the problem of adding, deleting, modifying and searching of single tables. Developers do not need to write SQL or add methods to DAO. As long as they write the entity class well, they can support corresponding methods of adding, deleting, modifying and searching.
How to use
Taking MySQL as an example, suppose there is such a table:
CREATE TABLE `test_table` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT '', `create_time` datetime DEFAULT NULL, `create_user_id` varchar(32) DEFAULT NULL, `update_time` datetime DEFAULT NULL, `update_user_id` varchar(32) DEFAULT NULL, `is_delete` int(8) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
The primary key is id, which increases by itself. Here is a table as an example to introduce how to use a universal mapper.
Maven dependencies
<!-- General Mapper --><dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId> <version>3.3.9</version></dependency>
SpringMVC configuration
<!-- General Mapper --><beanclass="tk.mybatis.spring.mapper.MapperScannerConfigurer"> <propertyname="basePackage"value="cn.com.bluemoon.bd.service.spider.dao"/> <propertyname="properties"> <value> mappers=tk.mybatis.mapper.common.Mapper </value> </property></bean>
Note that tk.mybatis.spring.mapper.MapperScannerConfigure is used here to replace the original Mybatis org.mybatis.spring.mapper.MapperScannerConfigurer .
Parameters available:
In most cases, these parameters will not be used, and you can study them yourself if you have special circumstances.
How to write entities
Remember one principle: Number of fields in entity class >= Number of fields that need to be operated in the database table. By default, all fields in the entity class are operated as fields in the table, and if there are additional fields, the @Transient annotation must be added.
@Table(name = "test_table")public class TestTableVOimplements Serializable{ private static final long serialVersionUID = 1L; @Id @GeneratedValue(generator = "JDBC") private Long id; @Transient private String userId; private String name; private Timestamp createTime; private String createUserId; private Timestamp updateTime; private String updateUserId; private Integer isDelete; // Omit get, set... }illustrate:
How to write DAO
In traditional Mybatis writing, the DAO interface needs to be associated with the Mapper file, that is, SQL needs to be written to implement methods in the DAO interface. In general mapper, DAO only needs to inherit a common interface to have rich methods:
Inheriting the generic mapper, generics must be specified
public interface TestTableDaoextends Mapper<TestTableVO>{}Once you inherit Mapper, the inherited Mapper has all the common methods of Mapper:
Select
Method: List<T> select(T record);
Note: Query based on the attribute value in the entity, and use equal signs for query conditions
Method: T selectByPrimaryKey(Object key);
Note: Query based on the primary key field. The method parameters must contain complete primary key attributes. The query conditions use equal signs.
Method: List<T> selectAll();
Note: Query all results, the select(null) method can achieve the same effect
Method: T selectOne(T record);
Note: Querying according to the properties in the entity, there can only be one return value, and multiple results are thrown. The query conditions use equal signs.
Method: int selectCount(T record);
Note: Query the total number of attributes in the entity, and use the equal sign for the query conditions.
Insert
Method: int insert(T record);
Note: Save an entity, the null attribute will also be saved, and the database default value will not be used.
Method: int insertSelective(T record);
Note: Save an entity, the null attribute will not be saved, and the database default value will be used.
Update
Method: int updateByPrimaryKey(T record);
Note: Update all fields of the entity according to the primary key, the null value will be updated
Method: int updateByPrimaryKeySelective(T record);
Description: Update the value whose attribute is not null according to the primary key
Delete
Method: int delete(T record);
Note: Delete according to entity attributes as conditions, use equal signs for query conditions
Method: int deleteByPrimaryKey(Object key);
Note: Delete according to the primary key field, method parameters must contain complete primary key attributes
Example method
Method: List<T> selectByExample(Object example);
Description: Query according to Example conditions
Key point: This query supports specifying query columns through the Example class and specifying query columns through the selectProperties method.
Method: int selectCountByExample(Object example);
Description: Query the total number according to Example conditions
Method: int updateByExample(@Param("record") T record, @Param("example") Object example);
Note: Update all properties contained in entity record according to Example conditions, and the null value will be updated.
Method: int updateByExampleSelective(@Param("record") T record, @Param("example") Object example);
Description: Updating the entity record according to Example conditions contains the property value that is not null
Method: int deleteByExample(Object example);
Description: Delete data according to Example conditions
Used in the code
Inject dao in service and it is ready to use.
@Autowiredprivate TestTableDao testTableDao;
The following is a general way of writing:
New
TestTableVO vo = new TestTableVO();// Omit the setting properties for vo...int row = testTableDao.insertSelective(vo);
Revise
TestTableVO vo = new TestTableVO();// Omit the setting properties for vo...int row = testTableDao.updateByPrimaryKeySelective(vo);
Query a single
TestTableVO vo = new TestTableVO();vo.setId(123L);TestTableVO result = testTableDao.selectOne(vo);
Conditional query
// Create ExampleExample example = new Example(TestTableVO.class);// Create CriteriaExample.Criteria criteria = example.createCriteria();// Add condition criteria.andEqualTo("isDelete", 0);criteria.andLike("name", "%abc123%");List<TestTableVO> list = testTableDao.selectByExample(example); Summarize
The principle of general mapper is to obtain the information of entity classes through reflection and construct the corresponding SQL. Therefore, we only need to maintain the entity classes, which provides great convenience for coping with complex and changeable needs. The above description is just a simple usage of general mapper. In actual projects, we should still encapsulate a larger, more general and better-used method based on the general mapper based on the business.
With Spring Boot configuration
Maven
<!--mybatis--><dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version></dependency><!--mapper--><dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>1.1.4</version></dependency>
application.properties configuration
#mapper#mappers Comma separated mappper.mappers=tk.mybatis.mapper.common.Mappermapper.not-empty=falsemapper.identity=MYSQL
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.