• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Rob Spoor
  • Bear Bibeault
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:
  • Frits Walraven
  • Himai Minh

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

 
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ?
 
Bartender
Posts: 1682
7
Android Mac OS X IntelliJ IDE Spring Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
reply
    Bookmark Topic Watch Topic
  • New Topic