One-To-Many Relationship in Spring Data JPA

前端 未结 2 1202
难免孤独
难免孤独 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:52

    Try this code :)

    Your Consumer Class

    @Entity
    public class Consumer {
    
        @Id
        @GeneratedValue
        @Column(name = "consumer_id")
        private Integer id;
    
        @Column(name = "name")
        private String name;
    
        @Column(name = "endpoint")
        private String endpoint;
    
        @OneToMany(cascade = CascadeType.ALL, mappedBy = "idPolicy")
        private List policies;
    
    
        public Consumer() {
        }
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getEndpoint() {
            return endpoint;
        }
    
        public void setEndpoint(String endpoint) {
            this.endpoint = endpoint;
        }
    
        public List getPolicies() {
            return policies;
        }
    
        public void setPolicies(List policies) {
            this.policies = policies;
        }
    }
    

    Be aware that in the mapped by, you should use the name of the column that references Policy in your database, so if it's no policyId, use the name you gave to it

    Your Policy Class

    @Entity
    public class Policy {
            @Id
            @GeneratedValue
            @Column(name = "id")
            private Integer id;
    
            @Column(name = "name")
            private String name;
    
            @ManyToOne(optional = false)
            private Consumer consumer;
    
            public Policy() {
    
            }
    
            public Integer getId() {
                return id;
            }
    
            public void setId(Integer id) {
                this.id = id;
            }
    
            public String getName() {
                return name;
            }
    
            public void setName(String name) {
                this.name = name;
            }
    
    }
    

提交回复
热议问题