JPA:CascadeType.PERSIST与多通

JPA:CascadeType.PERSIST与多通,jpa,many-to-one,Jpa,Many To One,我正在使用CascadeType.PERSIST和ManyToOne @ManyToOne(cascade=CascadeType.PERSIST) @JoinColumn(name="Article") private Article article; 持久性代码如下所示: Article article = new Article(); article.setAuthor("Article Author"); article.setTitle("Article Ti

我正在使用CascadeType.PERSIST和ManyToOne

@ManyToOne(cascade=CascadeType.PERSIST)
@JoinColumn(name="Article")
private Article article;
持久性代码如下所示:

    Article article = new Article();
    article.setAuthor("Article Author");
    article.setTitle("Article Title");
    Comment comm1 = new Comment();
    comm1.setAuthor("Author1");
    comm1.setTitle("Title1");
    article.addComment(comm1);
    em.persist(comm1);
    em.getTransaction().commit();
我希望使用CascadeType.PERSIST on字段将使持久性提供程序按照这样的顺序对SQL排序:首先持久化父实体(此处的文章),然后持久化子实体。但是我得到了

原因:org.apache.openjpa.lib.jdbc.ReportingSQLException:无法添加或更新子行:外键约束失败

在这种情况下,正确的做法是什么

第条:

@Entity
@NamedQuery(name="Article.findAll", query="SELECT a FROM Article a")
public class Article implements Serializable {
private static final long serialVersionUID = 1L;

@Id
private int id;

private String author;

private String title;

//bi-directional many-to-one association to Comment
@OneToMany(mappedBy="article",fetch=FetchType.LAZY,cascade=CascadeType.ALL)
private List<Comment> comments = new ArrayList<Comment>();

public List<Comment> getComments() {
    return this.comments;
}

public void setComments(List<Comment> comments) {
    this.comments = comments;
}

public Comment addComment(Comment comment) {
    getComments().add(comment);
    comment.setArticle(this);

    return comment;
}

........
以下工程罚款:

    em.getTransaction().begin();
    Article article = new Article();
    article.setAuthor("Article Author");
    article.setTitle("Article Title");
    em.persist(article);

实际上,实体被持久化的顺序决定了
insert
语句的生成顺序,因此所有的行为都是文档化的。有关更多详细信息,请参见

Comment
首先被持久化(您首先显式地持久化它),然后
Article
将被级联持久化


正确的方法是首先持久化
文章
,正如您已经指出的那样。

实际上,实体持久化的顺序决定了
插入
语句的生成顺序,因此一切都按照文档的方式进行。有关更多详细信息,请参见

Comment
首先被持久化(您首先显式地持久化它),然后
Article
将被级联持久化


正确的方法是首先持久化
文章
,正如您已经指出的那样。

文章的ID是如何生成的?上面没有
@GeneratedValue
,您没有在“持久性代码”片段中设置它。你漏掉了吗?否则这就是问题所在。如果我只是持久化一篇文章,而没有显式地设置id(在原始帖子中添加的代码),它工作得很好…所以我猜id生成在这里不是问题。如何生成文章的id?上面没有
@GeneratedValue
,您没有在“持久性代码”片段中设置它。你漏掉了吗?否则这就是问题所在。如果我只是持久化一篇文章,而没有显式地设置id(在原始帖子中添加的代码),它工作得很好…所以我想id生成在这里不是问题。
    em.getTransaction().begin();
    Article article = new Article();
    article.setAuthor("Article Author");
    article.setTitle("Article Title");
    em.persist(article);