Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to customize the type handler for collection types by Mybatis-Plus

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "Mybatis-Plus how to customize the type handler of collection type". The content of the explanation in this article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought slowly and deeply, and study and learn "Mybatis-Plus how to customize the type handler of collection type".

1. Cooperate with xml file

TypeHandler

/ * description: fastjson's collection object type handler maps the json field in the mysql table to the {@ code List} attribute in the entity class * compared with the FastjsonTypeHandler that comes with MP, the built-in type handler will resolve all {@ code List} to {@ code List}, * so that when traversing the objects, the get and set methods of the object properties will send type conversion JsonObject- >?, which is a conversion error. * the processor must be used with xml files, otherwise the object type to be parsed cannot be obtained, and it cannot be used with {@ link com.baomidou.mybatisplus.annotation.TableField} * included with MP. By default, @ TableField sets JavaType to the type of field, and if it is List, type = List.class, so the generics cannot be specified, and the type conversion will become JsonObject. * usage: * {@ code * 1. Use the annotation @ TableName on the entity class (value = "table name", resultMap = "id of resultMap in the xml file") * 2.xml file to customize resultMap and set the fields that need to be converted by JSON * * 3. Usage on custom methods * @ Mapper * public interface DemoDao extends BaseMapper {* @ Select ("select * from demo where demo_id = # {demoId}") * @ ResultMap (value = "id of resultMap in xml file") * List selectListByDemoId (Long demoId); *} * * / @ Slf4j@MappedJdbcTypes (value = JdbcType.VARCHAR) public class FastJsonArrayTypeHandler extends AbstractJsonTypeHandler type Public FastJsonArrayTypeHandler (Class type) {if (log.isTraceEnabled ()) {log.trace ("FastjsonTypeHandler (" + type + ")");} Assert.notNull (type, "Type argument cannot be null"); this.type = type;} @ Override protected List parse (String json) {return JSON.parseArray (json, type) / / be careful not to use parseObject method} @ Override protected String toJson (List obj) {return JSON.toJSONString (obj, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty);}}

Xml file

Dao

Mapperpublic interface DemoDao extends BaseMapper {@ Select ("select * from demo where demo_id = # {demoId}") @ ResultMap (value = "demoMap") List selectListByPlanId (Long demoId);}

Entity

@ Data@TableName (value = "demo", resultMap = "demoMap") public class DemoEntity implements Serializable {private static final long serialVersionUID =-1L; / * * primary key * / @ TableId private Long id; private Long demoId / * json field * / private List demoInfo;} 2. Manual registration

TypeHandler

Slf4j@MappedJdbcTypes (value = JdbcType.VARCHAR) public class FastJsonArrayTypeHandler extends AbstractJsonTypeHandler {private TypeReference type; public FastJsonArrayTypeHandler (TypeReference type) {this.type = type;} @ Override protected Object parse (String json) {return JSON.parseObject (json, type);} @ Override protected String toJson (Object obj) {return JSON.toJSONString (obj, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty);}}

Initialization, the remaining bean and dao do not require additional configuration

/ * description: initialize configuration * manually register type processor * / @ Componentpublic class InitConfig implements CommandLineRunner {public static final com.alibaba.fastjson.TypeReference F_DEMO_INFO = new com.alibaba.fastjson.TypeReference () {}; public static final TypeReference M_DEMO_INFO = new TypeReference () {} / / factory injected during mp auto-assembly, which can be used to obtain the configuration properties of mybatis. Here, it is used to obtain the registrar private final SqlSessionFactory factory; public InitConfig (SqlSessionFactory factory) {this.factory = factory of the type processor. } / * registered type processor * {@ code * 1.List type processor *. * * @ param args incoming main method arguments * @ throws Exception on error * / @ SuppressWarnings ("all") @ Override public void run (String...) Args) throws Exception {TypeHandlerRegistry typeHandlerRegistry = factory.getConfiguration () .getTypeHandlerRegistry (); typeHandlerRegistry.register (M_DEMO_INFO, new FastJsonArrayTypeHandler (F_DEMO_INFO));}}

The defect of the current method 2: although there is no problem with the addition and query, when performing the update operation included with MP, the parameterMap parameter type is Object and will not be processed by custom TypeHandler. Finally, it will directly set the json object (update demo., demo_info = JSON object.) resulting in an error.

Thank you for your reading, the above is the content of "Mybatis-Plus how to customize the type handler of the collection type". After the study of this article, I believe you have a deeper understanding of the problem of how to customize the type handler of the collection type of Mybatis-Plus, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report