Yes, I tried this ,it is possible to save and retrieve data into two tables using one pojo class.
One POJO Class mapped to Two Tables using Hibernate-polymorphism support
First
Create PrimaryEntityUserA.java Pojo and its hbm file
PrimaryEntityUserA.hbm.xml Mention `<class
name="PrimaryEntityUserA"
table="user_a"
entity-name ="PrimaryEntityUserA" >`
Second
Create SecondaryEntityUserB.hbm.xml Mention `<class
name="PrimaryEntityUserA"
table="user_b"
entity-name ="SecondaryEntityUserB"
polymorphism = "explicit" >`
To save
PrimaryEntityUserA myObject = new PrimaryEntityUserA();
myObject.setId( new Long( 10 ) );
myObject.setName( "Tayaba" );
String entityName = "PrimaryEntityUserA";
session.save( entityName, myObject );
entityName = "SecondaryEntityUserB";
session.save( entityName, myObject );>
To Retrieve
List<PrimaryEntityUserA> usersA=LuminaHibernateUtil.getUtil().getList(session.createQuery( "from PrimaryEntityUserA a" ) );
if ( !usersA.isEmpty() ) {
for ( PrimaryEntityUserA a : usersA ) {
System.out.println( "Name from first table \t" + a.getName());
}
}
List<PrimaryEntityUserA> usersB =LuminaHibernateUtil.getUtil().getList(session.createQuery( "from SecondaryEntityUserB a" ) );
if ( !usersB.isEmpty() ) {
for ( PrimaryEntityUserA b : usersB ) {
System.out.println( "Name from sesond table \t" + b.getName() );
}
}
Conclusion: We can use 2 different tables and entity-name attribute inside both hbm files and mention same name attribute value, also mention polymorphism = "explicit" inside secondaryentity.hbm.xml.
Please find useful links for the same:
http://snaike.blogspot.in/2009/04/mapping-java-object-to-two-tables-using.html
[https://coderanch.com/t/492558/databases/Mapping-POJO-table-Hibernate-XML]
Regards
Naziya Tayaba