Reputation: 829
I've found two topics this and this, but still cannot populate it to my case. I have an Account
. I can do Payments
from one account to another. For that purpose I want to store payer_account_id
and receiver_account_id
in Payments
table. How can I map that using Annotations?
@Entity
public class Account {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Double balance;
//mapping here to Payments Entity
private ???
}
@Entity
public class Payments {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Double ammount;
//mapping here to Account Entity
private Account payerAccount;
//mapping here to Account Entity
private Account receiverAccount;
}
Upvotes: 4
Views: 12895
Reputation: 34
How about this:
//mapping here to Account Entity
@ManyToOne
private Account payerAccount;
//mapping here to Account Entity
@ManyToOne
private Account receiverAccount;
Upvotes: -1
Reputation: 617
It seems to be an one-to-many relations. If you want to do a bidirectional relations use these annotations.
@Entity
public class Account {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Double balance;
@OneToMany(mappedBy="payerAccount", fetch = FetchType.EAGER)
private Collection<Payments> payers;
@OneToMany(mappedBy="receiverAccount", fetch = FetchType.EAGER)
private Collection<Payments> receivers;
/* GETTERS AND SETTERS */
}
@Entity
public class Payments {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Double ammount;
@ManyToOne
@JoinColumn(name="payer_account_id")
private Account payerAccount;
@ManyToOne
@JoinColumn(name="recever_account_id")
private Account receiverAccount;
/* GETTERS AND SETTERS */
}
In this code i use EAGER fetch, it means that your lists will be automatically populated if you have an object account.
Hope it helps.
Upvotes: 13