Pages

Table per concrete class with union

Table per concrete class with union

I will follow the same example for this post which i referred in the previous post. Now, we have we have three class (including abstract class) and one xml mapping metadata.
This strategy solves mostly problem of "Table per concrete class with implicit polymorphism" and it shares common identifier of all sub-classes.

we have modified the entity classes as follows:


public abstract class CreditCardHolder {

private Long creditCardHolderId;
private String owner;
//generate getters and setters method for above properties
}

public class CreditCardDetails extends CreditCardHolder {

private String number;
private String expMonth;
private String expYear;
        //generate getters and setters method for above properties
}

public class BankAccountDetails extends CreditCardHolder {

private String account;
private String bankName;
        //generate getters and setters method for above properties
}


Note: CreditCardHolder class is abstract. if a class is not defined as abstract So we have to define a saperate table for that class in the database. 

Now, only one xml mapping metadata file is required.


<hibernate-mapping package="table.per.concrete_class.with.union">
<class name="CreditCardHolder" abstract="true" dynamic-insert="true" dynamic-update="true">
<id name="creditCardHolderId" column="CREDIT_CARD_HOLDER_ID" type="long">
<generator class="identity"/> <!-- or increment-->
</id>

<property name="owner" column="OWNER"/> 

<union-subclass name="CreditCardDetails" table="CREDIT_CARD_DETAILS">
<property name="number" column="CREDIT_CARD_NUMBER"/>
<property name="expMonth" column="EXP_MONTH"/>
<property name="expYear" column="EXP_YEAR"/>
</union-subclass>

<union-subclass name="BankAccountDetails" table="BANK_ACCOUNT_DETAILS">
<property name="account" column="ACCOUNT_TYPE"/>
<property name="bankName" column="BANK_NAME"/>
</union-subclass>
</class>
</hibernate-mapping>
If you run the following code, 

public class HibernateTest {
private final static Logger LOGGER = Logger.getLogger(HibernateTest.class); 
/**
* @param args
*/
public static void main(String[] args) {
LOGGER.info("starting of main method");
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction txn = session.beginTransaction();
CreditCardDetails creditCard = new CreditCardDetails();
creditCard.setNumber("3423243234342");
creditCard.setOwner("Sachin Sharma");
creditCard.setExpMonth("10/18");
creditCard.setExpYear("2018");
BankAccountDetails bankAccountDetails = new BankAccountDetails();
bankAccountDetails.setAccount("saving");
bankAccountDetails.setBankName("SBI");
bankAccountDetails.setOwner("Sachin Sharma");
session.saveOrUpdate(creditCard);
session.saveOrUpdate(bankAccountDetails);
txn.commit();
session.close();
HibernateUtil.shutDown();
}
}
See the Hibernate generated statements on console :

17:43:12,899 INFO HibernateTest:19 - starting of main method
Oct 15, 2012 5:43:12 PM org.hibernate.cfg.Environment <clinit>
INFO: Hibernate 3.0rc1
Oct 15, 2012 5:43:12 PM org.hibernate.cfg.Environment <clinit>
INFO: hibernate.properties not found
Oct 15, 2012 5:43:12 PM org.hibernate.cfg.Environment <clinit>
INFO: using CGLIB reflection optimizer
Oct 15, 2012 5:43:12 PM org.hibernate.cfg.Environment <clinit>
INFO: using JDK 1.4 java.sql.Timestamp handling
Oct 15, 2012 5:43:12 PM org.hibernate.cfg.Configuration configure
INFO: configuring from resource: /hibernate.cfg.xml
Oct 15, 2012 5:43:12 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: Configuration resource: /hibernate.cfg.xml
Oct 15, 2012 5:43:13 PM org.hibernate.cfg.Configuration addResource
INFO: Mapping resource: table/per/concrete_class/with/union/CreditCardHolder.hbm.xml
Oct 15, 2012 5:43:13 PM org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
INFO: Mapping class: table.per.concrete_class.with.union.CreditCardHolder -> CREDITCARDHOLDER
Oct 15, 2012 5:43:13 PM org.hibernate.cfg.HbmBinder bindUnionSubclass
INFO: Mapping union-subclass: table.per.concrete_class.with.union.CreditCardDetails -> CE_CREDIT_CARD_DETAILS
Oct 15, 2012 5:43:13 PM org.hibernate.cfg.HbmBinder bindUnionSubclass
INFO: Mapping union-subclass: table.per.concrete_class.with.union.BankAccountDetails -> CE_BANK_ACCOUNT_DETAILS
Oct 15, 2012 5:43:13 PM org.hibernate.cfg.Configuration doConfigure
INFO: Configured SessionFactory: null
Oct 15, 2012 5:43:13 PM org.hibernate.cfg.Configuration secondPassCompile
INFO: processing extends queue
Oct 15, 2012 5:43:13 PM org.hibernate.cfg.Configuration secondPassCompile
INFO: processing collection mappings
Oct 15, 2012 5:43:13 PM org.hibernate.cfg.Configuration secondPassCompile
INFO: processing association property references
Oct 15, 2012 5:43:13 PM org.hibernate.cfg.Configuration secondPassCompile
INFO: processing foreign key constraints
Oct 15, 2012 5:43:13 PM org.hibernate.dialect.Dialect <init>
INFO: Using dialect: org.hibernate.dialect.MySQLDialect
Oct 15, 2012 5:43:13 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Maximum outer join fetch depth: 2
Oct 15, 2012 5:43:13 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Default batch fetch size: 1
Oct 15, 2012 5:43:13 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Generate SQL with comments: disabled
Oct 15, 2012 5:43:13 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Order SQL updates by primary key: disabled
Oct 15, 2012 5:43:13 PM org.hibernate.cfg.SettingsFactory createQueryTranslatorFactory
INFO: Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
Oct 15, 2012 5:43:13 PM org.hibernate.hql.ast.ASTQueryTranslatorFactory <init>
INFO: Using ASTQueryTranslatorFactory
Oct 15, 2012 5:43:13 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Query language substitutions: {}
Oct 15, 2012 5:43:13 PM org.hibernate.connection.C3P0ConnectionProvider configure
INFO: C3P0 using driver: null at URL: jdbc:mysql://localhost:3306/HibernateTest
Oct 15, 2012 5:43:13 PM org.hibernate.connection.C3P0ConnectionProvider configure
INFO: Connection properties: {autocommit=true, password=****, user=root}
Oct 15, 2012 5:43:13 PM org.hibernate.connection.C3P0ConnectionProvider configure
INFO: autocommit mode: true
Oct 15, 2012 5:43:13 PM org.hibernate.connection.C3P0ConnectionProvider configure
WARNING: No JDBC Driver class was specified by property hibernate.connection.driver_class
17:43:13,169 INFO MLog:80 - MLog clients using log4j logging.
17:43:13,397 INFO C3P0Registry:204 - Initializing c3p0-0.9.1.2 [built 21-May-2007 15:04:56; debug? true; trace: 10]
17:43:13,454 INFO AbstractPoolBackedDataSource:462 - Initializing c3p0 pool... com.mchange.v2.c3p0.PoolBackedDataSource@7b61fbf5 [ connectionPoolDataSource -> com.mchange.v2.c3p0.WrapperConnectionPoolDataSource@7d713a61 [ acquireIncrement -> 1, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, debugUnreturnedConnectionStackTraces -> false, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1bs1yqt8qruafse1ro6pj3|1340e79, idleConnectionTestPeriod -> 3000, initialPoolSize -> 5, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 300, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 20, maxStatements -> 100, maxStatementsPerConnection -> 0, minPoolSize -> 5, nestedDataSource -> com.mchange.v2.c3p0.DriverManagerDataSource@28473f2d [ description -> null, driverClass -> null, factoryClassLocation -> null, identityToken -> 1bs1yqt8qruafse1ro6pj3|1e16028, jdbcUrl -> jdbc:mysql://localhost:3306/HibernateTest, properties -> {autocommit=true, password=******, user=******} ], preferredTestQuery -> null, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false; userOverrides: {} ], dataSourceName -> null, factoryClassLocation -> null, identityToken -> 1bs1yqt8qruafse1ro6pj3|d3e973, numHelperThreads -> 3 ]
Oct 15, 2012 5:43:13 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC batch size: 15
Oct 15, 2012 5:43:13 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC batch updates for versioned data: disabled
Oct 15, 2012 5:43:13 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Scrollable result sets: enabled
Oct 15, 2012 5:43:13 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC3 getGeneratedKeys(): enabled
Oct 15, 2012 5:43:13 PM org.hibernate.transaction.TransactionFactoryFactory buildTransactionFactory
INFO: Using default transaction strategy (direct JDBC transactions)
Oct 15, 2012 5:43:13 PM org.hibernate.transaction.TransactionManagerLookupFactory getTransactionManagerLookup
INFO: No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
Oct 15, 2012 5:43:13 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Automatic flush during beforeCompletion(): disabled
Oct 15, 2012 5:43:13 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Automatic session close at end of transaction: disabled
Oct 15, 2012 5:43:13 PM org.hibernate.cfg.SettingsFactory createCacheProvider
INFO: Cache provider: org.hibernate.cache.EhCacheProvider
Oct 15, 2012 5:43:13 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Second-level cache: enabled
Oct 15, 2012 5:43:13 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Optimize cache for minimal puts: disabled
Oct 15, 2012 5:43:13 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Structured second-level cache entries: enabled
Oct 15, 2012 5:43:13 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Query cache: disabled
Oct 15, 2012 5:43:13 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Echoing all SQL to stdout
Oct 15, 2012 5:43:13 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Statistics: disabled
Oct 15, 2012 5:43:13 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Deleted entity synthetic identifier rollback: disabled
Oct 15, 2012 5:43:13 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Default entity-mode: pojo
Oct 15, 2012 5:43:13 PM org.hibernate.impl.SessionFactoryImpl <init>
INFO: building session factory
Oct 15, 2012 5:43:13 PM net.sf.ehcache.config.Configurator configure
WARNING: No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: jar:file:/D:/Anuj/Jars/HibernateLib/ehcache-1.1.jar!/ehcache-failsafe.xml
Exception in thread "main" java.lang.ExceptionInInitializerError
at util.HibernateUtil.<clinit>(HibernateUtil.java:21)
at com.HibernateTest.main(HibernateTest.java:20)
Caused by: org.hibernate.MappingException: Cannot use identity column key generation with <union-subclass> mapping for: table.per.concrete_class.with.union.BankAccountDetails
at org.hibernate.persister.entity.UnionSubclassEntityPersister.<init>(UnionSubclassEntityPersister.java:60)
at org.hibernate.persister.PersisterFactory.createClassPersister(PersisterFactory.java:61)
at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:199)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1043)
at util.HibernateUtil.<clinit>(HibernateUtil.java:19)
... 1 more

If you see the comments, identity or increment generator strategy is not supporting for "table per concrete class with union strategy". referred this link for more details. 

So to fix this problem, change the generator strategy to "hilo" and run again HibernateTest class.

<hibernate-mapping package="table.per.concrete_class.with.union">
<class name="CreditCardHolder" abstract="true" dynamic-insert="true" dynamic-update="true">
<id name="creditCardHolderId" column="CREDIT_CARD_HOLDER_ID" type="long">
<generator class="hilo"/> <!-- identity and increment do not support for table per concrete class with union strategy --> 
</id>
<property name="owner" column="OWNER"/> 
<union-subclass name="CreditCardDetails" table="CREDIT_CARD_DETAILS">
<property name="number" column="CREDIT_CARD_NUMBER"/>
<property name="expMonth" column="EXP_MONTH"/>
<property name="expYear" column="EXP_YEAR"/>
</union-subclass>
<union-subclass name="BankAccountDetails" table="BANK_ACCOUNT_DETAILS">
<property name="account" column="ACCOUNT_TYPE"/>
<property name="bankName" column="BANK_NAME"/>
</union-subclass>
</class>
</hibernate-mapping>

Now, see again hibernate generated SQL statements on console,

17:52:40,427 INFO HibernateTest:19 - starting of main method
Oct 15, 2012 5:52:40 PM org.hibernate.cfg.Environment <clinit>
INFO: Hibernate 3.0rc1
Oct 15, 2012 5:52:40 PM org.hibernate.cfg.Environment <clinit>
INFO: hibernate.properties not found
Oct 15, 2012 5:52:40 PM org.hibernate.cfg.Environment <clinit>
INFO: using CGLIB reflection optimizer
Oct 15, 2012 5:52:40 PM org.hibernate.cfg.Environment <clinit>
INFO: using JDK 1.4 java.sql.Timestamp handling
Oct 15, 2012 5:52:40 PM org.hibernate.cfg.Configuration configure
INFO: configuring from resource: /hibernate.cfg.xml
Oct 15, 2012 5:52:40 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: Configuration resource: /hibernate.cfg.xml
Oct 15, 2012 5:52:40 PM org.hibernate.cfg.Configuration addResource
INFO: Mapping resource: table/per/concrete_class/with/union/CreditCardHolder.hbm.xml
Oct 15, 2012 5:52:40 PM org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
INFO: Mapping class: table.per.concrete_class.with.union.CreditCardHolder -> CREDITCARDHOLDER
Oct 15, 2012 5:52:40 PM org.hibernate.cfg.HbmBinder bindUnionSubclass
INFO: Mapping union-subclass: table.per.concrete_class.with.union.CreditCardDetails -> CE_CREDIT_CARD_DETAILS
Oct 15, 2012 5:52:40 PM org.hibernate.cfg.HbmBinder bindUnionSubclass
INFO: Mapping union-subclass: table.per.concrete_class.with.union.BankAccountDetails -> CE_BANK_ACCOUNT_DETAILS
Oct 15, 2012 5:52:40 PM org.hibernate.cfg.Configuration doConfigure
INFO: Configured SessionFactory: null
Oct 15, 2012 5:52:40 PM org.hibernate.cfg.Configuration secondPassCompile
INFO: processing extends queue
Oct 15, 2012 5:52:40 PM org.hibernate.cfg.Configuration secondPassCompile
INFO: processing collection mappings
Oct 15, 2012 5:52:40 PM org.hibernate.cfg.Configuration secondPassCompile
INFO: processing association property references
Oct 15, 2012 5:52:40 PM org.hibernate.cfg.Configuration secondPassCompile
INFO: processing foreign key constraints
Oct 15, 2012 5:52:40 PM org.hibernate.dialect.Dialect <init>
INFO: Using dialect: org.hibernate.dialect.MySQLDialect
Oct 15, 2012 5:52:40 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Maximum outer join fetch depth: 2
Oct 15, 2012 5:52:40 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Default batch fetch size: 1
Oct 15, 2012 5:52:40 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Generate SQL with comments: disabled
Oct 15, 2012 5:52:40 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Order SQL updates by primary key: disabled
Oct 15, 2012 5:52:40 PM org.hibernate.cfg.SettingsFactory createQueryTranslatorFactory
INFO: Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
Oct 15, 2012 5:52:40 PM org.hibernate.hql.ast.ASTQueryTranslatorFactory <init>
INFO: Using ASTQueryTranslatorFactory
Oct 15, 2012 5:52:40 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Query language substitutions: {}
Oct 15, 2012 5:52:40 PM org.hibernate.connection.C3P0ConnectionProvider configure
INFO: C3P0 using driver: null at URL: jdbc:mysql://localhost:3306/HibernateTest
Oct 15, 2012 5:52:40 PM org.hibernate.connection.C3P0ConnectionProvider configure
INFO: Connection properties: {password=****, autocommit=true, user=root}
Oct 15, 2012 5:52:40 PM org.hibernate.connection.C3P0ConnectionProvider configure
INFO: autocommit mode: true
Oct 15, 2012 5:52:40 PM org.hibernate.connection.C3P0ConnectionProvider configure
WARNING: No JDBC Driver class was specified by property hibernate.connection.driver_class
17:52:40,699 INFO MLog:80 - MLog clients using log4j logging.
17:52:40,925 INFO C3P0Registry:204 - Initializing c3p0-0.9.1.2 [built 21-May-2007 15:04:56; debug? true; trace: 10]
17:52:40,982 INFO AbstractPoolBackedDataSource:462 - Initializing c3p0 pool... com.mchange.v2.c3p0.PoolBackedDataSource@baafe607 [ connectionPoolDataSource -> com.mchange.v2.c3p0.WrapperConnectionPoolDataSource@27e0928f [ acquireIncrement -> 1, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, debugUnreturnedConnectionStackTraces -> false, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1bs1yqt8qrumlp5cog2xw|1340e79, idleConnectionTestPeriod -> 3000, initialPoolSize -> 5, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 300, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 20, maxStatements -> 100, maxStatementsPerConnection -> 0, minPoolSize -> 5, nestedDataSource -> com.mchange.v2.c3p0.DriverManagerDataSource@d2b6975b [ description -> null, driverClass -> null, factoryClassLocation -> null, identityToken -> 1bs1yqt8qrumlp5cog2xw|1e16028, jdbcUrl -> jdbc:mysql://localhost:3306/HibernateTest, properties -> {password=******, autocommit=true, user=******} ], preferredTestQuery -> null, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false; userOverrides: {} ], dataSourceName -> null, factoryClassLocation -> null, identityToken -> 1bs1yqt8qrumlp5cog2xw|d3e973, numHelperThreads -> 3 ]
Oct 15, 2012 5:52:41 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC batch size: 15
Oct 15, 2012 5:52:41 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC batch updates for versioned data: disabled
Oct 15, 2012 5:52:41 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Scrollable result sets: enabled
Oct 15, 2012 5:52:41 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC3 getGeneratedKeys(): enabled
Oct 15, 2012 5:52:41 PM org.hibernate.transaction.TransactionFactoryFactory buildTransactionFactory
INFO: Using default transaction strategy (direct JDBC transactions)
Oct 15, 2012 5:52:41 PM org.hibernate.transaction.TransactionManagerLookupFactory getTransactionManagerLookup
INFO: No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
Oct 15, 2012 5:52:41 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Automatic flush during beforeCompletion(): disabled
Oct 15, 2012 5:52:41 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Automatic session close at end of transaction: disabled
Oct 15, 2012 5:52:41 PM org.hibernate.cfg.SettingsFactory createCacheProvider
INFO: Cache provider: org.hibernate.cache.EhCacheProvider
Oct 15, 2012 5:52:41 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Second-level cache: enabled
Oct 15, 2012 5:52:41 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Optimize cache for minimal puts: disabled
Oct 15, 2012 5:52:41 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Structured second-level cache entries: enabled
Oct 15, 2012 5:52:41 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Query cache: disabled
Oct 15, 2012 5:52:41 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Echoing all SQL to stdout
Oct 15, 2012 5:52:41 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Statistics: disabled
Oct 15, 2012 5:52:41 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Deleted entity synthetic identifier rollback: disabled
Oct 15, 2012 5:52:41 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Default entity-mode: pojo
Oct 15, 2012 5:52:41 PM org.hibernate.impl.SessionFactoryImpl <init>
INFO: building session factory
Oct 15, 2012 5:52:41 PM net.sf.ehcache.config.Configurator configure
WARNING: No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: jar:file:/D:/Anuj/Jars/HibernateLib/ehcache-1.1.jar!/ehcache-failsafe.xml
Oct 15, 2012 5:52:41 PM org.hibernate.impl.SessionFactoryObjectFactory addInstance
INFO: Not binding factory to JNDI, no JNDI name configured
Oct 15, 2012 5:52:41 PM org.hibernate.dialect.Dialect <init>
INFO: Using dialect: org.hibernate.dialect.MySQLDialect
Oct 15, 2012 5:52:41 PM org.hibernate.cfg.Configuration secondPassCompile
INFO: processing extends queue
Oct 15, 2012 5:52:41 PM org.hibernate.cfg.Configuration secondPassCompile
INFO: processing collection mappings
Oct 15, 2012 5:52:41 PM org.hibernate.cfg.Configuration secondPassCompile
INFO: processing association property references
Oct 15, 2012 5:52:41 PM org.hibernate.cfg.Configuration secondPassCompile
INFO: processing foreign key constraints
Oct 15, 2012 5:52:41 PM org.hibernate.cfg.Configuration secondPassCompile
INFO: processing extends queue
Oct 15, 2012 5:52:41 PM org.hibernate.cfg.Configuration secondPassCompile
INFO: processing collection mappings
Oct 15, 2012 5:52:41 PM org.hibernate.cfg.Configuration secondPassCompile
INFO: processing association property references
Oct 15, 2012 5:52:41 PM org.hibernate.cfg.Configuration secondPassCompile
INFO: processing foreign key constraints
Oct 15, 2012 5:52:41 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: Running hbm2ddl schema export
Oct 15, 2012 5:52:41 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: exporting generated schema to database
Oct 15, 2012 5:52:41 PM org.hibernate.connection.C3P0ConnectionProvider configure
INFO: C3P0 using driver: null at URL: jdbc:mysql://localhost:3306/HibernateTest
Oct 15, 2012 5:52:41 PM org.hibernate.connection.C3P0ConnectionProvider configure
INFO: Connection properties: {password=****, autocommit=true, user=root}
Oct 15, 2012 5:52:41 PM org.hibernate.connection.C3P0ConnectionProvider configure
INFO: autocommit mode: true
Oct 15, 2012 5:52:41 PM org.hibernate.connection.C3P0ConnectionProvider configure
WARNING: No JDBC Driver class was specified by property hibernate.connection.driver_class
17:52:41,614 INFO AbstractPoolBackedDataSource:462 - Initializing c3p0 pool... com.mchange.v2.c3p0.PoolBackedDataSource@2cfe5f6b [ connectionPoolDataSource -> com.mchange.v2.c3p0.WrapperConnectionPoolDataSource@6a6dce0 [ acquireIncrement -> 1, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, debugUnreturnedConnectionStackTraces -> false, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1bs1yqt8qrumlp5cog2xw|6ace81, idleConnectionTestPeriod -> 3000, initialPoolSize -> 5, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 300, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 20, maxStatements -> 100, maxStatementsPerConnection -> 0, minPoolSize -> 5, nestedDataSource -> com.mchange.v2.c3p0.DriverManagerDataSource@c9f9734 [ description -> null, driverClass -> null, factoryClassLocation -> null, identityToken -> 1bs1yqt8qrumlp5cog2xw|445dcf, jdbcUrl -> jdbc:mysql://localhost:3306/HibernateTest, properties -> {password=******, autocommit=true, user=******} ], preferredTestQuery -> null, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false; userOverrides: {} ], dataSourceName -> null, factoryClassLocation -> null, identityToken -> 1bs1yqt8qrumlp5cog2xw|10439a3, numHelperThreads -> 3 ]
Oct 15, 2012 5:52:41 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: schema export complete
Oct 15, 2012 5:52:41 PM org.hibernate.impl.SessionFactoryImpl checkNamedQueries
INFO: Checking 0 named queries
Hibernate: insert into CE_CREDIT_CARD_DETAILS (OWNER, CREDIT_CARD_NUMBER, EXP_MONTH, EXP_YEAR, CREDIT_CARD_HOLDER_ID) values (?, ?, ?, ?, ?)
Hibernate: insert into CE_BANK_ACCOUNT_DETAILS (OWNER, ACCOUNT_TYPE, BANK_NAME, CREDIT_CARD_HOLDER_ID) values (?, ?, ?, ?)
Oct 15, 2012 5:52:41 PM org.hibernate.impl.SessionFactoryImpl close
INFO: closing

Now, if you execute a polymorphic query against superclass as soon above :

public class HibernateTest {


private final static Logger LOGGER = Logger.getLogger(HibernateTest.class);

/**
* @param args
*/
public static void main(String[] args) {
LOGGER.info("starting of main method");
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction txn = session.beginTransaction();
Query query = session.createQuery("from CreditCardHolder where");
List list = query.list();
txn.commit();
session.close();
HibernateUtil.shutDown();
}
}

If superclass is non-abstract than additional table is required to hold the instance of super class.The advantage of this mapping strategy are clear, It generate a single SELECT SQL statement with From clause sub-query retrieves all instances of CreditCardHolder from all concrete class tables. A union is required to map the projection over the same columns. we have to pad and fill the non-existent column with NULL.

INFO: schema export complete
Oct 15, 2012 6:06:30 PM org.hibernate.impl.SessionFactoryImpl checkNamedQueries
INFO: Checking 0 named queries
Hibernate: 
select creditcard0_.CREDIT_CARD_HOLDER_ID as CREDIT1_, 
creditcard0_.OWNER as OWNER0_, 
creditcard0_.CREDIT_CARD_NUMBER as CREDIT1_1_, 
creditcard0_.EXP_MONTH as EXP2_1_, 
creditcard0_.EXP_YEAR as EXP3_1_, 
creditcard0_.ACCOUNT_TYPE as ACCOUNT1_2_, 
creditcard0_.BANK_NAME as BANK2_2_, 
creditcard0_.clazz_ as clazz_ 
from ( 
select null as BANK_NAME, 
EXP_YEAR, EXP_MONTH, CREDIT_CARD_NUMBER, 
OWNER, CREDIT_CARD_HOLDER_ID, null as ACCOUNT_TYPE, 
1 as clazz_ 
from CE_CREDIT_CARD_DETAILS 
union 
select BANK_NAME, null as EXP_YEAR, 
null as EXP_MONTH, null as CREDIT_CARD_NUMBER, 
OWNER, CREDIT_CARD_HOLDER_ID, 
ACCOUNT_TYPE, 2 as clazz_ 
from CE_BANK_ACCOUNT_DETAILS ) creditcard0_

Oct 15, 2012 6:06:30 PM org.hibernate.impl.SessionFactoryImpl close
INFO: closing






2 comments: