1

I am using Spring MVC, Hibernate to store 2 entities - FacilityMember and User. Business requirement is such that once entry is inserted into 'FacilityMember' then 'User' entry should get inserted with his email id as user name.

I have unidirectional mapping from FacilityMember to User. I need User->id for some further action inside my service layer. After hibernate persists I do get ID for FacilityMember but I get 0 for FacilityMember->User->Id.

Code snippet as follows:

My FacilityMember

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;

//other attributes 

@OneToOne(fetch = FetchType.EAGER)
@Fetch(FetchMode.SELECT)
@Cascade(CascadeType.SAVE_UPDATE)
@JoinColumn(name = "userId")
private User user;

//getters setters

My User entity

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NotNull
@Size(min = 4, max = 30)
private String username;

//getters setters

My service layer is having method level transaction which calls below Dao layer code.

User user = new User();
user.setUsername(userName);
facilityMember.setUser(user);
persist(facilityMember);
return facilityMember;

Inside service layer my facilityMember->id is having proper value but facilityMember->User->id is 0. Data gets stored properly into mysql tables.

Hibernate queries are executed in following manner

Insert FacilityMember ...
Insert User ..
Update FacilityMember ..

What's going wrong - how to get newly inserted id of my mapped entity ?

Thanks in advance

Manisha

user2869612
  • 607
  • 2
  • 10
  • 32
  • Try to call EntityManager.flush() before getting the user id. – Joachim Rohde Apr 28 '16 at 13:01
  • Thanks for the comment. I am using hibernate my persists method actually does: sessionFactory.getCurrentSession().persist(entity). But I am still unclear if I can get FacilityMember-> id in my service layer then why not FacilityMember->User->id ? – user2869612 Apr 28 '16 at 13:20
  • There is a difference between persist and flush (read e.g. here: http://stackoverflow.com/questions/17703312/what-does-entitymanager-flush-do-and-why-do-i-need-to-use-it) There is no ID yet for the user since it was not persisted in the database. That's why you should try to call flush to force Hibernate to write to the database (and therefore the ID of User will be known) – Joachim Rohde Apr 28 '16 at 13:41

0 Answers0