Issues using multiple custom type handlers

76 views
Skip to first unread message

Thomas Stallon

unread,
Feb 1, 2021, 3:15:16 AM2/1/21
to mybatis-user
A very common use case:
Suppose there's an entity called "MyEntity.java" like this.
There's three typical attributes in it. An objectA, an objectB, and a list of objectA. I need to serialize them all as a json format into the database, which means that I have to define my own type handler, as below.
But now there's a conflict.
I have to set the @MappedTypes for my type handlers, as Jackson needs the type-reference to which it deserializes into, and when Mybatis instantiates the type handlers, it just assigns to the generic with the classes defined in @MappedTypes.value one by one, which means that value wrote afterwards would overwrite those wrote forwards. 
That is, for example, ALL_TYPE_HANDLER_MAP will only persist MyObjectTypeHandler<ObjectB> for class name "MyObjectTypeHandler", which means that I cannot use MyObjectTypeHandler for attribute objectA manually.
Meanwhile, in map TYPE_HANDLER_MAP, MyListTypeHandler<ObjectA> overwrites MyObjectTypeHandler<ObjectA> with key "ObjectA", which means that I cannot use MyObjectTypeHandler for attribute objectA automatically.

Codes shown below.
MyEntity.java
MyObjectTypeHandler.java
MyListTypeHandler.java
MyEntityDAO.xml

Thomas Stallon

unread,
Feb 1, 2021, 3:17:04 AM2/1/21
to mybatis-user
Edit: there's some bugs in MyEntityDAO.xml, but they has nothing to do with the issue.

2021年2月1日月曜日 16:15:16 UTC+8 Thomas Stallon:

Guy Rouillier

unread,
Feb 1, 2021, 4:13:59 AM2/1/21
to MyBatis User
Without spending a lot of time with the code you provided, an apparent simple solution would be to just provide a separate TypeHandler for ObjectA an ObjectB.  Perhaps not as elegant as using generics, but gets you where you want to go.

--
Guy Rouillier
--
You received this message because you are subscribed to the Google Groups "mybatis-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mybatis-user...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/mybatis-user/1ff5bd44-53c0-4e41-9cf1-e8ff0db4d072n%40googlegroups.com.

Thomas Stallon

unread,
Feb 2, 2021, 12:16:27 PM2/2/21
to mybatis-user
Yeah that's an apparent solution, but quite ugly because in a big project, there's tens of thousands of json Objects, and I have to write separate type handlers for them all. That doesn't cost much to code ( as I can extends the same MyBaseJsonTypeHandler.class), but surely increase the numbers of classes by a lot.

2021年2月1日月曜日 17:13:59 UTC+8 Guy Rouillier:
Reply all
Reply to author
Forward
0 new messages