Can 2 objects have 2 relationships between them at the same time? (JPA),
For example, I have an account object with two constructors.
@Entity
public class DefaultAccount implements Account {
@OneToOne(targetEntity = DefaultManager.class)
private Manager manager;
public DefaultAccount(String email, String password) {
this.email = email;
this.password = password;
}
public DefaultAccount(String email, String password, Manager manager) {
this(email, password);
this.manager = manager;
}
// Getters
}
The second constructor is used to designate an account as a manager. The manager can manage a set of accounts.
@Entity
public class DefaultManager implements Manager {
@OneToOne(targetEntity = DefaultAccount.class)
private Account managerAccount;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "manager", targetEntity = DefaultAccount.class)
private Set<Account> accountsToManage = new HashSet<Account>();
public DefaultManager(Account managerAccount, Set<Account> accountsToManage) {
this.managerAccount = managerAccount;
this.accountsToManage.addAll(accountsToManage);
}
// Getters
}
Will this relationship work? If not, what's the best alternative for her to work?
source to share
Yes it will work, you can see SpringTest with hibernate here .
You need a no-argument constructor to work with JPA, this constructor doesn't have to be public
, it can be protected
.
In addition, your entities require a field annotated with @Id
. If your interfaces provide a @Id
getter method , then you need to put your annotations ( @OneToMany
and so on) in the getters of your concrete classes.
If you run the test, you will see the result:
Hibernate: call next value for man_seq
Hibernate: insert into Test25504340$DefaultAccount (manager_id, password, email) values (?, ?, ?)
Hibernate: insert into Test25504340$DefaultAccount (manager_id, password, email) values (?, ?, ?)
Hibernate: insert into Test25504340$DefaultAccount (manager_id, password, email) values (?, ?, ?)
Hibernate: insert into Test25504340$DefaultManager (managerAccount_email, id) values (?, ?)
Hibernate: update Test25504340$DefaultAccount set manager_id=?, password=? where email=?
Where:
- First, enter the sequence to insert the manager (I add the attribute
Long id
inDefaultManager
). - It will add three accounts referring to Manager (Account Manager -> Manager # id).
- Insert manager
- Update links
Manager#Account
to targetAccount
one (Manager # manageAccount → Account # email).
You can change the order of the calls ( persirst
manager first, for example) and the result will be a different sequence of inserts with the same final result.
source to share