0

Is there a way to get kotlin value classes (updated inline classes) to work with libraries such as Jackson and Hibernate and have them treat the value class simply as the underlying type?

Currently I get a bunch of errors saying that there is not default constructor for the type (which makes sense since it's really just a wrapper for the underlying type as far as I've understood it).

All exceptions I get are runtime errors so no warning during compile time that this will happen.

I assume that these issues are related as in both cases I get errors saying that the type is missing an empty constructor.

I apologize if my question is somewhat unclear, I've been digging in to this for a number of hours without really getting anywhere.

What I want to accomplish is (for example for hibernate):

value class Name(val name: String)

@Entity
@Table(name = "my_table")
class MyTable(
  @Id
  @Column(name = "id")
  @GeneratedValue(strategy = GenerationType.AUTO)
  val id: UUID = UUID.randomUUID(),

  @Column(name = "name", nullable = false)
  val name: Name = Name("John")
)

And have it treat name simply as a string when communicating with the database.

I'm using a stack based on http4k and jackson for rest communication and I have request/response entities on the form

data class MyRestObject(val id: UUID, val name: Name)

This works as I would expect for responses, the generated response json looks like:

{
  "id": UUID,
  "name": String
}

However it does not work for requests.

Example exception from jackson: Cannot construct instance of `component.Name`(no Creators, like default constructor, exist): no String-argument constructor/factory method to deserialize from String value ('foerijfm')

Vidde
  • 11
  • 1
  • 2

1 Answers1

0

For Jackson you can use the @JsonCreator annotation to annotate the constructor to use. Alternatively, you can register a Deserializer for the type in the ObjectMapper.

For Hibernate ORM you can use a JPA attribute converter.

Christian Beikov
  • 15,141
  • 2
  • 32
  • 58
  • Hi, and thanks for your reply! For all of those solutions am I wrong in thinking that they would have to be implemented on the containing type rather than the value class itself? – Vidde Feb 21 '23 at 09:07
  • `@JsonCreator` annotation goes onto a constructor of the value class. `Deserializer` and `AttributeConverter` are separate classes. – Christian Beikov Feb 21 '23 at 11:39
  • I have tried all of these solutions but I cannot get it to work. I had tried implementing the `Deserializer` before asking the question and since receiving your answer I have tried the other two and I get the same error with all of them. I have gotten both the Deserializer and the AttributeConverter to work if I implement them for the outer class (`MyTable` and `MyRestObject` in my example above) but never for the value class itself. – Vidde Feb 21 '23 at 12:51