Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is correct to use @OneToMany with @OneToOne?

I have a class Portfolio where the debts that the debtors have with different banks are kept. Therefore, a portfolio has a list of Debt objects and the annotation is @OneToMany.

This is Portfolio:     

@Entity
public class Portfolio extends PersistentEntity {
    @OneToMany
    private List<Debt> debts;

    /* Getters and setters */
}

And the class Debt:

@Entity
public class Debt extends PersistentEntity {
    @OneToOne
    private Portfolio portfolio;

    /* Getters and setters */
}

My question is what annotation to use in the Debt class. I understand it is @OneToOne because a debt belongs to a particular portfolio, but I was advised to use @ManyToOne. What I understand from this annotation is that a debt can be referenced by different portfolios. Is this correct?

like image 839
fferrin Avatar asked Feb 02 '26 00:02

fferrin


1 Answers

You should use annotation @ManyToOne. In your case, as you said Portfolio has a list of Debt objects and the annotation is @OneToMany. On the other hand, each Debt can belong ONLY ONE Portfolio, so you should use annotation @ManyToOne

Also, see these links:

  • Hibernate mapping: OneToMany and OneToOne on child object property
  • When to use, not to use, OneToOne and ManyToOne
  • Difference Between One-to-Many, Many-to-One and Many-to-Many?
  • https://dzone.com/tutorials/java/hibernate/hibernate-example/hibernate-mapping-many-to-one-1.html
like image 92
Lemmy Avatar answered Feb 03 '26 17:02

Lemmy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!