For somebody out there facing similar problem:
mapping files
User.hbm.xml
Code:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping package="com.exp.model">
<class name="User" table="TEST_USER">
<id name="userId" column="USERID">
<generator class="increment"/>
</id>
<property name="fullName" column="FULLNAME" type="string" />
<property name="userName" column="USERNAME" type="string" />
<property name="password" column="PASSWORD" type="string" />
<many-to-one name="billingAddress"
class="Address"
column="BILLING_ADDRESS_ID"
cascade="all"
unique="true"/>
</class>
</hibernate-mapping>
Address.hbm.xml
Code:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping package="com.exp.model">
<class name="Address" table="TEST_ADDRESS">
<id name="addressId" column="ADDRESSID">
<generator class="increment"/>
</id>
<property name="street" column="STREET" type="string" />
<property name="zipCode" column="ZIPCODE" type="string" />
<property name="city" column="CITY" type="string" />
</class>
</hibernate-mapping>
Code to test whether it added the address first then the user
Code:
public class UserProcessor {
public static void main(String[] args) throws Exception {
addNewUser();
}
private static void addNewUser() throws Exception {
User user = new User();
user.setFullName("Tina Roy");
user.setPassword("password");
user.setUserName("troy");
Address address = new Address();
address.setCity("Solana Beach");
address.setStreet("180 Rios Avenue");
address.setZipCode("123456");
user.setBillingAddress(address);
Session session = HibernateUtil.getSession();
Transaction tx = session.beginTransaction();
session.save(user);
tx.commit();
session.close();
}
}
generated sql in the log:
Hibernate: insert into TEST_ADDRESS (STREET, ZIPCODE, CITY, ADDRESSID) values (?, ?, ?, ?)
Hibernate: insert into TEST_USER (FULLNAME, USERNAME, PASSWORD, BILLING_ADDRESS_ID, USERID) values (?, ?, ?, ?, ?)