Hibernate creates duplicate entries in the database
I have a database structure which is something like the one described below.
"Universe" can contain any number of "Items". "Person" may have a "Box" which refers to one or more of the "Items" in the "Universe"
Universe, Items, Person, Box are all database tables. Box is like a join table for the Person and Items.
Note: I am using javax persistence API and hibernate
Now an Item can be created in the Universe and saved. A Person can have an entity in the Box for this Item and save the info for the Person. This works fine.
But my application desires to create an Item in the Universe but do not save it immediately. Now I am referring trying to associate this Item with the Person. I have a complete save method which tries to save all the contents in a transaction. Invoking this method I am getting two entries in the Items table for the same Item, one being referred by the Person and the other by the Universe.
Is there a way to make the Universe save the Item and make the Person refer to this Item through the usage of hibernate annotations and JPA.
Any ideas are welcome.
Am not good at editing the code. Please bear with me.
The Person class:
@Entity
@Table(name = "Person")
@Inheritance(strategy = InheritanceType.JOINED)
public class Person
{
private Integer myId;
private String myName;
private String Occupation;
/**
* Set of Items.
*/
private Set<Items> myItems = new HashSet<Items>();
@OneToMany
@JoinTable(name="Box",
joinColumns = @JoinColumn(name="person_id"),
inverseJoinColumns = @JoinColumn(name="item_id"))
@Cascade(value = {org.hibernate.annotations.CascadeType.DELETE_ORPHAN,
org.hibernate.annotations.CascadeType.ALL})
private Set<Items> getItems()
{
return myItems;
}
}
The table Box (the join table):
create table Box(
person_id int references Person(id) not null,
item_id int references Item(id) not null
)
The I开发者_运维技巧tems class:
@Entity
@Table(name = "Items")
@Inheritance(strategy = InheritanceType.JOINED)
public class Items
{
/**
* Database identifier.
*/
private Integer myDbId;
...
}
The table Universe has a one to many set of Items.
This is a big shot in the dark: use EntityManager#merge
. If you want a more precise answer, add more details to the question.
精彩评论