Have you tried using the Jackson library to assist with object serialization?
Your code would look like this:
@Getter
@Setter
@Entity
@Table(name = "setting")
public class SettingEntity<T> {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Enumerated(EnumType.STRING)
private SettingType type;
@Column(columnDefinition = "jsonb")
@Convert(converter = JsonConverter.class)
private T values;
}
Additionally, you'll need to create a converter to handle JSON conversion for a generic type:
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.io.IOException;
@Converter
public class JsonConverter<T> implements AttributeConverter<T, String> {
private final ObjectMapper objectMapper = new ObjectMapper();
@Override
public String convertToDatabaseColumn(T attribute) {
try {
return objectMapper.writeValueAsString(attribute);
} catch (IOException e) {
throw new IllegalArgumentException("Error converting JSON to string", e);
}
}
@Override
public T convertToEntityAttribute(String dbData) {
try {
return objectMapper.readValue(dbData, new TypeReference<T>() {});
} catch (IOException e) {
throw new IllegalArgumentException("Error converting string to JSON", e);
}
}
}
In the above example, the JsonConverter class implements AttributeConverter using Jackson to serialize and deserialize JSON objects.
Don't forget to add the Maven dependency:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>VERSION</version>
</dependency>
Or if you're using Gradle:
dependencies {
implementation 'com.fasterxml.jackson.core:jackson-databind:VERSION'
}
Remember to replace 'VERSION' with a version of Jackson compatible with your project!
@Type(io.hypersistence.utils.hibernate.type.json.JsonBinaryType.class)
, where that is the Hibernate 6 type. – Immune