【问题标题】:JAVA JPA : join two entities on attributes with annotationJAVA JPA:使用注释在属性上连接两个实体
【发布时间】:2021-02-10 00:33:45
【问题描述】:

我正在做一个不属于我的项目,我需要你的帮助。 目前我在数据库上有两个表:

TABLE A :  id | prop | prop ... | id_link
           1  |                 | 2
           2  |                 | 1
           3  |                 | 2
           4  |                 | 3


TABLE B :  id | prop | prop ... | id_link
           1  |                 | 1
           2  |                 | 1
           3  |                 | 1
           4  |                 | 2
           5  |                 | 2
           6  |                 | 2
           7  |                 | 3
           8  |                 | 3
           8  |                 | 3

在 Java 中,我得到了这个:

@Entity
@Table(name = "A")
@Getter
@Setter
public class A{
    
    @Id
    @Column(name = "id")
    private Long id;

    some properties...

    @Column(name = "id_link")
    private Long idLink;

@Entity
@Table(name = "B")
@Getter
@Setter
public class B{
    
    @Id
    @Column(name = "id")
    private Long id;

    some properties...

    @Column(name = "id_link")
    private Long idLink;

当我检索 A 的实例时,我想要这样的东西:

"A": [
                {
                  "id": 1,
                  ...
                  "B": [
                    {
                      "id": 4,
                       ...
                    },
                    {
                      "id": 5,
                       ...
                    },
                    {
                      "id": 6,
                       ...
                    },
                  ]
                },
]

但是我已经卡住了 2 天,我正在尝试使用 OneToMany 注释或这种注释,但没有成功。请帮我 ! :)

【问题讨论】:

  • I'm trying with OneToMany annotations or this kind of annotations 发表你的尝试?
  • 基于json,需要OneToMany

标签: java spring-boot hibernate jpa annotations


【解决方案1】:

根据您的 json,您的 A 类应该与 B 类有 OneToMany 关系。像这样

@Entity
@Table(name = "A")
@Getter
@Setter
public class A{
    
    @Id
    @Column(name = "id")
    private Long id;

    @OneToMany(mappedBy = "a")
    private List<B> bList;

B类将是

@Entity
@Table(name = "B")
@Getter
@Setter
public class B{
    
    @Id
    @Column(name = "id")
    private Long id;
    
    @ManyToOne
    private A aObject;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-01
    • 1970-01-01
    • 2015-11-14
    • 2013-11-27
    • 2014-09-30
    • 2016-06-30
    • 2017-04-04
    • 1970-01-01
    相关资源
    最近更新 更多