10

To persist I use Hibernate 6 and use on the entity:

@JdbcTypeCode(SqlTypes.JSON)
private String value;

When you save to the database, save wrapped in quotes and inside the json escape the quotes:

"{\\\"name\\\":\\\"pepito\\\", \\\"lastname\\\":\\\"perez\\\"}"

when I use the query to select value -> 'name' does not work, I do not understand why it does not save in the database in the following way:

{"name":"pepito", "lastname":"perez"}

Thanks.

2
  • 1
    for this case I had to use the lib: <groupId>com.vladmihalcea</groupId> <artifactId>hibernate-types-60</artifactId> and in the entity: @Type(JsonBinaryType.class) @Column(name = "value", columnDefinition = "jsonb") private String value; result in the db: {"name":"pepito", "lastname":"perez"} Commented Aug 18, 2022 at 23:49
  • Is that the solution, which you commented instead of creating an answer post of it? Commented Aug 19, 2022 at 5:29

3 Answers 3

8

Hibernate ORM 6.1.3.Final have fix for this issue, strings annotated with @JdbcTypeCode(SqlTypes.JSON) and @JdbcTypeCode(SqlTypes.SQLXML) will no longer be serialized to JSON/XML. Instead, they will be interpreted as plain JSON/XML to avoid the overhead of serialization/deserialization.

Reference

https://in.relation.to/2022/09/08/hibernate-orm-613-final/

Sign up to request clarification or add additional context in comments.

Comments

1

What you are seeing here is that Hibernate serializes the string as JSON. I guess it's not very useful to do that and Hibernate could instead interpret a string a plain JSON, but in the end, I would rather suggest you model this as java.util.Map instead, which is then serialized to the proper JSON representation that you expect.

Either way, I created a Hibernate issue (HHH-15458) for this as I understand that this is the way people would expect this to work when they don't care about the representation of the JSON structure in their model.

Comments

0
@Entity
  public class Entity {

  @JdbcTypeCode(SqlTypes.JSON)
  private JsonNode json;
}

@Test
@Commit
void shouldSaveJson() throws JsonProcessingException {
  ObjectMapper objectMapper = new ObjectMapper();
  JsonNode jsonMap = objectMapper.readValue(jsonEscapedString,JsonNode.class);
  Entity entity = new Entity(jsonMap);
  Entity saved = entityRepository.saveAndFlush(question);
  entityManager.clear();

  Entity fetched = entityRepository.findById(saved.getId()).orElse(null);
  Assertions.assertNotNull(fetched);
}

Instead of JsonNode you can use Map<String, Object>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.