9

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!

Hema
  • 988
  • 1
  • 16
  • 38
Justin
  • 153
  • 1
  • 1
  • 8
  • since you don't post any Spring code I'm not sure of the relevance of "new to Spring" to this. That is basic JPA. There are basic JPA docs on the internet. Here for example http://www.datanucleus.org:15080/products/accessplatform_5_1/jpa/mapping.html#one_many_relations Other than that DEFINE what you want to achieve –  Nov 02 '17 at 07:39
  • So you need one consumer with many policies...? – Hema Nov 02 '17 at 08:57

2 Answers2

6
@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.

v.ladynev
  • 19,275
  • 8
  • 46
  • 67
  • I'm getting a Error: "org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpa‌​AutoConfiguration.cl‌​ass]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory" "Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory – Justin Nov 02 '17 at 09:47
  • Caused by: java.sql.SQLException: Cannot add foreign key constraint – Justin Nov 02 '17 at 10:30
  • @Justin You need to carefully check an existing database schema and, probably, delete illegal constraints. Hibernate created them for your previous variants. – v.ladynev Nov 02 '17 at 11:34
  • I just connected to a new Database, but I'm confronting following error: "Caused by: org.hibernate.MappingException: Repeated column in mapping for entity: com.policyMgmt.policy.Policy column: id (should be mapped with insert="false" update="false")" – Justin Nov 02 '17 at 11:38
  • @Justin Try to set a join column name `@JoinColumn("consumer_id")`. Also check other column names. – v.ladynev Nov 02 '17 at 13:34
  • That worked! Thanks! But this is not really what I wanted. A consumer should have several Polcies, but a Policy **should't** have a Consumer. How can I handle this? I can't just remove the @ManyToOne – Justin Nov 02 '17 at 15:57
0

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<Policy> 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<Policy> getPolicies() {
        return policies;
    }

    public void setPolicies(List<Policy> 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;
        }

}
  • @v.ladynav's answer :) – Abdullah Khan Nov 02 '17 at 08:55
  • I'm getting a Error: "org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory" "Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory" – Justin Nov 02 '17 at 09:45
  • Caused by: java.sql.SQLException: Cannot add foreign key constraint – Justin Nov 02 '17 at 10:30