Reputation: 306
There's an Entity Class 'A' (supposed to be a Person),There's another Entity Class 'B' (supposed to be a Contract).
Entity 'A' has a relation @OneToMany
to Class 'B' ( a person can sign alot of contracts). Entity 'B' also has a relation @OneToMany
to Class 'A' (a contract can have many person signing it).
In this case, there's gonna be 2 JoinTable
in database, but actually they both are somehow the same.
Is there anyway that i make them just using One JoinTable?
tnx for any help!
Upvotes: 2
Views: 2185
Reputation: 32165
Situation:
You are complicating things here, the appropriate relationship between your Entities would be ManyToMany
, because :
person
can sign many contracts
.contract
can be signed by many persons
.And one JoinTable
in this relationship is sufficient to give you all the requested details:
Contract
.Contracts
have a Person
signed.Mapping:
So your mapping will be like this:
In your Person
class:
@ManyToMany(mappedBy = "persons")
private Set<Contract> contracts= new HashSet<Contract>();
And in your Contract
class:
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(
name = "PERSONS_CONTRACTS",
joinColumns = @JoinColumn(name = "CONTRACT_ID"),
inverseJoinColumns = @JoinColumn(name = "PERSON_ID")
)
private Set<Person> persons= new HashSet<Person>();
You can check this Hibernate Many-to-Many Association Annotations Example for further details.
Upvotes: 1
Reputation: 6922
Its a kind of Many to Many relationships. So it need just one junction table like person_contract in database. It will contains columns like:
where both person_id & contract_id will be a composite unique key.
In hibernate it will be: 1. In Person table
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "person_contract ", joinColumns = {
@JoinColumn(name = "person_id", nullable = false, updatable = false) },
inverseJoinColumns = { @JoinColumn(name = "contract_id",
nullable = false, updatable = false) })
public Set<Contract> contracts;
In Contract table
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "contracts")
public Set<Person> persons;
Upvotes: 1
Reputation: 19702
Looks like a @ManyToMany relation to me...
in class Person
@ManyToMany
@JoinTable(name="PERS_CONTRACTS")
public Set<Contract> getContracts() { return contracts; }
in class Contract
@ManyToMany(mappedBy="contracts")
public Set<Person> getSigners() { return signers; }
Upvotes: 2
Reputation: 2423
By using two @OneToMany there is no JoinTable. you can use @ManyToMany like this
@ManyToMany
@JoinTable(
name="AB",
joinColumns=@JoinColumn(name="A_ID", referencedColumnName="ID"),
inverseJoinColumns=@JoinColumn(name="B_ID", referencedColumnName="ID"))
private List<B> bS;
Upvotes: 1