I'm working on a Spring Boot application that needs to map a JSON column in my MySQL database to a Java entity using Hibernate. I am using the @Type annotation from the Hibernate Types library, but I'm encountering an issue with the type attribute in the annotation.
Here is my entity class:
package com.csbodima.demo.entity;
import com.vladmihalcea.hibernate.type.json.JsonType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;
import org.hibernate.annotations.TypeDefs;
import java.util.ArrayList;
@Entity
@Table(name = "customer")
@TypeDefs({
@TypeDef(name = "json", typeClass = JsonType.class)
})
public class Customer {
@Id
@Column(name = "customer_id", length = 50)
private int customerId;
@Column(name = "customer_name", length = 200, nullable = false)
private String custoemrName;
@Type(type = "json")
@Column(name = "contact_numbers", columnDefinition = "json")
private ArrayList contactNumbers;
}
I am using the following dependencies in my pom.xml:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.vladmihalcea</groupId>
<artifactId>hibernate-types-5</artifactId>
<version>2.16.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
Before running the application error shows in the "type" attribute in the @Type annotation.
When I run the application, I encounter an error related to the @Type annotation:
Cannot resolve method 'type'
If you are using hibernate 6, you can use the JdbcTypeCode annotation with the value of SqlTypes.JSON
@Entity
@Table(name = "customer")
public class Customer {
...
@Column(name = "contact_numbers")
@JdbcTypeCode(SqlTypes.JSON)
private ArrayList contactNumbers;
}
You can find a detailed example in this article.