I was trying to store some JSON as a string in a column via JPA and Spring and was following a baeldung tutorial . My code like this:
@Column
@Convert(converter = MyEntityExtentionConverter.class)
private Map<String, Object> myEntityExtention;
MyEntityExtentionConverter
is an implementation of javax.persistence.AttributeConverter<Map<String, Object>, String>
that converts the string back and forth using the Jackson ObjectMapper
.
According to mentioned tutorial this should have been it, however now I get an Error that
'Basic' attribute type should not be a map
Theoretically I could disable it by adding @SuppressWarnings("JpaAttributeTypeInspection")
to the annotations, but that feels like ignoring rather than solving the error. What am I doing wrong here?
You have to annotate prop "myEntityExtention" with @Type but is not possible to add both @Type and @Convert..
as you can see in this tutorial you have to define the json type on the top of your entity:
@Entity
@Table(name = "some_table_name")
@TypeDef(name = "json", typeClass = JsonStringType.class)
public class CustomEntity {
then add @Type annotation instead @Convert :
@Type( type = "json" )
private Map<String, Object> myEntityExtention;
be sure to add all the right dependencies/versions.
IE i'm using hibernate 5.4 so my dependencies are:
<!-- Hibernate ORM core version 5.4.21.Final (inherited from spring-boot 2.3.4)-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-hibernate5</artifactId>
<version>2.8.4</version>
</dependency>
<dependency>
<groupId>com.vladmihalcea</groupId>
<artifactId>hibernate-types-52</artifactId>
<!--for hibernate >= 5.2-->
<version>2.10.2</version>
</dependency>
</dependencies>
Look like this is an issue from IntelliJ IDEA:
https://youtrack.jetbrains.com/issue/IDEA-270687
We can use workaround by this way: Using the @SuppressWarnings("JpaAttributeTypeInspection")
annotation removes the warning.
That field is not meant to be persisted. Remove the @Column annotation and use @Transient. You are supposed to persist it as a JSON which will be done in the customerAttributeJSON, when reading from the database the customerAttributes will be populated and you can use it with DTOs.
@Entity @Table(name = "Customers") public class Customer { @Id private int id; private String firstName; private String lastName; private String customerAttributeJSON; @Transient @Convert(converter = HashMapConverter.class) private Map<String, Object> customerAttributes; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.