Mezoo
Mezoo

Reputation: 769

Spring JPA one to many

I have two entities :

@Entity
@Table(name="Registration")
public class Registration{

   @Id
   private UUID uuid;

   @OneToMany(cascade = {CascadeType.PERSIST, CascadeType.REMOVE, CascadeType.MERGE}, fetch = FetchType.LAZY)
   @JoinColumn(name="registration", nullable = false)
   private List<Payment> payment;
}


@Entity
@Table(name="Payment")
public class Payment {

   @Id
   private UUID uuid;

   /*@ManyToOne(targetEntity = Registration.class)  <-- MappingException: Repeated column in mapping for entity
   private Registration registration;*/
}

This entities create two tables :

TABLE `registration` (
 `uuid` binary(16) NOT NULL,
 PRIMARY KEY (`uuid`))

TABLE `payment` (
 `uuid` binary(16) NOT NULL,
 `registration` binary(16) NOT NULL,
 PRIMARY KEY (`uuid`),
 CONSTRAINT `FK_jgemihcy9uethvoe3l7mx2bih` FOREIGN KEY (`registration`)           REFERENCES `registration` (`uuid`))

I'm using Rest Service. I can access to

registration.payment

but not

payment.registration

why ? I need a relation oneToMany bidirectionnal ?

Upvotes: 0

Views: 1132

Answers (1)

C&#232;sar
C&#232;sar

Reputation: 1246

Yes, you need to add the payment.registration @ManyToOne relationship if you use it in your code.

Take into account that JPA allows you to map a SQL database model to an object oriented one. Once you have the mapping between your objects and your database, you always work at the object level. That's why, although you have the relationship in the database, your Payment object doesn't know anything about it unless you map it to an attribute.

Of course it applies when you are using you data model objects or performing JPQL or Criteria queries. If you use native queries you have access to the database model as it is.

Upvotes: 1

Related Questions