Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JPA: Is it possible to update existing entities automatically?

 
Kenneth Gustafsson
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have an entity called TreeNode which represents a node in a tree structure.

It has references to its parent (mainTreeNode) as well so its children (childTreeNodes).

To specify this using JPA I choose to have mainTreeNode as a @ManyToOne relationship mapping and childTreeNodes as a @OneToMany relationship mapping. Where the children can be defined using the mainTreeNode.



It seems to work, as in I get no error when starting the server and the tables are created as expected (with only a mainTreeNode column and no relationship table for childTreeNodes).

I get a problem when I:

1. Create the root TreeNode t1 (it has no mainTreeNode) and persist it
2. Add a child TreeNode t2 which has t1 as its mainTreeNode (parent) and persist it
3. Use t1.getChildTreeNodes() as it doesn't know that t2 has it as its mainTreeNode.

Is there a way to "automatically" update t1 with the new information available when t2 was persisted?
 
Cameron Wallace McKenzie
author and cow tipper
Saloon Keeper
Posts: 4968
1
Hibernate Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm just wondering if this isn't one of those solutions where a CascadeType could be added to the association and solve all of your problems?

It is quite cumbersome to save, delete, or reattach individual objects, especially if you deal with a graph of associated objects. A common case is a parent/child relationship.

For each basic operation of the entity manager - including persist(), merge(), remove(), refresh() - there is a corresponding cascade style. Respectively, the cascade styles are named PERSIST, MERGE, REMOVE, REFRESH. If you want an operation to be cascaded to associated entity (or collection of entities), you must indicate that in the association annotation:


Understanding the CascadeType Options in Hibernate

Here's some JavaDoc:

Hibernate JavaDoc for CascadeType Enum

And here's a one-to-many mapped relationship that uses the CascadeType.ALL enum value to persist entities:

Hibernate Example Using CascadeType.ALL in a JPA Mapped One to Many Association

@OneToMany(mappedBy="team",
targetEntity=Player.class,
fetch=FetchType.EAGER, cascade = CascadeType.ALL)

-Cameron McKenzie
[ May 12, 2008: Message edited by: Cameron Wallace McKenzie ]
 
James Sutherland
Ranch Hand
Posts: 553
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You must maintain both sides of bi-directional relationships in JPA (and Java in general).

See,
http://en.wikibooks.org/wiki/Java_Persistence/Relationships
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic