简体   繁体   中英

JAVA JPA : join two entities on attributes with annotation

I am working on a project that is not mine and I need your help. Currently I have two table on database :

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

In Java, I got this :

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

and

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

And I want something like this when I retrieve an instance of A :

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

But I've been stuck for 2 days, I'm trying with OneToMany annotations or this kind of annotations, but without success. Please help me ! :)

Based on your json you class A should have OneToMany relation with class B. Something like this

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

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

and B class will be

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM