Provide support for JSON like field types in any Database. Note, that I developed this handler with PostgreSql in mind, but it looks like it can be used with any other database even without JSON support.
You should be able to use any Jackson version compatible with API version >= 2.6.0.
Because JDBC does not support JSON types, it transfer JSON to/from database as a string. It serialize JSON to string on save and deserialize from string on read. This feature means that we are really do not care if our DB can support JSON or not.
There are 2 handlers available:
- TreeNodeTypeHandler - work only with ArrayNode and ObjectNode only via TreeNode interface
- JsonNodeValueTypeHandler - value wrapper around JsonNode
Type handlers return lazy wrapper instead of already parsed Node representation. It is waiting for you to call any of its methods - only then it will read JSON into structure. But this approach may lead to unexpected runtime exceptions in a case if your database will return invalid JSON string.
I just want to avoid some complexity by relying on MissingNode and not nullable results.
Just look here.
class Dto {
JsonNodeValue value1;
TreeNode value2;
// ... Some getters and setters
}
// Note that in DB value1 and value2 columns are null or empty strings
Dto row = dtoMapper.get();
// But actually you have JsonNodeValue wrapper and it is not null
assert row.getValue1().isNotPresent();
// Eventually you will find that you are dealing with MissingNode
assert row.getValue1().get().isMissingNode();
assert row.getValue2().isMissingNode();
You can add this artifact to your project using JitPack.
All versions list, instructions for gradle, maven, ivy etc. can be found by link above.
To get latest commit use -SNAPSHOT instead version number.
In result map configuration you should use:
javaType="com.fasterxml.jackson.core.TreeNode"
javaType="com.fasterxml.jackson.databind.JsonNode"
You should not configure anything if you want to use TreeNode types as arguments in your mapper functions, but keep in mind that handler only expect objects of type ArrayNode or ObjectNode for TreeNodeTypeHandler. And JsonNode for JsonNodeValueTypeHandler.
<!-- mybatis-config.xml -->
<typeHandlers>
<typeHandler handler="com.github.jneat.mybatis.TreeNodeTypeHandler"/>
<typeHandler handler="com.github.jneat.mybatis.JsonNodeValueTypeHandler"/>
</typeHandlers>
Or you can use package search
<!-- mybatis-config.xml -->
<typeHandlers>
<package name="com.github.jneat.mybatis"/>
</typeHandlers>
<bean id="SomeId" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- your configuration -->
<property name="typeHandlersPackage" value="com.github.jneat.mybatis" />
</bean>