Pages

Mapping Components

Mapping Component

Let say user can have unique bank account details, consider the following relationship between User and BankAccount.


This aggregation is a stronger form of association. In java terms, this relationship is called composition but in object/relational model , there is no concept of composition. So it's better to keep these fields with User table.
BankDetails is a value type So it will not have identifier whereas User class is a entity type ,it must have identifier property.

Following are the User and BankDetails classes :

public class User {
private Long userId;
private String userName;
private String password;
private Date createdDate;
private Date modifieDate;
private BankDetails bankDetails;

// generate Getter and Setter method
}

public class BankDetails {  
private Long accountNo;
private String emailId;
private String dateOfBirth;

// generate Getter and Setter method

}

See the User.hbm.xml mapping metadata file :
<hibernate-mapping>

<class name="model.User" table="USER">
<id name="userId" column="USER_ID">
<generator class="increment"/>
</id>
<property name="userName" column="USER_NAME"/>
<property name="password" column="PASSWORD"/>
<property name="createdDate" column="CREATED_DATE"/>
<property name="modifiedDate" column="MODIFIED_DATE"/>

<component name="bankDetails" class="model.BankDetails">
<property name="accountNo" column="ACCOUNT_NO"/>
<property name="emailId" column="EMAIL_ID"/>
<property name="dateOfBirth" column="DATE_OF_BIRTH"/>
</component>
</class>
</hibernate-mapping>



When you try to run the following code :

public static void main(String... str) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction txn = session.beginTransaction();
User user = new User();
user.setUserName("Rahul");
user.setPassword("********");
user.setCreatedDate(new Date());
user.setModifiedDate(new Date());
BankDetails bankDetails = new BankDetails();
bankDetails.setAccountNo(23423421123083L);
bankDetails.setDateOfBirth("16-10-1987");
bankDetails.setEmailId("gavin.king2410@gmail.com");
user.setBankDetails(bankDetails);
session.saveOrUpdate(user);
txn.commit();
session.close();
HibernateUtil.shutDown();
}

it generates following hibernate comments :
Hibernate: insert into USER (USER_NAME, PASSWORD, CREATED_DATE, MODIFIED_DATE, ACCOUNT_NO, EMAIL_ID, DATE_OF_BIRTH, USER_ID) values (?, ?, ?, ?, ?, ?, ?, ?)

and User details is saved into the database with BankDetails information.















2 comments: