Viktoriia
Viktoriia

Reputation: 2400

How change hibernate association mapping from 'one to many' into 'many to many'?

The relation between the entities must be changed and I'd like to know is it normal to change the association mapping type and whether the data that already exist in db will be transfered normally? I tried to find information about it but didn't found. Or if the mapping will be changed the data that already exists must be transfered manually via sql queries? Thanks

Upvotes: 2

Views: 1885

Answers (2)

user1767316
user1767316

Reputation: 3641

I could do it simply:

Let A and B be the original tables. A->B (N-1) was moved to A<-AB->B (N-N).

I had to - "remove" the foreignkey column from table A, in favor of records to be inserted into AB (made of the two foreign keys leading to A and B) That's all.

  • Step one: Replace your Many-to-One annotation by your Many-to-Many annotations. and lauch hibernate in append mode to generate the N-N table
  • Step two: Insert record in this N-N table given what is found in the remaining foreign-key column of you 1-N relationship.
  • Step three: Delete this foreign-key column.

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691735

If the association already uses a join table, and the mapping of the many-to-many keeps using the same join table with the same column names, you won't have to do anything except removing the unicity constraint you could have on one of the ci=olumns of the join table.

Otherwise, yes, obviously, you'll have to migrate your schema, using SQL, or any other tool (FlywayDB, Liquibase, etc.).

Upvotes: 1

Related Questions