【问题标题】:Saving to child table with springboot+jpa使用spring boot + jpa保存到子表
【发布时间】:2016-05-09 16:01:50
【问题描述】:

我无法保存...从子表中提取正在工作 这是我的 父表 pojo

@Entity
@Table(name = "Dei_Resources")
public class DeiResources {

    private int id;
    private String employeeId;
    private Set<DeiResourceType> deiResourceType;
    //other setters getters not included
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public int getId() {
        return id;
    }

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "deiResource", cascade = CascadeType.ALL)
    public Set<DeiResourceType> getDeiResourceType() {
        return deiResourceType;
    }

子表 pojo

@Entity
public class DeiResourceType implements Serializable{

    private int id;
    private int resourceId;
    private String typeValue;
    @JsonBackReference
    private DeiResources deiResource;

    //other setters getters not included
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public int getId() {
        return id;
    }

    @ManyToOne(fetch=FetchType.LAZY,optional=false)
    @JoinColumn(name = "resourceId", referencedColumnName="id",insertable = false, updatable = false)
    public DeiResources getDeiResource() {
        return deiResource;
    }

我有 DeiResourcesRepository,在我的服务中我正在尝试这个

DeiResources dei = new DeiResources();
DeiResourceType deii =  new DeiResourceType();
Set<DeiResourceType> deiResourceType = new HashSet<DeiResourceType>();
deii.setTypeValue("Driver");
deiResourceType.add(deii);
dei.setEmployeeId("unique1");
dei.setDeiResourceType(deiResourceType);
deiResourcesRepository.save(dei);

收到此错误

[错误] org.hibernate.engine.jdbc.spi.SqlExceptionHelper - ORA-02291: 违反完整性约束 (DEI_ADMIN.DEI_RESOURCE_TYPE_R01) - 找不到父键

在 DeiResourceType 表中,我添加了带有父表 ID 的外键约束。我怎样才能摆脱这个错误,任何建议/帮助?

【问题讨论】:

  • 类型Driver是否已经存在于数据库表DeiResourceType中?
  • 是的,但是 typeValue 没有唯一键约束

标签: java jpa spring-boot


【解决方案1】:

首先,在 SQL 中没有子/父模式。这就是为什么像真正的家庭这样的结构的想象是错误的。在这个例子中,父母不能是孩子,在现实世界中,每个父母都是孩子!

我们只有两个表,它们具有 1-n 关系,尊重每个 DeiResource 必须具有 DeiResourceType 的约束!只要这个约束保持其完整性,就不会有例外。

记住这一点你调用了两个实体的构造函数但是你只保存了一个(你保存了没有 DeiResourceType 的 DeiResource)。所以你保存一个没有类型的资源。但是每个 DeiResource 必须有一个 DeiResourceType 的约束被打破,数据库不再具有完整性并抛出异常!

你有两个选择:

  • 您先保存 DeiResourceType,然后再保存 DeiResource
  • 您首先加载现有的 DeiResourceType,将其连接到 DeiResource,然后保存 DeiResource。

我更喜欢第二种方法,以避免在“DeiResourceType”表中出现重复。

(顺便说一句,这些约束可以推迟,一个古老的、被遗忘的、强大的魔法)

【讨论】:

    猜你喜欢
    • 2018-04-30
    • 2020-02-03
    • 1970-01-01
    • 2021-06-22
    • 1970-01-01
    • 2021-01-28
    • 1970-01-01
    • 2015-06-13
    • 1970-01-01
    相关资源
    最近更新 更多