Hi,
I have a one-to-one mapping like below:
User.hbm.xml <class name="org.hibernate.tutorial.domain.User" table="user_i"> <id name="userId" column="user_id"> <generator class="assigned"/> </id> <one-to-one name="userDetails" class="org.hibernate.tutorial.domain.UserDetails" cascade="all" /> </class>
<class name="org.hibernate.tutorial.domain.UserDetails" table="user_details"> <id name="userId" column="user_id"> <generator class="foreign"> <param name="property">user</param> </generator> </id> <one-to-one name="user" class="org.hibernate.tutorial.domain.User" constrained="true" /> </class>
Below is the code used for saving user object User user = new User(); user.setUserId("testuser2"); user.setPassword("testpassword"); user.setUserType("S");
UserDetails userDetails = new UserDetails(); userDetails.setUserFirstName("fname"); /user.setUserDetails(userDetails); userDetails.setUser(user); for (int i = 0; i < 4; i++) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); Transaction tx = session.beginTransaction(); session.saveOrUpdate(user); tx.commit(); }
It works fine for the first time when I load my session, it inserts both user and user_details in the tables. But once I start a new session and try saving the same user object, it again tries to insert user details object which fails, as there is a already present in the database. Below is mapping used in .cfg.xml file <property name="hbm2ddl.auto">update</property>
How to overcome the abopve issue? DO i need to explicitly assign id to user details?Any kind of help will be appreciated here. Thanks
|