Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One-To-Many Relationship in Spring Data JPA

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 JSON object I would like to have:

{
     id : 1,
     name : "Peter",
     endpoint: "123.456.778",
     policies: [
                    {
                       id : 1,
                       name: "policy 01"
                    },
                    {
                       id : 2,
                       name: "policy 02"
                    }
             ]
}

This is what I have so far:

Policy Entity

@Entity
public class Policy {
        @Id
        @GeneratedValue
        @Column(name = "id")
        private Integer id;

        @Column(name = "name")
        private String name;

        //getters and setters
    }

Consumer Entity

@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
    @JoinColumn(??)
    private List<Policy> policies;

  //getters and setters
}

It's not that hard I think, but im trying now for several hours and can't get it done. I'm new to Spring, so if someone is able to help me, I would be very thankfull!

like image 712
Justin Avatar asked Nov 02 '17 00:11

Justin


1 Answers

@Entity
public class Consumer {

    @OneToMany(mappedBy = "consumer")
    private List<Policy> 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<Policy> 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<Policy> policies;

}

@Entity
public class Policy {
    
}

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

like image 199
v.ladynev Avatar answered Oct 08 '22 07:10

v.ladynev