jn025
jn025

Reputation: 2895

Persistence OneToMany list not being updated on persist

I have a Categories and Posts entities and tables. I'm persisting a new Post which is successfully being added to the database however it seems the objects are not being added to the Categories List that is loaded.

Categories:

@OneToMany(fetch=FetchType.LAZY, mappedBy="categories")
public List<Post> getPosts() 
{
    return this.posts;
}

To add the new post to the database I'm simply doing:

Post newPost = new Post(..);
entityManager.persist(newPost);

So the new post gets added to the database however it seems the list of Posts that Categories has, isn't being updated until I restart the server or wait a few minutes.. This is how I fetch categories:

Category category = entityManager.find(Category.class, id);

And then I get the list of Posts from getPosts()

Upvotes: 0

Views: 67

Answers (1)

Steve C
Steve C

Reputation: 19445

From the information provided you have a uni-directional relationship:

Category --> * Post

For this scenario to work correctly, you would need access to the Category when creating and persisting the Post:

Category category = ...;
Post newPost = new Post(..);
category.getPosts().add(newPost);
entityManager.persist(newPost);
category = entityManager.merge(category);   // may not be needed if category is already managed

If it is a bidirectional relationship then you would also need:

newPost.setCategory(category);

prior to the persist(newPost).

Upvotes: 1

Related Questions