【问题标题】:Multiple foreign key in java JPAjava JPA中的多个外键
【发布时间】:2021-06-03 01:59:01
【问题描述】:

我想在数据库中保留 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));
    }
}

【问题讨论】:

  • 这不是你在 jpa 中做复合键的方式。

标签: java spring-boot jpa


【解决方案1】:

使用@EmbeddedId 代替@IdClass

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

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-09
    • 1970-01-01
    • 1970-01-01
    • 2019-11-06
    • 2022-01-16
    相关资源
    最近更新 更多