Mapping MySQL JSON Fields with MyBatis-Plus
Preface
MySQL supports fields of type JSON. In comparison to string-type fields, JSON fields offer the following advantages:
- Automatic validation of JSON syntax
- Underlying support for quick access to elements within the JSON. There’s no need to read the entire string and then parse it into a JSON object.
Logically, JSON is no different from a POJO. Spring MVC has already implemented automatic conversion between the two at the Controller tier, evident in request parameters and return values. So, how can the Repository tier achieve automatic conversion?
This article demonstrates achieving seamless, non-intrusive mapping (ORM) between JSON and POJO using MyBatis-Plus in the Repository tier.
Demo
Table
1 | CREATE TABLE `person` ( |
Dependencies
1 | <dependency> |
entity
1 |
|
The PersonLog
here is the focal point of our discussion, aiming to map it to JSON.
The Person
class needs two annotations, usually used together:
TableName#autoResultMap
: Responsible for converting JSON to POJO during query.
TableField#typeHandler
: Responsible for converting POJO to JSON during insert. Since spring-web-starter has already imported the Jackson dependency, we can directly use JacksonTypeHandler
.
mapper.xml
1 |
|
In the mapper file, specify the full class name of the typeHandler
for the log
field.
Testing
1 |
|
Service tier is omitted.
1 |
|
Test both methods; if no errors occur, it indicates success. We can also check the database after insertion.
The non-intrusive ORM mentioned in the Preface implies that we don’t need to manually execute the conversion between JSON and PersonLog
in the code.
Conclusion
This article demonstrates achieving seamless, non-intrusive mapping between JSON and POJO using MyBatis-Plus in the Repository tier.
My exploration of this issue originated from the requirements of a business logic during my internship. When I searched for information online, I found that the descriptions in the posts were not quite complete or intuitive. Therefore, I documented the solution and wrote this article.