Tuesday, July 14, 2009

Can a single POJO class in Hibernate be mapped to multiple tables?

Question:Can a single POJO in Hibernate be mapped to multiple tables?

Ans: Yes a single POJO can be mapped to multiple tables.

Hibernate provides an easy way to do this.

Suppose we have an AccountDTO class and an AccountPOJO which needs to be mapped to two different tables

1)User_account 2)Admin_account

Here is the AccountDTO:

public class AccountDTO{

private int id;
private String login;
private String password:

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}
public String getLogin() {
return login;
}

public void setLogin(String login) {
this.login = login;
}
public int getID() {
return id;
}

public void setID(int clientID) {
this.id = clientID;
}

}

Here is the AccountPOJO :

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="com.digitalk.dto">
<class entity-name="User" table="User_account" name="AccountDTO">
<id name="id" type="integer" column="ID">
<generator class="increment"></generator>
</id>

<property name="login" type="string" column="LOGIN"></property>
<property name="password" type="string" column="PASSWORD"></property>


</class>
<class entity-name="Admin" table="Admin_account" name="AccountDTO">
<id name="id" type="integer" column="ID">
<generator class="increment"></generator>
</id>

<property name="login" type="string" column="LOGIN"></property>
<property name="password" type="string" column="PASSWORD"></property>
</class>

</hibernate-mapping>

(A) From the AccountPOJO you can see that this single POJO is mapped to two different tables
1)User_account 2)Admin_account

Now when you want to save the instance of the AccountDTO class in User_account table
then do the following steps:
1)create an instance of AccountDTO class
AccountDTO account=new AccountDTO();
2)set the properties.
3)create a hibernate session

4) Then save the object as
session.save("User",account);

(B)Now if you want to save the AccountDTO instance to Admin_account table then do the following:

1)create an instance of AccountDTO class
AccountDTO account=new AccountDTO();
2)set the properties.
3)create a hibernate session

4) Then save the object as
session.save("Admin",account);

From above you can see the only difference is in step 4

i.e you have to use entity-name instead of class name.

Similarly you can perform update,delete ond other operation using entity-name.

1 comment: