JPA toplink 级联 persist with javadb 具有空外键



我在尝试保持一对多关系时遇到异常。 我可以看到出现问题是因为插入子级(链接)时未使用父级(策略)自动生成的 id。

SQL 命令:

CREATE TABLE POLICIES
(
  ID INTEGER NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
  CURRENTLINKID INTEGER,
);
CREATE TABLE LINKS
(
  ID INTEGER NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
  ORDINAL INTEGER NOT NULL,
  LINK VARCHAR(50) NOT NULL,
  POLICYID INTEGER NOT NULL
);
ALTER TABLE POLICIES
ADD FOREIGN KEY(CURRENTLINKID) 
REFERENCES LINKS(ID);
ALTER TABLE LINKS
ADD FOREIGN KEY(POLICYID) 
REFERENCES POLICIES(ID);

实体:

@Entity
@Table(name = "POLICIES", catalog = "", schema = "")
public class PolicyEntity
{
    ...
    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "_policy")
    private Collection<LinkEntity> _linkEntityCollection;
    ...
}
@Entity
@Table(name = "LINKS", catalog = "", schema = "")
public class LinkEntity
{
    ...
    @JoinColumn(name = "POLICYID", referencedColumnName = "ID")
    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, optional = false)
    private PolicyEntity _policy;
    ...
}

创建实体并保留:

LinkEntity link = new LinkEntity();
link.setLink("link");
link.setOrdinal(1);
List<LinkEntity> links = new ArrayList<LinkEntity>();
links.add(link);
PolicyEntity policy = new PolicyEntity();
policy.setLinks(links);
EntityManager entityManager = _emf.createEntityManager();
// Begin transaction
entityManager.getTransaction().begin();
// persist
entityManager.persist(policy);
// Commit the transaction
entityManager.getTransaction().commit();
// Close this EntityManager
entityManager.close();

例外:

javax.persistence.RollbackException: Exception [TOPLINK-4002] (Oracle 拓联要点 - 2006.8(内部版本 060830)): oracle.toplink.essentials.exceptions.DatabaseException Internal 异常:java.sql.SQLIntegrityConstraintViolationException: Column "策略 ID"不能接受空值。错误代码:20000 调用:插入 进入链接(链接、序号、策略 ID)值 (?, ?, ?) 绑定 => [链接, 1、] 查询:插入对象查询(xxx.xxxx.xxx.xxx.datalayer.entities.LinkEntity@1bb813b)


调用:插入到链接(链接、序号、策略 ID)值 (?, ?, ?) 绑定 => [链接, 1, 空] <---如何在此处设置自动生成的策略 ID?

根据

克里斯的评论进行了更新。

我意识到我需要在链接实体中实际设置策略。 现在,链接已无一例外地插入。

PolicyEntity policy = new PolicyEntity();
LinkEntity link = new LinkEntity();
link.setLink("link");
link.setOrdinal(1);
link.setPolicy(policy) // set policy so it wasn't null
List<LinkEntity> links = new ArrayList<LinkEntity>();
links.add(link);
policy.setLinks(links);

相关内容

  • 没有找到相关文章

最新更新