3

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?

fferrin
  • 888
  • 2
  • 12
  • 29
  • The opposite end of a one-to-many relationship is many-to-one. There are "many" debts to "one" portfolio. From the perspective of a single debt, it is one debt to one portfolio, but in reality, the relationship in the debt class is representative of the relation as a whole. – Alex May 15 '17 at 20:22
  • Many `Debt`s belong to a single 'Portfolio` so @ManyToOne in `Debt`. It's about the overall relationship between the entities, and not about a particular instance of a `Debt`. – Andrew S May 15 '17 at 20:24
  • Perfect! But if I use `@OneToOne`, does an error occur (in addition to the conceptual misunderstanding)? I ask you because I was using it with `@OneToOne` but it did not throw any error, so it may be that errors do not arise or that I have forgotten to implement something and those errors do not appear to me. – fferrin May 15 '17 at 20:30
  • a good read on some JPA relationships: http://stackoverflow.com/questions/3113885/difference-between-one-to-many-many-to-one-and-many-to-many – Dachstein May 15 '17 at 20:35

1 Answers1

2

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:

Community
  • 1
  • 1
Lemmy
  • 2,437
  • 1
  • 22
  • 30
  • 1
    The annotation in the two classes is used when we want a bidirectional relationship, right? If I do not care that the debt has a portfolio reference, I only use `@ OneToMany` in `Portfolio`, right? – fferrin May 15 '17 at 20:45