One-To-Many Relationship in Spring Data JPA

前端 未结 2 1210
难免孤独
难免孤独 2021-01-18 12:23

I would like to have a One-to-many relationship between 2 Entities, Consumer and Policy. One consumer should have several policies.

This is an example of a Consumer

2条回答
  •  渐次进展
    2021-01-18 12:55

    @Entity
    public class Consumer {
    
        @OneToMany(mappedBy = "consumer")
        private List policies;
    
    }
    
    @Entity
    public class Policy {
    
        @ManyToOne(fetch = FetchType.LAZY)
        @JoinColumn("consumer_id")
        private Consumer consumer;
    
    }
    

    fetch = FetchType.LAZY is not necessary, but desirable.

    I have provided some basics here

    what is @JoinColumn and how it is used in Hibernate

    If you want to a Policy don't have a Consumer:

    You can use a join table

    @Entity
    public class Consumer {
    
        @OneToMany
        private List policies;
    
    }
    
    @Entity
    public class Policy {
    
    }
    

    A unidirectional relation (a Policy table will have consumer_id column, but a Policy class doesn't have a Consumer)

    @Entity
    public class Consumer {
    
        @OneToMany
        @JoinColumn("consumer_id")
        private List policies;
    
    }
    
    @Entity
    public class Policy {
    
    }
    

    Also, keep in mind, that if you want to use a Policy as a reference (from a dictionary) you will need @ManyToMany.

提交回复
热议问题