JPA:带有ManyToOne的CascadeType.PERSIST

时间:2016-01-23 05:44:06

标签: 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 Title");
    Comment comm1 = new Comment();
    comm1.setAuthor("Author1");
    comm1.setTitle("Title1");
    article.addComment(comm1);
    em.persist(comm1);
    em.getTransaction().commit();

我预计在字段上使用CascadeType.PERSIST会使持久性提供程序按照父(此处为Article)首先保留的顺序对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;
}

........

注释:

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

1 个答案:

答案 0 :(得分:0)

实际上,实体持久化的顺序决定了insert语句的生成顺序,因此所有内容的行为都符合记录。有关详细信息,请参阅this answer

首先保留

Comment(首先明确地保留它),然后通过级联保存Article

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