I have a Person Table ( PersonID
), and an Address table ( AddressID
). I want to create a new Join table called Person_Address
which maps Person->Adress
using a ManyToMany
relationship and I have to specify the primary key as a composition of the two primary keys ( PersonID - AddressID
).
How can I do that using Hibernate HBM syntax?
Use @ManyToMany
and forget about join tables in Hibernate. The join table will exist in your database, but not in your code, Hibernate knows how to handle this.
Example:
Person class (as the owner of the relationship):
@ManyToMany(targetEntity = Address.class, cascade = { CascadeType.PERSIST, CascadeType.MERGE }, fetch = fetchType.LAZY)
@JoinTable(name = "person_address", joinColumns = @JoinColumn(name = "PersonID"), inverseJoinColumns = @JoinColumn(name = "AddressID"))
List<Address> addresses;
Address class (if it's required):
@ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "addresses", targetEntity = Person.class, fetch = FetchType.LAZY)
List<Person> persons;
Edit:
This link will help you with the many-to-many XML mapping.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.