0

Say I have the following data in Postgresql table entity_b, which has an array column of ids from table entity_a:

id | e_a_ids[]
---+----------
b1 | a1,a2,a3
b2 | a1,a3

I want to map in Hibernate these two entities with annotations:

@Entity
class EntityA {
    Set<EntityB> entityBs;
}

@Entity
class EntityB {
    Set<EntityA> entityAs;
}

I have found examples of custom hibernate type that works with array column, but those are for primitives not for another entity type. I can also use a normal id column instead of an array column with the traditional many to many method by introducing another mapping table, but thats not so much a question to ask here then.

How can a bidirectional mapping with an array column of ids for another entity be mapped in Hibernate for a Postgresql database tables?

user1589188
  • 5,316
  • 17
  • 67
  • 130
  • I'm not sure Hibernate supports this, at least I'm not aware of any such mapping. User types might be an option but given all the other things to keep in mind (lazy loading, first level cache, cascading etc.) this will be pretty hard to get right if doable at all. – Thomas Jan 17 '22 at 08:04

1 Answers1

0

Even if there would be ways to make this work with Hibernate (which may be hard as @Thomas suggested), you would most probably loose the foreign key constraint validation.

Neither postresql nor mysql (just 2 examples) seem to support this:
postgresql: PostgreSQL array of elements that each are a foreign key
mysql: Array of foreign keys in one column

So it might be best to stick with the standard association table.

fladdimir
  • 1,230
  • 1
  • 5
  • 12