JPA entity relations are not populated after .persist()

Posted by Tomik on Stack Overflow See other posts from Stack Overflow or by Tomik
Published on 2011-03-13T00:07:03Z Indexed on 2011/03/13 0:10 UTC
Read the original article Hit count: 96

Filed under:

Hello, this is a sample of my two entities:

@Entity
public class Post implements Serializable {
    @OneToMany(mappedBy = "post", fetch = javax.persistence.FetchType.EAGER)
    @OrderBy("revision DESC")
    public List<PostRevision> revisions;

@Entity(name="post_revision")
public class PostRevision implements Serializable {
    @ManyToOne
    public Post post;

    private Integer revision;

    @PrePersist
    private void prePersist() {
        List<PostRevision> list = post.revisions;

        if(list.size() >= 1)
            revision = list.get(list.size() - 1).revision + 1;
        else
            revision = 1;
    }

So, there's a "post" and it can have several revisions. During persisting of the revision, entity takes a look at the list of the existing revisions and finds the next revision number. Problem is that Post.revisions is NULL but I think it should be automatically populated. I guess there's some kind of problem in my source code but I don't know where. Here's my "persistence" code:

Post post = new Post();
PostRevision revision = new PostRevision();
revision.post = post;

em.persist(post);
em.persist(revision);
em.flush();

I think that after persisting "post", it becomes "managed" and all the relations should be populated from now on.

Thanks for help!

(Note: public attributes are just for demonstration)

© Stack Overflow or respective owner

Related posts about jpa