Add custom java objects using jsonb in spring-boot

Published On: 31 March 2022.By .
  • Digital Engineering

Scratch the NoSQL Surface with Spring Boot and PostgreSQL’s JSONB Data Structure

NoSQL databases are, as the name says, databases that do not store their data with relationships. There are many types of NoSQL databases: graph , key-value stores, document, etc. Generally speaking, one of the most significant advantages of this kind of database is the lack of schema enforcement (you can mix a different kind of data), different levels of data consistency and better performance in some cases.

PostgreSQL adopted some data types to handle JSON data inside its data structures. This datatype is called JSONB.

  • To fully work with JSONB in Spring Data JPA (Hibernate) project with Vlad Mihalcea’s hibernate-types lib you should just add the following dependency in pom.xml:
 

  • Then use its types in your entities, for example:
The @TypeDef annotations can be applied to a base entity class.

To store the Option object in a jsonb PostgreSQL column, we just need to annotate the options property with @Type(type = “jsonb”).

The Entity defines basic properties (e.g. Id) and customs Hibernate types, among which, we are interested in the JsonBinaryType one.

JSONB helps to maps any given Java object on a binary JSON column type.

 

  • Then you will be able to use, for example, a simple JpaRepository to work with your objects:

 

 

Add some values to entity.

 

Now we can Retrieve values from the entity.

 

PostgreSQL has been supporting JSON types since version 9.2. There are two types that can be used:

  • json
  • jsonb

Both PostgreSQL JSON types need to be materialised using a binary data format, but the generic JsonType can handle this just fine.

Conclusion

The Hibernate Types support for JSON column mapping is very useful, and you can use it to map entity attributes that are either POJO, String, or even JsonNode.

The best thing about the Hibernate Types project is that it offers support for Oracle, SQL Server, PostgreSQL, or MySQL JSON column types.

Related content

That’s all for this blog

Go to Top