-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 5 posts ] 
Author Message
 Post subject: Detaching and reattaching - Help!
PostPosted: Fri Jun 10, 2005 1:20 pm 
Newbie

Joined: Mon Oct 18, 2004 7:59 am
Posts: 10
Location: Netherlands
It seems I cannot get reattachment of detached objects to work anymore, I'm going crazy. Please tell me what I'm missing here.

Code:
public void testDetachReattach3()
{
   log.debug("Begin DetachReattach3");
   Session session = null, session2 = null;
   Simpel simpel = null;

   try {
      session = HibernateUtil.getSessionFactory().openSession();
      simpel = (Simpel) session.createQuery("from Simpel").list().get(0);   
   } catch (HibernateException e) {
      e.printStackTrace();
   } finally {
      session.disconnect();
      session.close();
   }
   // Now all is detached, re-attach!   
   try {
      session2 = HibernateUtil.getSessionFactory().openSession();
      session2.update(simpel);
         
   } catch (HibernateException e) {
      e.printStackTrace();
   } finally {
      session2.disconnect();
      session2.close();
   }
   log.debug("eind DetachReattach3");
}


This should just work, right? Nope, I get an exception with message 'This class has no identifier property'.

Below I attach the entire log, just for completion. The line 'session2.update(simpel)' in the code above, is line 173.

19:00:41,530 DEBUG main LongTx:157 - Begin DetachReattach3
19:00:41,560 INFO main Environment:464 - Hibernate 3.0.5
19:00:41,570 INFO main Environment:477 - hibernate.properties not found
19:00:41,570 INFO main Environment:510 - using CGLIB reflection optimizer
19:00:41,620 INFO main Environment:540 - using JDK 1.4 java.sql.Timestamp handling
19:00:41,730 INFO main Configuration:1110 - configuring from resource: /hibernate.cfg.xml
19:00:41,730 INFO main Configuration:1081 - Configuration resource: /hibernate.cfg.xml
19:00:41,841 INFO main Configuration:444 - Mapping resource: nl/blablah/hibernateworkshop/Simpel.hbm.xml
19:00:41,961 INFO main HbmBinder:260 - Mapping class: nl.blablah.hibernateworkshop.Simpel -> SIMPEL
19:00:41,971 INFO main Configuration:1222 - Configured SessionFactory: null
19:00:41,971 INFO main Configuration:875 - processing extends queue
19:00:41,971 INFO main Configuration:879 - processing collection mappings
19:00:41,981 INFO main Configuration:888 - processing association property references
19:00:41,981 INFO main Configuration:917 - processing foreign key constraints
19:00:42,041 INFO main DriverManagerConnectionProvider:41 - Using Hibernate built-in connection pool (not for production use!)
19:00:42,041 INFO main DriverManagerConnectionProvider:42 - Hibernate connection pool size: 20
19:00:42,051 INFO main DriverManagerConnectionProvider:45 - autocommit mode: false
19:00:42,151 INFO main DriverManagerConnectionProvider:80 - using driver: oracle.jdbc.driver.OracleDriver at URL: jdbc:oracle:thin:@localhost:1521:TESTDB
19:00:42,151 INFO main DriverManagerConnectionProvider:86 - connection properties: {user=scott, password=****}
19:00:42,522 INFO main SettingsFactory:77 - RDBMS: Oracle, version: Personal Oracle9i Release 9.2.0.1.0 - Production
With the Partitioning, OLAP and Oracle Data Mining options
JServer Release 9.2.0.1.0 - Production
19:00:42,532 INFO main SettingsFactory:78 - JDBC driver: Oracle JDBC driver, version: 9.2.0.1.0
19:00:42,552 INFO main Dialect:92 - Using dialect: org.hibernate.dialect.Oracle9Dialect
19:00:42,562 INFO main TransactionFactoryFactory:31 - Using default transaction strategy (direct JDBC transactions)
19:00:42,562 INFO main TransactionManagerLookupFactory:33 - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
19:00:42,562 INFO main SettingsFactory:125 - Automatic flush during beforeCompletion(): disabled
19:00:42,562 INFO main SettingsFactory:129 - Automatic session close at end of transaction: disabled
19:00:42,562 INFO main SettingsFactory:136 - JDBC batch size: 15
19:00:42,572 INFO main SettingsFactory:139 - JDBC batch updates for versioned data: disabled
19:00:42,572 INFO main SettingsFactory:144 - Scrollable result sets: enabled
19:00:42,572 INFO main SettingsFactory:152 - JDBC3 getGeneratedKeys(): disabled
19:00:42,572 INFO main SettingsFactory:160 - Connection release mode: null
19:00:42,572 INFO main SettingsFactory:187 - Default batch fetch size: 1
19:00:42,572 INFO main SettingsFactory:191 - Generate SQL with comments: disabled
19:00:42,572 INFO main SettingsFactory:195 - Order SQL updates by primary key: disabled
19:00:42,572 INFO main SettingsFactory:334 - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
19:00:42,582 INFO main ASTQueryTranslatorFactory:21 - Using ASTQueryTranslatorFactory
19:00:42,582 INFO main SettingsFactory:203 - Query language substitutions: {}
19:00:42,582 INFO main SettingsFactory:209 - Second-level cache: enabled
19:00:42,582 INFO main SettingsFactory:213 - Query cache: disabled
19:00:42,582 INFO main SettingsFactory:321 - Cache provider: org.hibernate.cache.EhCacheProvider
19:00:42,582 INFO main SettingsFactory:228 - Optimize cache for minimal puts: disabled
19:00:42,582 INFO main SettingsFactory:237 - Structured second-level cache entries: disabled
19:00:42,592 INFO main SettingsFactory:261 - Statistics: disabled
19:00:42,592 INFO main SettingsFactory:265 - Deleted entity synthetic identifier rollback: disabled
19:00:42,602 INFO main SettingsFactory:279 - Default entity-mode: pojo
19:00:42,762 INFO main SessionFactoryImpl:152 - building session factory
19:00:42,762 DEBUG main SessionFactoryImpl:161 - Session factory constructed with filter configurations : {}
19:00:42,762 DEBUG main SessionFactoryImpl:164 - instantiating session factory with properties: {hibernate.connection.password=pizze, java.runtime.name=Java(TM) 2 Runtime Environment, Standard Edition, sun.boot.library.path=C:\j2sdk1.4.2_08\jre\bin, java.vm.version=1.4.2_08-b03, hibernate.connection.username=scott, java.vm.vendor=Sun Microsystems Inc., java.vendor.url=http://java.sun.com/, hibernate.cache.use_query_cache=false, path.separator=;, java.vm.name=Java HotSpot(TM) Client VM, file.encoding.pkg=sun.io, user.country=NL, sun.os.patch.level=Service Pack 2, java.vm.specification.name=Java Virtual Machine Specification, user.dir=D:\jdev\eclipse-31\BOM, java.runtime.version=1.4.2_08-b03, cglib.use_reflection_optimizer=false, java.awt.graphicsenv=sun.awt.Win32GraphicsEnvironment, java.endorsed.dirs=C:\j2sdk1.4.2_08\jre\lib\endorsed, os.arch=x86, java.io.tmpdir=C:\DOCUME~1\marcf\LOCALS~1\Temp\, line.separator=
, java.vm.specification.vendor=Sun Microsystems Inc., user.variant=, hibernate.cache.use_second_level_cache=true, os.name=Windows XP, sun.java2d.fontpath=, java.library.path=C:\j2sdk1.4.2_08\bin;.;C:\WINDOWS\system32;C:\WINDOWS;d:\IBMDebug\bin;D:\oracle\ora92\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\Common Files\Adaptec Shared\System;c:\jdk1.5.0\bin;D:\jbin\Rational\common;C:\Program Files\Common Files\Compuware, java.specification.name=Java Platform API Specification, java.class.version=48.0, cache.use_second_level_cache=true, java.util.prefs.PreferencesFactory=java.util.prefs.WindowsPreferencesFactory, os.version=5.1, connection.password=pizze, user.home=C:\Documents and Settings\marcf, user.timezone=Europe/Berlin, connection.username=scott, java.awt.printerjob=sun.awt.windows.WPrinterJob, file.encoding=Cp1252, java.specification.version=1.4, hibernate.connection.driver_class=oracle.jdbc.driver.OracleDriver, user.name=marcf, java.class.path=D:\jdev\eclipse-31\BOM\bin;D:\jdev\eclipse-31\BOM\lib\commons-lang-2.0.jar;D:\jdev\eclipse-31\BOM\lib\hibernate3.jar;D:\jbin\eclipse-3.1\plugins\org.junit_3.8.1\junit.jar;D:\jdev\eclipse-31\BOM\lib\commons-logging-1.0.4.jar;D:\jdev\eclipse-31\BOM\lib\commons-collections-2.1.1.jar;D:\jdev\eclipse-31\BOM\lib\dom4j-1.6.jar;D:\jdev\eclipse-31\BOM\lib\ehcache-1.1.jar;D:\jdev\eclipse-31\BOM\lib\jta.jar;D:\jdev\eclipse-31\BOM\lib\junit-3.8.1.jar;D:\jdev\eclipse-31\BOM\lib\log4j-1.2.9.jar;D:\jdev\eclipse-31\BOM\lib\ojdbc14.jar;D:\jdev\eclipse-31\BOM\lib\cglib-2.1.jar;D:\jdev\eclipse-31\BOM\lib\antlr-2.7.5H3.jar;D:\jdev\eclipse-31\BOM\lib\asm.jar;D:\jdev\eclipse-31\BOM\lib\asm-attrs.jar;D:\jdev\eclipse-31\BOM\lib\concurrent-1.3.3.jar;/d:/jbin/eclipse-3.1/plugins/org.eclipse.jdt.junit_3.1.0/junitsupport.jar;/d:/jbin/eclipse-3.1/plugins/org.eclipse.jdt.junit.runtime_3.1.0/junitruntime.jar, java.vm.specification.version=1.0, java.home=C:\j2sdk1.4.2_08\jre, sun.arch.data.model=32, hibernate.connection.url=jdbc:oracle:thin:@localhost:1521:TESTDB, hibernate.dialect=org.hibernate.dialect.Oracle9Dialect, user.language=nl, java.specification.vendor=Sun Microsystems Inc., awt.toolkit=sun.awt.windows.WToolkit, hibernate.cglib.use_reflection_optimizer=false, java.vm.info=mixed mode, java.version=1.4.2_08, java.ext.dirs=C:\j2sdk1.4.2_08\jre\lib\ext, cache.use_query_cache=false, sun.boot.class.path=C:\j2sdk1.4.2_08\jre\lib\rt.jar;C:\j2sdk1.4.2_08\jre\lib\i18n.jar;C:\j2sdk1.4.2_08\jre\lib\sunrsasign.jar;C:\j2sdk1.4.2_08\jre\lib\jsse.jar;C:\j2sdk1.4.2_08\jre\lib\jce.jar;C:\j2sdk1.4.2_08\jre\lib\charsets.jar;C:\j2sdk1.4.2_08\jre\classes, java.vendor=Sun Microsystems Inc., connection.driver_class=oracle.jdbc.driver.OracleDriver, file.separator=\, java.vendor.url.bug=http://java.sun.com/cgi-bin/bugreport.cgi, sun.io.unicode.encoding=UnicodeLittle, sun.cpu.endian=little, connection.url=jdbc:oracle:thin:@localhost:1521:TESTDB, dialect=org.hibernate.dialect.Oracle9Dialect, sun.cpu.isalist=pentium i486 i386}
19:00:42,772 WARN main Configurator:126 - No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: jar:file:/D:/jdev/eclipse-31/BOM/lib/ehcache-1.1.jar!/ehcache-failsafe.xml
19:00:43,102 DEBUG main SessionFactoryObjectFactory:39 - initializing class SessionFactoryObjectFactory
19:00:43,102 DEBUG main SessionFactoryObjectFactory:76 - registered: 402881e50467323c010467323ede0000 (unnamed)
19:00:43,102 INFO main SessionFactoryObjectFactory:82 - Not binding factory to JNDI, no JNDI name configured
19:00:43,112 DEBUG main SessionFactoryImpl:262 - instantiated session factory
19:00:43,112 INFO main SessionFactoryImpl:379 - Checking 0 named queries
19:00:43,142 DEBUG main SessionImpl:250 - opened session at timestamp: 4581059965386752
19:00:43,162 DEBUG main SessionImpl:829 - find: from Simpel
19:00:43,353 DEBUG main SQL:324 - select simpel0_.id as id, simpel0_.version as version0_, simpel0_.name as name0_, simpel0_.value as value0_ from SIMPEL simpel0_
19:00:43,433 DEBUG main SessionImpl:357 - disconnecting session
19:00:43,433 DEBUG main SessionImpl:403 - after transaction completion
19:00:43,433 DEBUG main SessionImpl:269 - closing session
19:00:43,433 DEBUG main SessionImpl:250 - opened session at timestamp: 4581059966701568
org.hibernate.HibernateException: The class has no identifier property: nl.blablah.hibernateworkshop.Simpel
at org.hibernate.tuple.AbstractTuplizer.getIdentifier(AbstractTuplizer.java:101)
at org.hibernate.persister.entity.BasicEntityPersister.getIdentifier(BasicEntityPersister.java:2944)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.getUpdateId(DefaultSaveOrUpdateEventListener.java:221)
at org.hibernate.event.def.DefaultUpdateEventListener.getUpdateId(DefaultUpdateEventListener.java:46)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsDetached(DefaultSaveOrUpdateEventListener.java:212)
at org.hibernate.event.def.DefaultUpdateEventListener.performSaveOrUpdate(DefaultUpdateEventListener.java:33)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:69)
at org.hibernate.impl.SessionImpl.update(SessionImpl.java:499)
at org.hibernate.impl.SessionImpl.update(SessionImpl.java:490)
at nl.blablah.hibernateworkshop.LongTx.testDetachReattach3(LongTx.java:173)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:324)
at junit.framework.TestCase.runTest(TestCase.java:154)
at junit.framework.TestCase.runBare(TestCase.java:127)
at junit.framework.TestResult$1.protect(TestResult.java:106)
at junit.framework.TestResult.runProtected(TestResult.java:124)
at junit.framework.TestResult.run(TestResult.java:109)
at junit.framework.TestCase.run(TestCase.java:118)
at junit.framework.TestSuite.runTest(TestSuite.java:208)
at junit.framework.TestSuite.run(TestSuite.java:203)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:474)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:342)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:194)
19:00:43,443 DEBUG main SessionImpl:357 - disconnecting session
19:00:43,443 DEBUG main SessionImpl:403 - after transaction completion
19:00:43,443 DEBUG main SessionImpl:269 - closing session
19:00:43,443 DEBUG main LongTx:181 - eind DetachReattach3


Top
 Profile  
 
 Post subject: Re: Detaching and reattaching - Help!
PostPosted: Sat Jun 11, 2005 10:23 am 
Newbie

Joined: Mon Oct 18, 2004 7:59 am
Posts: 10
Location: Netherlands
Oh crap i've found it - I forgot the 'name=' attribute on id in my mapping files. It took a while before I found that - session.getId() still gave me the Id just like I expected.

So, I guess you guys knew this all along and just thought, hey let him find out for himself! Well, rightly so.


Top
 Profile  
 
 Post subject:
PostPosted: Sat Jun 11, 2005 11:24 am 
Senior
Senior

Joined: Thu May 12, 2005 11:40 pm
Posts: 125
Location: Canada
Detach an individual instance by calling session.flush() followed by session.evict(instance). Attach it again by calling session.lock(instance, LockMode.NONE).


Top
 Profile  
 
 Post subject: Attahching object and object version
PostPosted: Tue Jul 19, 2005 6:03 am 
Newbie

Joined: Mon Mar 21, 2005 12:27 am
Posts: 17
I have problem with attaching object as well. But the problem is that the object is version is updated by Hibernate multiple times. I take the example from the Hibernate User Doc.

Code:
session1 = ...
// in the first session
Cat cat = (Cat) firstSession.load(Cat.class, catId);
cat.setAge(5); // just set fields
session1.close();

// in session2
session2 = ...
session2.update(cat);
// some query happened.
Cat potentialMate = (Cat)session2.load(Cat.class, cat2Id);
cat.setMate(potentialMate); // transitive persistency for 'mate'
session2.close();

// later, in session3
session3 = ...
session3.beginTransaction();
session3.update(cat);
session3.commit(); // fail because the cat's on object version error


In particular, it seems if I have done a query in session2, I would get the version error in session3. The object version was increased in session2 unexpectedly. But clearly I must be able to set the reference in the earlier session beause I need to continue collecting data from the user.

Any idea what's wrng?

Thanks
[/code]

_________________
Hacking Bear


Top
 Profile  
 
 Post subject: Attach object, session and connection pool
PostPosted: Wed Jul 20, 2005 4:50 am 
Newbie

Joined: Mon Mar 21, 2005 12:27 am
Posts: 17
Hi,

I still have the problem with attaching objects across multiple sessions. Please help.

1. A versioned object X is created/commited in session1.
2. session1 is closed and session2 is opened.
3. The version object is attached to session2 via update()
4. A field of that object is changed in session2.
5. A query or load occurs in session2, causing a flush to happen and increment the version number
6. session2 is closed and session3 opened
7. Attach object to session3 via update()
8. Start and commit a transaction. It fails due to StaleObjectException.

Note: I cannot use lock() to attach the object as it may have been modified in previous session. I also tried evict() and flush() before closing a session; no use.

Another weirdness, if I use the default Hibernate connection pool instead of c3p0 pool, the problem would not occur but the version has been updated mutiple times. But further investigation leads me to belive the default pool seems to reuse the connection without forgetting the previously issued changes.

I believe the bug is that in session2, the version number is not "rolled back" even though all data updates has been effectively rolled back, because there is no transaction commit.

What would be the right fix/work around for this strange issue.

Thanks.

Example test case for the problem:

Code:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
   "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="test.hib.Cat" table="TB_Cat" lazy="false">
        <id name="id" type="string" unsaved-value="null">
            <generator class="uuid.hex"/>
        </id>
        <version name="version" type="long" column="VERSION_"
            unsaved-value="negative"/>
        <property name="name" not-null="true"/>
        <property name="age"/>
    </class>
</hibernate-mapping>

package test.hib;

import junit.framework.TestCase;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class HibernateTest extends TestCase
{

    public static void main(String[] args) {
        junit.textui.TestRunner.run(HibernateTest.class);
    }

    private static SessionFactory s_factory;

    private void configure() throws HibernateException {
        Configuration config = new Configuration();
        config.addClass(Cat.class);
        config.configure();
        s_factory = config.buildSessionFactory();
        SchemaExport export = new SchemaExport(config);
        export.create(true, true);
    }

    private Session openSession() {
        try {
            if (s_factory == null) {
                configure();
            }
            return s_factory.openSession();
        } catch (HibernateException e) {
            throw new RuntimeException("Can not open hibernate session.", e);
        }
    }

    public void testDetach() {

        // create a cat
        Cat cat = new Cat();
        cat.setName("abc");
        cat.setAge(10);
        assertEquals(-1, cat.getVersion());
        Session sess1 = openSession();
        Transaction tx = sess1.beginTransaction();
        sess1.save(cat);
        tx.commit();
        sess1.close();
        assertNotNull(cat.getId());

        // load cat
        Session sess2 = openSession();
        cat = (Cat)sess2.load(Cat.class, cat.getId());
        sess2.close();// cat state is detached
        assertEquals(0, cat.getVersion());

        // modify cat
        cat.setAge(12);

        // attach to sess3
        Session sess3 = openSession();
        sess3.update(cat);
        Criteria query = sess3.createCriteria(Cat.class);
        query.list();
        assertEquals(1, cat.getVersion());// cat version is increased
        sess3.close();

        // commit
        Session sess4 = openSession();
        sess4.update(cat);
        tx = sess4.beginTransaction();
        tx.commit();// fail,if use c3p0 connectin pool
        sess4.close();
        assertEquals(2, cat.getVersion());// cat version is increased
    }
}


Exception stack at commit

Code:
Could not synchronize database state with session
org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [TestSingleRef:66]
   at org.hibernate.persister.entity.BasicEntityPersister.check(BasicEntityPersister.java:1431)
   at org.hibernate.persister.entity.BasicEntityPersister.update(BasicEntityPersister.java:1976)
   at org.hibernate.persister.entity.BasicEntityPersister.updateOrInsert(BasicEntityPersister.java:1899)
   at org.hibernate.persister.entity.BasicEntityPersister.update(BasicEntityPersister.java:2139)
   at org.hibernate.action.EntityUpdateAction.execute(EntityUpdateAction.java:75)
   at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:239)
   at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:223)
   at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:137)
   at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:274)
   at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
   at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:726)
   at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:320)
   at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:86)

_________________
Hacking Bear


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 5 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.