I just started learning JPA & Hibernate, I'm confused about understanding the proper way of reading/conceptualizing @OneToMany mapping in JPA with Hibernate.
As an example imagine and Account which can have many Transactions but One Transaction can be only linked to one Account.
So I read this perspective to the "Account class/Entity" as "One Account can have Many transaction thus I should mark the Transcation field as @OneToMany.
And other way around perspective to the "Transaction class/Entity" I think like "One Transaction can only be linked to One Account thus I should mark Account field in the Transaction Entity as @OneToOne"
But from the almost all the video video tutorials I watched and Web resources mentions that Transactions Entity's Account field should be @ManyToOne because "Many Transaction can be linked with one Account" which is true but to me it's just the same relationship we mentioned in the Account Entity explained different way but doesn't say other side of the relationship that "One Transaction can only be linked to one Account"
Please if you can help me to understand how to read and How, Why the relationship of the opposite side when one entity is @OneToMany.
@Entity
public class Account {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long accountId;
@OneToMany(cascade = CascadeType.ALL)
private List<Transaction> transactions = new ArrayList<>();
}
@Entity
public class Transaction {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long transactId;
@ManyToOne
Account account;
}
I like to think of it this way:
@Entity
public class Account {
// Here I read this as "One Account (The entity we are in) ToMany Transactions (The foreign entity)
@OneToMany(cascade = CascadeType.ALL)
private List<Transaction> transactions = new ArrayList<>();
}
@Entity
public class Transaction {
// If we use the same process as above we get:
// Many Transactions (The entity we are in) ToOne Account (The foreign entity)
@ManyToOne
Account account;
}