简体   繁体   中英

How to join column with multiple primary keys or specific primary key in jpa

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

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

    @JoinColumn(name = "test_id")
    private List<Test> testId;
}
@Entity
@Table(name = "Test")
public class Test {
    @Id
    @Column(name = "test_id")
    private Long testId;
}

Error Result is

" JPA trouble with OneToOne relationship: A Foreign key refering has the wrong number of column. should be 2 "

How to specific primary key for join Test table?

Table A: column id map with Table B: column test_id

Since your table A has a composite key, you should separate the columns out into another key class and then join on the individual part of the key of the table.

For instance, create AKey

@Embeddable
public class AKey {

    @Column(name = "id")
    private Long id;

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

    //getters and setters
}

Then replace the ids in class A

@Entity
@Table(name = "A")
public class A {
    @EmbeddedId
    private AKey key;

    @JoinColumn(name = "test_id")
    private List<Test> testId;
}

Then you can do a join on Test.testId = A.key.id

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