Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Mohana Priya
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ?
 
Bill Gorder
Bartender
Posts: 1682
7
Android IntelliJ IDE Linux Mac OS X Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic