首页 > 解决方案 > java JPA中的多个外键

问题描述

我想在数据库中保留 Class2 的一个实例。但是当我向'/two'发送GET请求时,它会报告异常org.postgresql.util.PSQLException: ERROR: null value in column "id1" of relation "class2" violates not-null constraint Detail: Failing row contains (2, null, null, 1).

我该怎么做才能成功持久化 Class2 的新实例。是否可以使PK成为Class2的主键(PK是Class1的主键和Class2的外键,我想使它成为Class2的主键)

Class1.java

@Table
@Entity
@Data
@IdClass(PK.class)
@AllArgsConstructor
@NoArgsConstructor
public class Class1{

    @Id
    private int id1;

    @Id
    private int id2;

    private int one;

}

Class2.java

@Table
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Class2{

    @Id
    private int id;

    @OneToOne
    @JoinColumns({
            @JoinColumn(name = "id1", referencedColumnName = "id1", insertable = false, updatable = false),
            @JoinColumn(name = "id2", referencedColumnName = "id2", insertable = false, updatable = false)
    })
    private Class1 class1;

    private int two;

}

控制器

@RestController
public class ForeignController {

    @Autowired
    Class1Repository repository1;

    @Autowired
    Class2Repository repository2;

    @GetMapping("/one")
    public void createone(int id1, int id2, int one){
        repository1.saveAndFlush(new Class1(id1, id2, one));
    }

    @GetMapping("/two")
    public void createtwo(int id1, int id2, int two, int id){
        Class1 class1 = repository1.getOne(new PK(id1, id2));
        repository2.saveAndFlush(new Class2(id, class1, two));
    }
}

标签: javaspring-bootjpa

解决方案


代替@IdClass,使用@EmbeddedId

@Table
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Class1{

    @EmbeddedId
    private PK pk;

    private int one;

}
public class Class2{

    @EmbeddedId
    private PK pk;

    @MapsId
    @OneToOne
    private Class1 class1;

    private int two;

}

推荐阅读