hibernatekotlinquarkusquarkus-panache

Hibernate composite type for amount field


Im trying to map my custom postgres type to my hibernate entity, also I'm using Quarkus with kotlin and panache repository.

-> My postgres setup...

CREATE TYPE money_and_currency AS (amount integer, currency varchar(3));
CREATE TABLE example_table (
    "id" uuid,
    "amount" money_and_currency,
);

-> My Hibernate entity setup...

@Entity
@Table(name = "example_table")
class ScheduledTransactionEntity : PanacheEntityBase {
    @Id
    @GeneratedValue
    @Column(columnDefinition = "uuid", updatable = false)

    @Column(nullable = false)
    @Embedded
    var amount: MoneyAndCurrency? = null
}
@Embeddable
data class MoneyAndCurrency(val amount: Int, val currency: String)

I got this error when I try to insert a new data into database:

org.hibernate.exception.SQLGrammarException: could not execute statement [ERROR: column "currency" of relation "scheduled_transactions" does not exist

I tried also to add a columnDefinition="money_and_currency" to @Column annotation but nothing changed...

I just need to know how to properly map a composite custom type using hibernate.


Solution

  • The entity is right but is missing a @Struct(name = "money_and_currency") annotation to tell hibernate what is the type declared in the database that hibernate should map to@Entity

    @Table(name = "example_table")
    class ScheduledTransactionEntity : PanacheEntityBase {
        @Id
        @GeneratedValue
        @Column(columnDefinition = "uuid", updatable = false)
    
        @Column(nullable = false)
        @Embedded
        var amount: MoneyAndCurrency? = null
    }
    @Embeddable
    @Struct(name = "money_and_currency")
    data class MoneyAndCurrency(val amount: Int, val currency: String)