Add custom java objects using jsonb in spring-boot
- Digital Engineering
Add custom java objects using jsonb in spring-boot
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:
1 2 3 4 5 |
<dependency> <groupId>com.vladmihalcea</groupId> <artifactId>hibernate-types-52</artifactId> <version>2.3.4</version> </dependency> |
- Then use its types in your entities, for example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
@Data @NoArgsConstructor @Entity @Table(name = "entity") @TypeDef(name = "jsonb", typeClass = JsonBinaryType.class) public class Entity { @Id <span>@GeneratedValue</span>(strategy = GenerationType.<span>IDENTITY</span>) private Long id; private String name; @Type(type = "jsonb") @Column(columnDefinition = "jsonb") private List<Option> options; } |
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:
1 2 |
public interface EntityDao extends JpaRepository<Entity, Integer> { } |
Add some values to entity.
1 2 3 4 5 |
entityDao.save(new Entity( "entity_name", asList(new Option("option1"), new Option("option2")) ) ); |
Now we can Retrieve values from the entity.
1 2 |
Entity result = EntityDao.findById(1); List<String> options = result.getOptions(); |
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
Auriga: Leveling Up for Enterprise Growth!
Auriga’s journey began in 2010 crafting products for India’s