Skip to content
Advertisement

Spring JPA relationships


I have some troubles with Spring JPA relationships.
I have two entities: Gift and Candy. And I want user to be able to select available candy and add it to gift.
How can I do that using spring jpa?
I’ve already tried ‘one to many’ relationship with gift as owning side, and I got “null value in column ‘gift_id violates not-null constraints'” error while creating and saving candy. Here is my code:
Gift class:

JavaScript

Candy:

JavaScript

Advertisement

Answer

Just use the mappedBy property to specify what field to use for mapping the relation.

  1. In Gift

@OneToMany(mappedBy = "gift", cascade = CascadeType.ALL, orphanRemoval = true) private List<Candy> candyList = new ArrayList<>();

  1. In Candy

@ManyToOne() private Gift gift;

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement