hibernate is updating in the middle of selects - java

I have a legacy web app that I am maintaining. It started out as Java 1.4, but I've compiled it to Java5. We're using Spring+Hibernate. I'm not using annotations yet. I'm sticking with XDoclet for now. In it, I have an object graph that looks like this:
Job 1:m Operations 1:m Activities 1:m Transactions
Those Transactions are NOT J2EE transactions. We're just documenting the workflow from one Activity to another.
In HttpRequest#1, I update a couple of Activities and create a new Transaction. Then in HttpRequest#2, I redisplay the entire Job. What I am seeing at this point is the usual SELECT statements for the Job, Operations and Activities, but then I'm seeing some UPDATE statements for the Transactions. It turns out those updates are reverting the Transactions back to their previous states, discarding the latest updates.
Why in the world is Hibernate doing this?
As requested, here's the .hbm.xml file:
<hibernate-mapping>
<class name="ActivityTransaction" table="imed_if_move_transactions"
lazy="false" mutable="true">
<cache usage="nonstrict-read-write" />
<id name="id" column="IF_MOVE_TRANSACTION_ID" type="java.lang.Long">
<generator class="sequence">
<param name="sequence">IMED_IF_MOVE_TRANSACTIONS_S</param>
</generator>
</id>
<property name="activityActionKey" type="java.lang.String"
update="true" insert="true" column="ACTIVITY_ACTION_KEY" />
<property name="approvalStatus" type="int" update="true"
insert="true" column="APPROVAL_STATUS" />
<property name="authorizedBy" type="java.lang.Long" update="true"
insert="true" column="AUTHORIZATION_ID" />
<many-to-one name="authorizedByUser"
class="UserModel" cascade="none"
outer-join="false" update="false" insert="false" not-found="ignore"
fetch="select" column="AUTHORIZATION_ID" />
<property name="date" type="java.util.Date" update="true"
insert="true" column="JOA_TRANSACTION_DATE" />
<many-to-one name="from"
class="JobOpActivity" cascade="none"
outer-join="false" update="true" insert="true" fetch="select"
column="FM_JOB_OP_ACTIVITY_ID" />
<property name="fromIntraActivityStepType" type="java.lang.Integer"
update="true" insert="true" column="FM_INTRAACTIVITY_STEP_TYPE" />
<property name="fromIntraOperationStepType" type="java.lang.Integer"
update="true" insert="true" column="FM_INTRAOPERATION_STEP_TYPE" />
<property name="fromOperationSeqNum" type="java.lang.Integer"
update="true" insert="true" column="FM_OPERATION_SEQ_NUM" />
<many-to-one name="job" class="Job"
cascade="none" outer-join="false" update="true" insert="true" fetch="select"
column="WIP_ENTITY_ID" />
<property name="operationEndDate" type="java.util.Date"
update="true" insert="true" column="OP_END_DATE" />
<property name="operationStartDate" type="java.util.Date"
update="true" insert="true" column="OP_START_DATE" />
<many-to-one name="organization" class="Organization"
cascade="none" outer-join="false" update="true" insert="true" fetch="select"
column="ORGANIZATION_ID" />
<property name="processingStatus" type="java.lang.String"
update="true" insert="true" column="PROCESS_FLAG" />
<property name="quantity" type="int" update="true" insert="true"
column="TRANSACTION_QUANTITY" />
<property name="reasonId" type="java.lang.Long" update="true"
insert="true" column="REASON_ID" />
<property name="reference" type="java.lang.String" update="true"
insert="true" column="REFERENCE" />
<property name="scrapAccountId" type="java.lang.Long" update="true"
insert="true" column="SCRAP_ACCOUNT_ID" />
<property name="spsaId" type="java.lang.Long" update="true"
insert="true" column="SPSA_ID" />
<many-to-one name="to"
class="JobOpActivity" cascade="none"
outer-join="false" update="true" insert="true" fetch="select"
column="TO_JOB_OP_ACTIVITY_ID" />
<property name="toIntraActivityStepType" type="java.lang.Integer"
update="true" insert="true" column="TO_INTRAACTIVITY_STEP_TYPE" />
<property name="toIntraOperationStepType" type="java.lang.Integer"
update="true" insert="true" column="TO_INTRAOPERATION_STEP_TYPE" />
<property name="toOperationSeqNum" type="java.lang.Integer"
update="true" insert="true" column="TO_OPERATION_SEQ_NUM" />
<property name="typeId" type="java.lang.Long" update="true"
insert="true" column="TRANSACTION_TYPE_ID" />
<property name="webKeyEntryId" type="java.lang.String"
update="true" insert="true" column="WEB_KEY_ENTRY_ID" />
<property name="issueMaterial" type="true_false" update="true"
insert="true" column="MATERIAL_ISSUE" />
<property name="createDate" type="java.util.Date" update="true"
insert="true" column="CREATION_DATE" />
<property name="createdBy" type="java.lang.Integer" update="true"
insert="true" column="CREATED_BY" />
<property name="lastUpdateDate" type="java.util.Date" update="true"
insert="true" column="LAST_UPDATE_DATE" />
<property name="lastUpdatedBy" type="java.lang.Integer"
update="true" insert="true" column="LAST_UPDATED_BY" />
</class>
</hibernate-mapping>
And here's an example transaction setup:
<bean id="moldingActivitiesService" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager" ref="etrack2ProviderTransactionManager"/>
<property name="target" ref="moldingActivitiesServiceTarget"/>
<property name="transactionAttributes">
<props>
<prop key="*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>

From some Hibernate Javadoc document on Google http://ajava.org/online/hibernate3api/org/hibernate/FlushMode.html:
AUTO
public static final FlushMode AUTO
The Session is sometimes flushed before query execution in order to ensure that queries never return stale state. This is the default flush mode.
Every modification you are doing on a JPA-managed entity is done in a persistent context. That means Hibernate is assuming that the things that you modify in your entity are safe to be committed. So when you select data from the same entity or related entities, in this mode Hibernate puts consistency of your changes over everything else. So it flushes and then does the read to reflect your changes correctly. If you do not want to have this behavior you can do two things:
disable auto-commit (which I prefer, but it is some kind of a JPA convention, so make up your mind). The downside of this approach is that you have to do more by hand depending on your configuration. The upside is, that everything is much more explicit and less magic
change your code that you collect the data you need first. Also this would make your code much cleaner. Because it would work like the basic computer science pattern everybody understands: Input, Computation, Output. Your mixing those things up, which is the reason why the default mode does not work.
Edit: On how to use Spring's PlatformTransactionManager best without using annotations I would recommend the TransactionTemplate: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/transaction.html#tx-prog-template
Just inject your PlatformTransactionManager (Hibernate) there and use it to abstract from the transaction handling.

Depending on your FLUSHMODE you will see this, because whenever you do a query, hibernate will normally guess as to whether it should FLUSH to get a clean and consistent read.

Ok, finally found the problem. Here's a more complete flow:
I have Controller C1, Manager M1, Manager M2 and Persister P1. M1 and M2 have managed transactions as I stated above, using TransactionProxyFactoryBean.
C1.methodA() calls M1.methodB() which calls P1.methodC()
C1.methodA() then calls M2.methodD(), which then calls M1.methodE() which calls P1.methodF().
See the problem yet?
It happens when M1.methodD calls M1.methodE(). What I think happens is that since both M1 and M2 are transaction managed, two transactions are created, one for each call. Those two transactions battle it out for which one has the true state of the system, with neither one truly winning.

Related

How to optimize the insert query time using hiberate?

I have about 1.4 million records of data but it is taking more than 3hr to insert them. I cannot seems to find the problem to it.
I read up and change from identity to sequence. It only improved by a little but it still take quite a long time to finish insert.
I am using:
Hibernate 5
Spring 4
mssql 2014
Wildfly 10
applicationContext-hibernate.xml
<tx:advice id="txAdvice">
<!-- the transactional semantics... -->
<tx:attributes>
<tx:method name="*_TransNew" propagation="REQUIRES_NEW" />
<tx:method name="*_NoTrans" propagation="NEVER" />
<tx:method name="create*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="generate*" propagation="REQUIRED" />
<tx:method name="get*" propagation="REQUIRED" />
<tx:method name="is*" propagation="REQUIRED" />
<!-- other methods use the default transaction settings (see below) -->
<tx:method name="*" read-only="true" />
</tx:attributes>
</tx:advice>
<!-- ensure that the above transactional advice runs for any execution of
an operation defined by the following -->
<aop:config>
<aop:pointcut id="demoServiceOperations"
expression="execution(* com.test.*.*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="demoServiceOperations" />
</aop:config>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServer2012Dialect</prop>
<prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.jdbc.batch_size">50</prop>
<prop key="hibernate.order_inserts">true</prop>
<prop key="hibernate.order_updates">true</prop>
<prop key="hibernate.c3p0.min_size">5</prop>
<prop key="hibernate.c3p0.max_size">20</prop>
<prop key="hibernate.c3p0.timeout">1800</prop>
<prop key="hibernate.c3p0.max_statements">50</prop>
</props>
</property>
</bean>
Umts.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Nov 22, 2016 11:36:21 AM by Hibernate Tools 5.2.0.Beta1 -->
<hibernate-mapping>
<class name="com.test.domain.Umts" table="TBLDM_UMTS" schema="dbo" catalog="DEMO" optimistic-lock="version" dynamic-update="true">
<id name="umtsId" type="java.lang.Integer">
<column name="UMTS_ID" />
<generator class="org.hibernate.id.enhanced.SequenceStyleGenerator">
<param name="optimizer">pooled-lo</param>
<param name="increment_size">1</param>
<param name="sequence_name">UMTS_SEQ</param>
</generator>
</id>
<property name="cid" type="java.lang.Integer">
<column name="CI" not-null="true" />
</property>
<property name="channelNo" type="java.lang.Integer">
<column name="UARFCN" />
</property>
<property name="signalStrength" type="java.lang.Double">
<column name="EC_IO" precision="53" scale="0" />
</property>
<property name="sc" type="java.lang.Integer">
<column name="SC" />
</property>
<property name="latitude" type="java.lang.Double">
<column name="LATITUDE" precision="53" scale="0" />
</property>
<property name="longitude" type="java.lang.Double">
<column name="LONGITUDE" precision="53" scale="0" />
</property>
<property name="mcc" type="java.lang.Integer">
<column name="MCC" not-null="true" />
</property>
<property name="mnc" type="java.lang.Integer">
<column name="MNC" not-null="true" />
</property>
<property name="recvDate" type="date">
<column name="RECV_DATE" length="10" />
</property>
<property name="recvTime" type="time">
<column name="RECV_TIME" length="16" />
</property>
</class>
</hibernate-mapping>
Service class:
public void process(List<Umts> umtsList)
{
for (int i = 0; i < umtsList.size(); i = i + PropertiesUtil.MAX_COMMIT_COUNT)
{
int min = i;
int max = i + PropertiesUtil.MAX_COMMIT_COUNT;
if (max > umtsList.size())
{
max = umtsList.size();
}
createUmts_TransNew(umtsList.subList(min, max));
}
}
#Override
public void createUmts_TransNew(Collection list)
{
// TODO Auto-generated method stub
umtsDAO.saveAll(list);
}
DAO class:
#Transactional
public void saveAll(Collection collection)
{
log.debug("** save all");
try
{
if (collection != null && collection.size() > 0)
{
for (Object obj : collection)
{
sessionFactory.getCurrentSession().saveOrUpdate(obj);
}
}
}
catch (RuntimeException re)
{
log.error("** save all failed", re);
throw re;
}
}
** Edited
Does connection pool plays a part here? Meaning does connection pool helps with the performance? Do i need to add the jar file to the wildfly 10 or to application itself?
First off, try increasing the pooled-lo value. Since you set it to 1, there is no optimisation/pooling going on - since every ID that needs to be fetched needs a call to the DB to get the actual value. If you have a bigger increment size, hibernate will pre-fetch/reserve a block of ID's to use for new entities, without a per-entity round-trip.
Not sure how the code you posted is executed, but I'm assuming you're inserting them sequentially in a single thread. You can:
Use a thread-pool in which each thread takes a number of items from the list/queue to insert.
The items inserted in a single transaction by one thread has ideally same size as the configured hibernate batch size to again, minimize roundtrips.
Ensure the number of threads in the pool is in par with the connection pool size, so you don't end up blocking the worker threads when waiting for a connection.
Ensure connection pool size is reasonable for the load your server can take and use a good connection pool (eg. HikariCP). Here is an interesting writeup on connection pool size.

Hibernate : why createQuery() appends package name to the Entity Name?

I am trying to query database from two Different Tables i.e.
query = "select rbt.rbtCode, rbt.maskedName, cmas.catId, cmas.maskedName " +
"from CrbtRbt rbt, CrbtCategoryMaster cmas " +
"where rbt.playable='Y' and rbt.showOnWeb='Y' and rbt.rbtCode!=0 " +
"and rbt.catId=cmas.catId";
but when I pass this query through session.createQuery(query);
It appends package name to the next in coming Entity Name i.e.
select rbt.rbtCode, rbt.maskedName, cmas.catId, cmas.maskedName
from CrbtRbt rbt, com.telemune.toolGeneratedPojos.CrbtCategoryMaster cmas
where rbt.playable='Y' and rbt.showOnWeb='Y' and rbt.rbtCode!=0 and rbt.catId=cmas.catId
and gives the following Exception:
org.hibernate.hql.internal.ast.QuerySyntaxException: CrbtRbt is not mapped [select rbt.rbtCode, rbt.maskedName, cmas.catId, cmas.maskedName from CrbtRbt rbt, com.telemune.toolGeneratedPojos.CrbtCategoryMaster cmas where rbt.playable='Y' and rbt.showOnWeb='Y' and rbt.rbtCode!=0 and rbt.catId=cmas.catId]
at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:180)
at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:110)
at org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:93)
at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:325)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3252)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3141)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:694)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:550)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:287)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:235)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:248)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:183)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:101)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:119)
at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:214)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:192)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1537)
at com.telemune.generator.TestQuery.select(TestQuery.java:114)
at com.telemune.generator.PojoGenerator.main(PojoGenerator.java:191)
But if I query the Entities One By One it shows the desired result successfully.
i.e.
select rbt.rbtCode, rbt.maskedName
from CrbtRbt rbt
where rbt.playable='Y' and rbt.showOnWeb='Y' and rbt.rbtCode!=0;
gives desired result.
Can anyone Explain what I can do?
here is some example code:
Query Code
hql = session.createQuery(query);
hql.setMaxResults( querySchema.getMaxRes() );
list=hql.list();
For information I have done All the Mappings and included all the libraries very carefully no chance of any mistake.
UPDATE
As I said I have done the mappings carefully but someone may have doubts so here is the mapping:
<hibernate-mapping>
<class name="com.telemune.toolGeneratedPojos.CrbtCategoryMaster" schema="SDP" table="CRBT_CATEGORY_MASTER">
<id name="catId" type="java.lang.Integer">
<column name="CAT_ID" precision="4" scale="0" />
<generator class="assigned" />
</id>
<property column="SHOW_IN_SMS" name="showInSms" type="java.lang.String" />
<property column="SHOW_ON_WEB" name="showOnWeb" type="java.lang.String" />
<property column="PLAYABLE" name="playable" type="java.lang.String" />
<property column="STATUS" name="status" type="java.lang.String" />
<property column="IMAGE_PATH" name="imagePath" type="java.lang.String" />
<property column="DESCRIPTION" name="description" type="java.lang.String" />
<property column="MASKED_NAME" name="maskedName" type="java.lang.String" />
<property column="IVR_FILEPATH_1" name="ivrFilepath1" type="java.lang.String" />
<property column="IVR_FILEPATH" name="ivrFilepath" type="java.lang.String" />
<property column="MASKED_NAME_1" name="maskedName1" type="java.lang.String" />
</class></hibernate-mapping>
and for CRBT_RBT:
<hibernate-mapping>
<class name="com.telemune.toolGeneratedPojos.CrbtRbt" schema="SDP" table="CRBT_RBT">
<id name="rbtCode" type="java.lang.Integer">
<column name="RBT_CODE" precision="10" scale="0" />
<generator class="assigned" />
</id>
<property column="PLAYABLE" name="playable" type="java.lang.String" />
<property column="OTHER" name="other" type="java.lang.Integer" />
<property column="IMAGE_PATH" name="imagePath" type="java.lang.String" />
<property column="RBT_ORDER" name="rbtOrder" type="java.lang.Integer" />
<property column="VALIDITY_PERIOD" name="validityPeriod" type="java.lang.Integer" />
<property column="LYRICIST" name="lyricist" type="java.lang.String" />
<property column="APPROVED_BY" name="approvedBy" type="java.lang.String" />
<property column="PREV_CAT_ID" name="prevCatId" type="java.lang.Integer" />
<property column="RELEASE_YEAR" name="releaseYear" type="java.lang.Integer" />
<property column="COMPOSER" name="composer" type="java.lang.String" />
<property column="SHOW_ON_WEB" name="showOnWeb" type="java.lang.String" />
<property column="MASKED_NAME" name="maskedName" type="java.lang.String" />
<property column="CONTENT_PROVIDER_CODE" name="contentProviderCode" type="java.lang.Integer" />
<property column="CREATE_DATE" name="createDate" type="java.sql.Date" />
<property column="IVR_FILEPATH" name="ivrFilepath" type="java.lang.String" />
<property column="CORP_ID" name="corpId" type="java.lang.Integer" />
<property column="SHOW_IN_SMS" name="showInSms" type="java.lang.String" />
<property column="ALBUM_NAME" name="albumName" type="java.lang.String" />
<property column="NOKIA" name="nokia" type="java.lang.Integer" />
<property column="STATUS" name="status" type="java.lang.String" />
<property column="FILE_PATH" name="filePath" type="java.lang.String" />
<property column="REFERENCE_ID" name="referenceId" type="java.lang.Integer" />
<property column="CHARGING_CODE" name="chargingCode" type="java.lang.Integer" />
<property column="RBT_NICK" name="rbtNick" type="java.lang.String" />
<property column="APPROVAL_DATE" name="approvalDate" type="java.sql.Date" />
<property column="CAT_ID" name="catId" type="java.lang.Integer" />
<property column="RBT_SCORE" name="rbtScore" type="java.lang.Integer" />
<property column="ARTIST_NAME" name="artistName" type="java.lang.String" />
</class>
</hibernate-mapping>
I don't think there is any mistake in the mapping.
Hibernate.cfg.xml :
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.password">sdp</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#10.168.2.127:1521:mastera</property>
<property name="hibernate.connection.username">sdp</property>
<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
<mapping resource="com/telemune/toolGeneratedPojos/CrbtRbt.hbm.xml"/>
<mapping resource="com/telemune/toolGeneratedPojos/CrbtCategoryMaster.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Well, I got this.
SessionFactory getSessionFactory(className) {
try {
configuration.addResource( className + ".hbm.xml" );
}catch (Exception e) {
e.printStackTrace();
}
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
return configuration.buildSessionFactory(serviceRegistry);
here is the code to add .hbm.xml file,programatically, for each class while creating session factory.
try {
sessionFactory = ...getSessionFactory(className);
session = sessionFactory.openSession();
}
catch (Exception e) {
e.printStackTrace();
}
the problem with this code was that:
1. It was building a new session factory for each call(of getSessionFactory(classname)).
2. a new session was opened every time.
So, only the mapping of last class added to configuration was added as a resource and that's why its was searching the other classes by appending the packageName to it's name.
What I did is:
I just counted the no of mapping files in the package and added them with the help of a loop in the same session factory.
And it worked.
Here is the way:
File file = new File(packageName.replace(".", "/"));
for(File file1 : file.listFiles()){
if(file1.getName().trim().substring(file1.getName().trim().lastIndexOf("."),
file1.getName().trim().length()).equalsIgnoreCase(".xml")){
configuration.addResource( packageName.replaceAll("\\.", "/") + "/" + file1.getName() );
}
}
It was just a silly mistake.

Association references unmapped class hibernate

The configuration for Affiliate class is:
<class name="AffiliatesDO" table="AFFILIATES">
<id name="affiliateId" column="affiliate_id" type="java.lang.String">
<generator class="assigned" />
</id>
<property name="customerId" column="customer_id" type="int" />
<property name="affiliateType" column="affiliate_type" type="java.lang.String" />
<property name="site" column="site" type="java.lang.String" />
<property name="status" column="status" type="java.lang.String" />
<property name="createdBy" column="created_by" type="java.lang.String" />
<property name="creationDate" column="creation_date" type="java.util.Date" />
<property name="lastUpdatedBy" column="last_updated_by" type="java.lang.String" />
<property name="lastUpdated" column="last_updated" type="java.util.Date" />
<set name="address" lazy="true" inverse="true" order-by="address_id asc">
<key column="address_id"/>
<one-to-many class="AddressDO"/>
</set>
</class>
The Configuration for Address class is
<class name="Address"
table="Address">
<id name="addressId" column="address_id"
type="java.lang.String">
<generator class="assigned" />
</id>
<property name="name" column="name" type="java.lang.String" />
<property name="address1" column="address1" type="java.lang.String" />
<property name="phone" column="phone" type="java.lang.String" />
<property name="landLineNumber" column="land_line_number" type="java.lang.String" />
<property name="faxNumber" column="fax_number" type="java.lang.String" />
</class>
I am getting the below error
org.hibernate.MappingException: Association references unmapped class: com.infibeam.customerservice.dbObjects.AddressDO
at org.hibernate.cfg.HbmBinder.bindCollectionSecondPass(HbmBinder.java:2370)
at org.hibernate.cfg.HbmBinder$CollectionSecondPass.secondPass(HbmBinder.java:2652)
at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:43)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1054)
at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:296)
at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1039)
at org.codehaus.mojo.hibernate3.configuration.AbstractComponentConfiguration.getConfiguration(AbstractComponentConfiguration.java:38)
at org.codehaus.mojo.hibernate3.HibernateExporterMojo.configureExporter(HibernateExporterMojo.java:186)
at org.codehaus.mojo.hibernate3.exporter.Hbm2JavaGeneratorMojo.configureExporter(Hbm2JavaGeneratorMojo.java:69)
Kindly show me the mistakes I have made.. I want to use one to many relation AffiliateDO->AddressDO
It looks like your mapping of the parent class is referring to AddressDO, but the subsequent child mapping is referring to Address (No "DO")... If I had to guess, you should change the second mapping to AddressDO (or visa versa). In any event, looks like a typo to me.
Considering Do as a typo error in Addrees xml, The Address mapping seems incorrect, there must address_id must be many-to-one currently it is generated new one.

Hibernate parent/child relationship. Why is object saved twice?

I am looking into Hibernate's parent/child relationships.
I have 3 entities Employee Customers and Orders.
Their relationship is
Employee 1 <-> N Orders
Customer 1 <-> N Orders
I want to be able to save/update/delete Customer objects and Employees and Orders but I want to use some interface so that the calling code does not deal with any Hibernate or JPA stuff.
E.g. I tried something like the following:
class Utils{
public static void saveObject(Object o){
logger.debug(o.toString());
Session session = getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
session.save(o);
tx.commit();
session.close();
}
}
and in the calling code I do:
Employee employee = new Employee();
//set data on employee
Customer customer = new Customer();
//set data on customer
Order order = new Order();
//set data on order
employee.addOrder(order);//this adds order to its list, order gets a reference of employee as parent
customer.addOrder(order);//this adds order to its list, order gets a reference of customer as parent
Utils.saveObject(customer);
Utils.saveObject(employee);
Now I noticed that with this code, 2 records of employee are created instead of 1.
If I only do:
Utils.saveObject(customer);
Only 1 (correctly) record is created.
Why does this happen?
Does this happens because the same Order object is saved by both Customer and Employee? And the cascade="all" makes this side-effect?
Now if I do not use the DBUtils method and do directly:
Session session = DBUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
session.save(employee);
session.save(customer);
tx.commit();
session.close();
Again, it works as expected. I.e. only 1 employee record is created.
What am I doing something wrong here?
UPDATE:
Hibernate mappings:
<hibernate-mapping>
<class name="database.entities.Associate" table="EMPLOYEE">
<id name="assosiateId" type="java.lang.Long">
<column name="EMPLOYEEID" />
<generator class="identity" />
</id>
<property name="firstName" type="java.lang.String" not-null="true">
<column name="FIRSTNAME" />
</property>
<property name="lastName" type="java.lang.String" not-null="true">
<column name="LASTNAME" />
</property>
<property name="userName" type="java.lang.String" not-null="true">
<column name="USERNAME" />
</property>
<property name="password" type="java.lang.String" not-null="true">
<column name="PASSWORD" />
</property>
<set name="orders" table="ORDERS" inverse="true" cascade="all" lazy="true">
<key>
<column name="EMPLOYEEID" />
</key>
<one-to-many class="database.entities.Order" />
</set>
</class>
</hibernate-mapping>
<hibernate-mapping>
<class name="database.entities.Customer" table="CUSTOMER">
<id name="customerId" type="java.lang.Long">
<column name="CUSTOMERID" />
<generator class="identity" />
</id>
<property name="customerName" type="java.lang.String">
<column name="CUSTOMERNAME" />
</property>
<set name="orders" table="ORDERS" inverse="true" cascade="all" lazy="true">
<key>
<column name="CUSTOMERID" />
</key>
<one-to-many class="database.entities.Order" />
</set>
</class>
</hibernate-mapping>
<hibernate-mapping>
<class name="database.entities.Order" table="ORDERS">
<id name="orderId" type="java.lang.Long">
<column name="ORDERID" />
<generator class="identity" />
</id>
<property name="orderDate" type="java.util.Date">
<column name="ORDERDATE" />
</property>
<property name="quantity" type="java.lang.Integer">
<column name="QUANTITY" />
</property>
<property name="quantityMargin" type="java.lang.Long">
<column name="QUANTITYMARGIN" />
</property>
<property name="port" type="java.lang.String">
<column name="PORT" />
</property>
<property name="orderState" type="java.lang.String">
<column name="ORDERSTATE" />
</property>
<many-to-one name="customer" class="database.entities.Customer" cascade="all" fetch="join">
<column name="CUSTOMERID" />
</many-to-one>
<many-to-one name="associate" column="EMPLOYEEID" class="database.entities.Employee" cascade="all" fetch="join">
</many-to-one>
</class>
</hibernate-mapping>
UDATE 2:
class Employee{
//Various members
Set<Order> orders = new HashSet<Order>();
public void addOrder(Order order){
order.setEmployee(this);
orders.add(order);
}
}
Also:
class Customer{
//Various members
Set<Order> orders = new HashSet<Order>();
public void addOrder(Order order){
order.setCustomer(this);
orders.add(order);
}
}
It seems to me that in the DBUtils code, you are wrapping both saves in an outer transaction, whereas in the Utils code, you have them in two completely separate transactions without an outer one.
Depending on your cascading, Hibernate has to figure out which objects need to be saved. When you run the Utils code, with two separate transactions, it will save the Order first. Since you're cascading all, this means it will save the Order first, then the Customer. However, you've created the SAME Order for both the Customer and Employee. Therefore, the Employee also gets saved in the first transaction (due to cascading). The second transaction, since it is separate, will not be aware of this and save another Employee.
On the other hand, if you wrap them in an outer transaction, Hibernate can figure out the identities of all the objects and save them properly.
try saving only Order instead of saving Employee and Customer separately. With your existing cascade=all setting both parent object will get saved without creating any duplicates.

Migrating Hibernate 3.2.5 to 3.6

Currently We are facing a lot of problem in migrating our Application from Hibernate 3.2.5 to 3.6.1.
The first error that We are facing is :
SEVERE: Invalid column name 'btn_name'. Although btn_name is mapped no where. The actual mapping is btnName.
Here is my mapping file
<hibernate-mapping>
<class abstract="true" name="com.sampleproject.client.beansdm.metadata.Component"
table="component_master">
<id column="metadata_id" name="id" type="long">
<generator class="native" />
</id>
<property column="metadata_type" name="type" type="string" />
<property name="createdDateTime" column="created_date" type="date"
update="false"></property>
<property name="version" type="string" column="version_id"></property>
<property name="currentDate" type="date" column="curr_date"></property>
<property name="currentIP" type="string" column="current_ip"></property>
<many-to-one name="currentUser"
class="com.sampleproject.client.beansdm.domain.common.User" cascade="refresh"
column="current_user_id"></many-to-one>
<property name="latestDate" type="date" column="latest_date"></property>
<property name="latestIP" type="string" column="latest_ip"></property>
<many-to-one name="latestUser"
class="com.sampleproject.client.beansdm.domain.common.User" cascade="refresh"
column="latest_user"></many-to-one>
<property name="recordStatus" type="boolean" column="record_status"></property>
<property name="portal" type="string" column="portal"></property>
<many-to-one cascade="refresh,save-update,delete"
class="com.sampleproject.client.beansdm.metadata.Component" column="md_id"
name="metadata" not-null="false" />
<joined-subclass
name="com.sampleproject.client.beansdm.metadata.uicontrols.UIControl"
table="ui_control_master">
<key column="ui_control_id" />
<property column="display_name" name="displayText" />
<property column="help_text" name="helpText" />
<property column="info_text" name="informativeText" />
<property column="rows" name="rows" type="integer" />
<property column="cols" name="cols" type="integer" />
<property column="btnName" name="btnName" type="string" />
<property name="version" type="string" column="version_id"></property>
<property name="currentDate" type="date" column="curr_date"></property>
<property name="currentIP" type="string" column="current_ip"></property>
<many-to-one name="currentUser"
class="com.sampleproject.client.beansdm.domain.common.User" cascade="refresh"
column="current_user_id"></many-to-one>
<property name="latestDate" type="date" column="latest_date"></property>
<property name="latestIP" type="string" column="latest_ip"></property>
<many-to-one name="latestUser"
class="com.sampleproject.client.beansdm.domain.common.User" cascade="refresh"
column="latest_user"></many-to-one>
<property name="recordStatus" type="boolean" column="record_status"></property>
<property name="portal" type="string" column="portal"></property>
<property name="readOnly" type="boolean" column="read_only"/>
<joined-subclass
name="com.sampleproject.client.beansdm.metadata.uicontrols.InputControl"
table="input_control_master" lazy="true">
<key column="input_control_id" />
<property column="default_value" name="defaultValue"
not-null="false" />
<property column="is_fk" name="fk" />
<property column="validatable" name="validatable" />
<property column="violatable" name="violatable" />
<property name="isRequired" column="is_required"></property>
<property name="ruleType"
type="com.sampleproject.facadeimplementation.util1.UserEnumRuleType"
column="rule_type"></property>
<property name="fileType" column="file_type"></property>
<property name="maxFileSize" column="max_file_size" type="integer"></property>
<property name="precision" column="input_precision" type="integer"></property>
<property name="maxLength" column="maxlength" type="integer"></property>
<property name="minLength" column="minlength" type="integer"></property>
<property name="dateFormatType" column="dateformat"
type="com.sampleproject.facadeimplementation.util1.UserEnumDateFormatType"></property>
<property name="specialCharAllow" column="isspecialcharallow"></property>
<property name="specialChars" column="specialchars" type="string"></property>
<property name="dateType"
type="com.sampleproject.facadeimplementation.util1.UserEnumDateType"
column="date_type"></property>
<property name="minDate" column="mindate" type="string"></property>
<property name="maxDate" column="maxdate" type="string"></property>
<property name="inspection" column="inspection" type="boolean"></property>
<property name="values" column="default_values" type="string"></property>
<property name="targetNames" column="target_names" type="string"></property>
<!--
<many-to-one cascade="save-update, delete"
class="com.sampleproject.client.beansdm.metadata.Column"
column="target_column_id" name="targetColumn" />
-->
<property name="targetColumn" column="target_column" type="string"></property>
<property name="templateName" column="template_name" type="string"></property>
<!--
<bag name="targetColumnNames" cascade="save-update"
table="input_possible_columns_map"> <key
column="input_control_id"></key> <element column="column_name"
not-null="true" type="string" /> </bag>
-->
<!--<bag name="possibleValues" cascade="save-update" table="input_possible_values_map">
<key column="input_control_id" />
<many-to-many
class="com.sampleproject.client.beansdm.metadata.uicontrols.PossibleValue"
column="value" />
</bag>
--><property name="seperator" column="seperator" type="string" />
<many-to-one name="refTable" cascade="refresh"
class="com.sampleproject.client.beansdm.metadata.Table" column="ref_table_id" lazy="false">
</many-to-one>
<many-to-one name="targetTable" cascade="refresh"
class="com.sampleproject.client.beansdm.metadata.Table" column="target_table_id" />
<property name="version" type="string" column="version_id"></property>
<property name="currentDate" type="date" column="curr_date"></property>
<property name="currentIP" type="string" column="current_ip"></property>
<many-to-one name="currentUser"
class="com.sampleproject.client.beansdm.domain.common.User" cascade="refresh"
column="current_user_id"></many-to-one>
<property name="latestDate" type="date" column="latest_date"></property>
<property name="latestIP" type="string" column="latest_ip"></property>
<many-to-one name="latestUser"
class="com.sampleproject.client.beansdm.domain.common.User" cascade="refresh"
column="latest_user"></many-to-one>
<property name="recordStatus" type="boolean" column="record_status"></property>
<property name="portal" type="string" column="portal"></property>
<many-to-one name="linkedColumn" cascade="refresh"
class="com.sampleproject.client.beansdm.metadata.Column" column="linked_column_name">
</many-to-one>
<many-to-one name="linkedMasterColumn" cascade="refresh"
class="com.sampleproject.client.beansdm.metadata.Column" column="linked_master_column">
</many-to-one>
<many-to-one name="linkedTable" cascade="refresh"
class="com.sampleproject.client.beansdm.metadata.Table" column="linked_master_id">
</many-to-one>
</joined-subclass>
</joined-subclass>
</class>
</hibernate-mapping>
Focus on com.sampleproject.client.beansdm.metadata.uicontrols.InputControl joined-subclass mapping there is a field named btnName. Its working fine with 3.2.5 version but when i changed it to newer hibernate version it stops responding.
Is there any possible jar conflicts ?
Please help.
Thanking You,
Regards,
The Hibernate Version Comparison guide states when moving from 3.5 to 3.6 that:
However, for users still using hbm.xml
you should be aware that we chose to
use the
org.hibernate.cfg.EJB3NamingStrategy
used in AnnotationConfigration instead
of the older
org.hibernate.cfg.DefaultNamingStrategy
historically used on Configuration.
This may cause naming mismatches; one
known place where this is an issue is
if you rely on the naming strategy to
default the name of a association
(many-to-many and collections of
elements) table. If you find yourself
in this situation, you can tell
Hibernate to use the the legacy
org.hibernate.cfg.DefaultNamingStrategy
by calling
Configuration#setNamingStrategy and
passing it
org.hibernate.cfg.DefaultNamingStrategy#INSTANCE
The NamingStrategy interface defines several methods like String foreignKeyColumnName(String propertyName, String propertyEntityName, String propertyTableName, String referencedColumnName)used to determine the names of columns and associations which are implemented by the EJB3NamingStrategy. I suggest you look at the implementation of these methods in the EJB3NamingStrategy class and see how it is transforming property names to column names.
It looks like hibernate is now adding the underscores to what it expects the column name to be in the DB via one these transformations, and is upset when it can't find the resultant column name 'btn_name' in your database.

Categories

Resources