*
The moose likes Object Relational Mapping and the fly likes JPA cascade = CascadeType.ALL inserting 2 records in child table Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "JPA cascade = CascadeType.ALL inserting 2 records in child table " Watch "JPA cascade = CascadeType.ALL inserting 2 records in child table " New topic
Author

JPA cascade = CascadeType.ALL inserting 2 records in child table

Mohana Priya
Ranch Hand

Joined: Jan 16, 2005
Posts: 45
Issue : JPA cascade = CascadeType.ALL inserting 2 records in child table .


In User.java :

@OneToOne(cascade = CascadeType.ALL , mappedBy="user" , fetch=FetchType.EAGER)
@PrimaryKeyJoinColumn
private Role role ;


In Role.java :


@OneToOne(cascade= CascadeType.DETACH, fetch=FetchType.LAZY)
@LazyToOne(value = LazyToOneOption.NO_PROXY)
@JoinColumns({
@JoinColumn(name="user_id", referencedColumnName="user_id"),
})
private User user ;


Code :

Role role = new Role();
user.setRole(role);
dao.update(user); // This is inserting 2 records in Role table .


Why is this happening ?


SCJP 1.4<br />SCWCD 1.4
Bill Gorder
Bartender

Joined: Mar 07, 2010
Posts: 1646
    
    7

Please UseCodeTags

It looks like there is a user_id in the user table. Is that the id field? Why are you using @PrimaryKeyJoinColumn on the Role object?

The two things to remember when mapping bi-directional one-to-one

1. The @JoinColumn annotation goes on the mapping of the entity that is mapped to the table containing the join column, or the owner of the relationship. This might be on either side of the association.
2. The mappedBy element should be specified in the @OneToOne annotation in the entity that does not define a join column, or the inverse side of the relationship

Since it looks like Role contains the join column (user_id) it looks like it is the owner.

Role.java



User.java



Also when you do Role role = new Role(); where are you setting the user on the role object? When you call dao.update(user); is that a merge?


[How To Ask Questions][Read before you PM me]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: JPA cascade = CascadeType.ALL inserting 2 records in child table
 
Similar Threads
how to lazy load @onetoOne
fetching data :: eager Vs lazy
Composite like relationship - Mapping Question
problem with one-to-one mapping
uses a non-entity as target entity in relationship attribute