Skip to content
Advertisement

Mapping java.lang.String type to Postgres JSON Type

My question is related to the following question Mapping postgreSQL JSON column to Hibernate value type and although the answer works when I test passing a string to psql in postgres it doesn’t work when passing a string from my Java code.

I am using MyBatis to map sql to the postgres database via Spring injection.

Here is my Java interface for MyBatis and the method I am having problems mapping to a Postgres JSON column is the updateState() method.

JavaScript

Following is my mapper class:

JavaScript

Following is the Spoke bean class:

JavaScript

Following is the code for my applicationContext.xml file

JavaScript

Following is the db.properties file

JavaScript

Following is the mybatis-config.xml file

JavaScript

Here is the spokes table which contains the json field

JavaScript

Next create function for string to json conversion

JavaScript

Create cast

JavaScript

This works when doing conversion from within my psql but not from the java side

Following are some tests showing the function and cast working via psql for a table called xxx and also the fact that invalid json is not accepted

JavaScript

Following is my test class:

JavaScript

So it all seems to be working fine but when I try to run the Java side I get the cast exception as shown in the Stack trace below:

JavaScript

Advertisement

Answer

Adding stringtype=unspecified to my jdbc connection string as https://stackoverflow.com/users/1499698/pozs suggested worked:

JavaScript

Doing this I could also remove the function and cast from a string to json.

I also tested the change by passing invalid json to the JSON column.

As hoped when doing so I got a DataIntegrityViolationException as I would expect from that test

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement