Spring Data JPA中的一对多关系 [英] One-To-Many Relationship in Spring Data JPA

查看:274
本文介绍了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.

这是我想要的Consumer JSON对象的示例:

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:

政策实体

@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的新手,所以如果有人能够帮助我,我将非常感激!

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!

推荐答案

@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不是必需的,但可取的.

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

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

I have provided some basics here

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

如果您想使用Policy,请不要使用Consumer:

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

您可以使用联接表

@Entity
public class Consumer {

    @OneToMany
    private List<Policy> policies;

}

@Entity
public class Policy {

}

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

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 {

}

此外,请记住,如果要使用Policy作为参考(来自字典),则需要@ManyToMany.

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

这篇关于Spring Data JPA中的一对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆