JPA:CascadeType.PERSIST 与 ManyToOne

JPA: CascadeType.PERSIST with ManyToOne

我正在使用 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 会使持久性提供程序按照这样的顺序对 SQL 进行排序,即先持久化父实体(此处为文章),然后再持久化子实体。但是我得到

Caused by: org.apache.openjpa.lib.jdbc.ReportingSQLException: Cannot add or update a child row: a foreign key constraint fails

在这种情况下,正确的处理方法是什么?

文章:

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

........

评论:

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

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;

private String author;

private String title;

//bi-directional many-to-one association to Article
@ManyToOne(cascade=CascadeType.PERSIST)
@JoinColumn(name="Article")
private Article article;

......

以下工作正常:

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

实际上,实体的持久化顺序决定了 insert 语句的生成顺序,因此一切都按照记录的方式运行。有关详细信息,另请参阅

Comment 首先被持久化(你明确地首先持久化它),然后 Article 将被级联持久化。

正如您已经指出的那样,正确的方法是首先坚持 Article