我在尝试坚持一对多关系时遇到异常。我可以看到问题发生的原因是在插入子(链接)时没有使用父级(策略)自动生成的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 TopLink Essentials - 2006.8(Build 060830)): oracle.toplink.essentials.exceptions.DatabaseException内部 例外:java.sql.SQLIntegrityConstraintViolationException:Column &#39;策略ID&#39;不能接受NULL值。错误代码:20000调用:INSERT INTO LINKS(LINK,ORDINAL,POLICYID)VALUES(?,?,?)bind =&gt; [链接, 1, null ] 查询:InsertObjectQuery(xxx.xxxx.xxx.xxx.datalayer.entities.LinkEntity@1bb813b)
致电:插入链接(链接,序列,政策)价值(?,?,?) bind =&gt; [link,1,null]&lt; ---如何在这里设置自动生成的策略ID?
答案 0 :(得分:0)
根据克里斯的评论更新。
我意识到我需要在链接实体中实际设置策略。现在链接插入毫无例外。
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);