Home > Mobile >  Spring JPA relationships
Spring JPA relationships

Time:11-28


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:

    @Entity
    public class Gift implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private long id;
    private String buyer;

    @OneToMany(cascade = CascadeType.REMOVE)
    @JoinColumn(name = "GiftId", nullable = true)
    private List<Candy> candyList = new ArrayList<>();
    ...

Candy:

    @Entity
    public class Candy implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @JsonIgnore
    private long id;
    private String name;
    private String brand;
    private double price;
    private int weight;
    private int sugar;
    ...

CodePudding user response:

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;

  • Related