jpaone-to-oneself-referencing-table

Do self referencing entities need @OneToOne JPA annotations or not?


Imagine an Entity A has a non-mandatory one-to-one relationship with itself, say something like the diagram below. diagram

Do I write sourceTransaction and destinationTransaction as: public DepositAccountTransaction sourceTransaction; public DepositAccountTransaction destinationTransaction; without any annotations?


Solution

  • No you always will need the annotation. If it is optional:

    @OneToOne(optional = true)
    private DepositAccountTransaction destinationTransaction;
    

    I wouldn't declare any property as public btw. You may want to use projectlombok to generate getters and setters.