Spring Data JPA中的一对多关系

9
我希望在两个实体,Consumer和Policy之间建立一种一对多的关系。一个Consumer应该有多个Policy。
这是一个Consumer JSON对象的示例:
{
     id : 1,
     name : "Peter",
     endpoint: "123.456.778",
     policies: [
                    {
                       id : 1,
                       name: "policy 01"
                    },
                    {
                       id : 2,
                       name: "policy 02"
                    }
             ]
}

这是我目前所拥有的:

策略实体

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

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

        //getters and setters
    }

消费者实体

@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
}

我认为这并不难,但我已经尝试了数个小时还没有完成。我是 Spring 的新手,如果有人能帮助我,我将非常感激!


由于您没有发布任何Spring代码,我不确定“新手入门Spring”的相关性。那是基本的JPA。互联网上有基本的JPA文档。例如,在此处http://www.datanucleus.org:15080/products/accessplatform_5_1/jpa/mapping.html#one_many_relations。除此之外,明确您想要实现什么。 - user8558216
所以你需要一个消费者拥有多个策略...? - Hema
2个回答

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 不是必需的,但是很理想。

我在这里提供了一些基础知识。

什么是 @JoinColumn,它在 Hibernate 中如何使用

如果你想让一个 Policy 没有一个 Consumer

你可以使用一个连接表。

@Entity
public class Consumer {

    @OneToMany
    private List<Policy> policies;

}

@Entity
public class Policy {
    
}

单向关系(一个Policy表将有consumer_id列,但是一个Policy类没有Consumer

@Entity
public class Consumer {

    @OneToMany
    @JoinColumn("consumer_id")
    private List<Policy> policies;

}

@Entity
public class Policy {
    
}

此外,请记住,如果您想将 Policy 作为表格数据(从字典中)使用,则需要使用 @ManyToMany

我遇到了一个错误:"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
由于:java.sql.SQLException: 无法添加外键约束。 - Justin
@Justin 你需要仔细检查现有的数据库模式,并可能删除非法约束。Hibernate为您之前的变体创建了它们。 - v.ladynev
我刚连接到一个新的数据库,但是我遇到了以下错误:"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
@Justin 尝试将联接列命名为 @JoinColumn("consumer_id")。还要检查其他列名。 - v.ladynev
成功了!谢谢!但这不是我真正想要的。一个消费者应该有多个策略,但一个策略不应该有一个消费者。我该如何处理?我不能只是删除@ManyToOne。 - Justin

0

试试这段代码 :)

你的消费者类

@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;
    }
}

请注意,在映射中,您应该使用在数据库中引用策略的列的名称,因此如果没有policyId,请使用您为其命名的名称

您的策略类

@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的回答 :) - Abdullah Khan
我遇到了一个错误:"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
由于:java.sql.SQLException: 无法添加外键约束。 - Justin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接