javaserializationjacksonmicronautmicronaut-data

Store object to postgres varchar column as Json using Micronaut Data


Is it possible to automatically serialize/deserialize java object to single varchar/text column in postgres without manually using objectMapper etc? I only use Micronaut Data without Hibernate.

For example let's imagine this case:

CREATE TABLE person (
    id int not null primary key,
    name varchar not null,
    address varchar not null
);
@MappedEntity
public class Person {
    @Id
    private Long id;
    private String name;
    private Address address;

    // getters and setters
}
public class Address {
    private String street;
    private String city;
    private String streetNumber;

    // getters and setters
@Repository
public interface PersonRepository extends CrudRepository<Person, Long> {
}

I tried to use annotations like @Serdeable or @JsonProperty, but I must be missing something, because I get an RuntimeExceptionHandler error with a message:

Unexpected error in XYZ project: Error executing PERSIST: Unable to set PreparedStatement value: Can't infer the SQL type to use for an instance of x.y.z.Address. Use setObject() with an explicit Types value to specify the type to use.

The only solution that I could come up with was to change address attribute in person class to String and then manually map the response using Jackson's objectMapper. But then I would need to create another class and map Person and Address into it.

Is it possible to serialize/deserialize it just by using some annotations etc?


Solution

  • So it seems I found a solution. Both classes need to be annotated with @Serdeable annotation and in Person class use @TypeDef(type = DataType.JSON) annotation on address attribute.