-->
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.  [ 1 post ] 
Author Message
 Post subject: J-unit test for Optomistic Locking Fails on migration to HB3
PostPosted: Tue May 10, 2005 4:35 pm 
Newbie

Joined: Sun May 08, 2005 12:08 am
Posts: 1
Hello,

I have just migrated to Hibernate 3 and one of my J-unit tests that worked under
Hibernate 2 is failing. I am using Read Committed isolation
Code:
<property name="hibernate.connection.isolation">2</property>
and have
implemented versioning. It is my understanding that if I try to
update the same record twice. the second commit should know that it is
operating on stale data and throw a StaleObjectStateException. This was
he case under HB2 but now the Second Update is winning which is
unacceptable. The migration guide doesn’t seem to suggest that any
changes in this area have occurred. I am using the thread local session
factory from Hibernate in Action. Any suggestions would be greatly
appreciated.

Except for this issue the migration to HB3 has been painless. Thanks for a great product.

Thanks again, Robert


Hibernate version:

hibernate-3.0.2

Mapping documents:

Code:
<?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>
    <class name="com.cosmetto.ski.model.Reservation" table="res">
        <id name="id" column="res_id" type="long" unsaved-value="null">   
            <generator class="hilo"/>
        </id>
        <version name="version" />
        <property name="timestamp" column="timestamp" type="timestamp" not-null="false"  />
        <property name="date" column="date" type="calendar_date" not-null="true"/>
        <property name="note" column="note" type="string" length="50" not-null="false"/>
        <property name="guests" column="guests" type="int"  not-null="false"/>
        <many-to-one name="user" class="com.cosmetto.ski.model.User" cascade="save-update" column="user_id" not-null="false"/>
    </class>
</hibernate-mapping>


Code:
<?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.cosmetto.ski.model">
   
    <class name="com.cosmetto.ski.model.User" table="user">
        <id name="id" column="user_id" type="long" unsaved-value="null">   
            <generator class="hilo"/>
        </id> 
        <version name="version" />
        <property name="email" column="email" type="string" length="60" not-null="false"/>
        <property name="firstName" column="first_name" type="string" length="12" not-null="true"/>
         <property name="lastName" column="last_name" type="string" length="15" not-null="true"/>
         <property name="userName" column="user_name" type="string" length="15" unique="true" index="true" not-null="true"/>
         <property name="password" column="password" type="string" length="15" unique="false" index="faslse" not-null="true"/> 
   
        <component
            name="address"
            class="Address" >
            <property name="label" column="label" type="string" length="50" not-null="false"/>
            <property name="street" column="street" type="string" length="50" not-null="false"/>
            <property name="city" column="city" type="string" length="50" not-null="false"/>
            <property name="state" column="state" type="string" length="2" not-null="false"/>
            <property name="country" column="country" type="string" length="3" not-null="false"/>
            <property name="zip" column="zip" type="string" length="12" not-null="false"/>
        </component>
       
        <component
            name="phone1"
            class="PhoneNumber" >
            <property name="areaCode" column="pn1_area_code" type="string" length="4" not-null="false" />
            <property name="number" column="pn1_number" type="string" length="15" not-null="false"/>
            <property name="label" column="pn1_label" type="string" length="20" not-null="false"/>
        </component>
       
        <component
            name="phone2"
            class="PhoneNumber">
            <property name="areaCode" column="pn2_area_code" type="string" length="4" not-null="false"/>
            <property name="number" column="pn2_number" type="string" length="15" not-null="false"/>
            <property name="label" column="pn2_label" type="string" length="20" not-null="false"/>
        </component>
       
        <component
            name="phone3"
            class="PhoneNumber">
            <property name="areaCode" column="pn3_area_code" type="string" length="4" not-null="false"/>
            <property name="number" column="pn3_number" type="string" length="15" not-null="false"/>
            <property name="label" column="pn3_label" type="string" length="20" not-null="false"/>
        </component>
       
         <set 
            cascade="all"
            name="reservations"     
            lazy="true"
            inverse="true">
            <key column="user_id"/>
            <one-to-many class="com.cosmetto.ski.model.Reservation" />
        </set>
       
    </class>
</hibernate-mapping>

Code between sessionFactory.openSession() and session.close():

Code:
ses1 = HibernateUtil.getSessionFactory().openSession();
            Transaction tx1 = ses1.beginTransaction();
            ses2 =  HibernateUtil.getSessionFactory().openSession();
            Transaction tx2 = ses2.beginTransaction();
           
            log.debug("ses1 " + ses1 + " " + ses1.hashCode());
            log.debug("ses2 " + ses2 + " " + ses2.hashCode());
           
            Reservation res1 = (Reservation) ses1.load(Reservation.class,resId);
            Reservation res2 = (Reservation) ses2.load(Reservation.class, resId);
           
            int guest = new Long(System.nanoTime()).intValue();
           
            res1.setGuests(guest);
            ses1.saveOrUpdate(res1);
            tx1.commit();
           
            res2.setGuests(guest + 1);
            ses2.saveOrUpdate(res2);
            tx2.commit();
           
            fail("Should Raise a net.sf.hibernate.StaleObjectStateException");
           
            // }catch(net.sf.hibernate.StaleObjectStateException e){
        }catch(org.hibernate.StaleObjectStateException e){
            assertNotNull(e);
           
        }catch(Exception e ){
            fail("Should ONLY  Raise a net.sf.hibernate.StaleObjectStateException");
           
        }finally{
            try{
                ses1.close();
                ses2.close();
               
            }catch(Exception e){
                log.error(e);
            }

Full stack trace of any exception that occurs:
N/A
Name and version of the database you are using:
Mysql 4.0.17-nt
The generated SQL (show_sql=true):
itestIsolationAndVersioning
TestCaseWithData.initDAta()
13:21:13,555 DEBUG HibernateUtil:164 - Starting new database transaction in this thread.
13:21:13,570 DEBUG HibernateUtil:123 - Opening new Session for this thread.
13:21:13,758 DEBUG HibernateUtil:182 - Committing database transaction of this thread.
Hibernate: insert into SW_user (version, email, first_name, last_name, user_name, password, label, street, city, state, country, zip, pn1_area_code, pn1_number, pn1_label, pn2_area_code, pn2_number, pn2_label, pn3_area_code, pn3_number, pn3_label, user_id) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into SW_res (version, timestamp, date, note, guests, user_id, res_id) values (?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into SW_res (version, timestamp, date, note, guests, user_id, res_id) values (?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into SW_user (version, email, first_name, last_name, user_name, password, label, street, city, state, country, zip, pn1_area_code, pn1_number, pn1_label, pn2_area_code, pn2_number, pn2_label, pn3_area_code, pn3_number, pn3_label, user_id) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into SW_res (version, timestamp, date, note, guests, user_id, res_id) values (?, ?, ?, ?, ?, ?, ?)
13:21:13,976 DEBUG HibernateUtil:148 - Closing Session of this thread.
13:21:13,976 DEBUG HibernateUtil:164 - Starting new database transaction in this thread.
13:21:13,976 DEBUG HibernateUtil:123 - Opening new Session for this thread.
Hibernate: select reservatio0_.res_id as res1_, reservatio0_.version as version0_, reservatio0_.timestamp as timestamp0_, reservatio0_.date as date0_, reservatio0_.note as note0_, reservatio0_.guests as guests0_, reservatio0_.user_id as user7_0_ from SW_res reservatio0_ where reservatio0_.date=? order by reservatio0_.timestamp asc
13:21:14,351 DEBUG ReservationDAOTest:166 - List [ note: 2nd reservation guests: 2 date: Thu Jan 01 00:00:00 PST 2004 id: 32769]
13:21:14,351 DEBUG ReservationDAOTest:170 - reservatioin note: 2nd reservation guests: 2 date: Thu Jan 01 00:00:00 PST 2004 id: 32769
13:21:14,351 DEBUG ReservationDAOTest:172 - resid 32769
13:21:14,414 DEBUG ReservationDAOTest:179 - ses1 org.hibernate.impl.SessionImpl(PersistentContext[entitiesByKey={}] ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[]]) 11511434
13:21:14,414 DEBUG ReservationDAOTest:180 - ses2 org.hibernate.impl.SessionImpl(PersistentContext[entitiesByKey={}] ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[]]) 31375837
Hibernate: select reservatio0_.res_id as res1_0_, reservatio0_.version as version0_0_, reservatio0_.timestamp as timestamp0_0_, reservatio0_.date as date0_0_, reservatio0_.note as note0_0_, reservatio0_.guests as guests0_0_, reservatio0_.user_id as user7_0_0_ from SW_res reservatio0_ where reservatio0_.res_id=?
Hibernate: update SW_res set version=?, timestamp=?, date=?, note=?, guests=?, user_id=? where res_id=? and version=?
Hibernate: select reservatio0_.res_id as res1_0_, reservatio0_.version as version0_0_, reservatio0_.timestamp as timestamp0_0_, reservatio0_.date as date0_0_, reservatio0_.note as note0_0_, reservatio0_.guests as guests0_0_, reservatio0_.user_id as user7_0_0_ from SW_res reservatio0_ where reservatio0_.res_id=?
Hibernate: update SW_res set version=?, timestamp=?, date=?, note=?, guests=?, user_id=? where res_id=? and version=?
13:21:14,555 DEBUG HibernateUtil:201 - Tyring to rollback database transaction of this thread.
13:21:14,555 DEBUG HibernateUtil:148 - Closing Session of this thread.
Testsuite: com.cosmetto.ski.dao.ReservationDAOTest
Tests run: 1, Failures: 1, Errors: 0, Time elapsed: 5.422 sec
Debug level Hibernate log excerpt:

13:30:50,789 DEBUG HibernateUtil:164 - Starting new database transaction in this thread.
13:30:50,789 DEBUG HibernateUtil:123 - Opening new Session for this thread.
13:30:50,789 DEBUG SessionImpl:237 - opened session at timestamp: 11157570507
13:30:50,789 DEBUG JDBCTransaction:46 - begin
13:30:50,789 DEBUG AbstractBatcher:422 - opening JDBC connection
13:30:50,789 DEBUG DriverManagerConnectionProvider:93 - total checked-out connections: 0
13:30:50,789 DEBUG DriverManagerConnectionProvider:99 - using pooled JDBC connection, pool size: 0
13:30:50,805 DEBUG JDBCTransaction:50 - current autocommit status: false
13:30:50,820 DEBUG SessionImpl:777 - find: from com.cosmetto.ski.model.Reservation as res where res.date = ? order by res.timestamp asc
13:30:50,820 DEBUG QueryParameters:217 - parameters: [2004-01-01 00:00:00]
13:30:50,820 DEBUG QueryParameters:220 - named parameters: {}
13:30:50,945 DEBUG QueryTranslatorImpl:207 - parse() - HQL: from com.cosmetto.ski.model.Reservation as res where res.date = ? order by res.timestamp asc
13:30:50,961 DEBUG AST:223 - --- HQL AST ---
\-[QUERY] 'query'
+-[SELECT_FROM] 'SELECT_FROM'
| \-[FROM] 'from'
| \-[RANGE] 'RANGE'
| +-[DOT] '.'
| | +-[DOT] '.'
| | | +-[DOT] '.'
| | | | +-[DOT] '.'
| | | | | +-[IDENT] 'com'
| | | | | \-[IDENT] 'cosmetto'
| | | | \-[IDENT] 'ski'
| | | \-[IDENT] 'model'
| | \-[IDENT] 'Reservation'
| \-[ALIAS] 'res'
+-[WHERE] 'where'
| \-[EQ] '='
| +-[DOT] '.'
| | +-[IDENT] 'res'
| | \-[IDENT] 'date'
| \-[PARAM] '?'
\-[ORDER] 'order'
+-[DOT] '.'
| +-[IDENT] 'res'
| \-[IDENT] 'timestamp'
\-[ASCENDING] 'asc'

13:30:50,976 DEBUG ErrorCounter:72 - throwQueryException() : no errors
13:30:51,039 DEBUG HqlSqlBaseWalker:120 - query() << begin, level = 1
13:30:51,070 DEBUG FromElement:81 - FromClause{level=1} : com.cosmetto.ski.model.Reservation (res) -> reservatio0_
13:30:51,070 DEBUG FromReferenceNode:48 - Resolved : res -> reservatio0_.res_id
13:30:51,086 DEBUG DotNode:476 - getDataType() : date -> org.hibernate.type.CalendarDateType@d24e3f
13:30:51,086 DEBUG FromReferenceNode:48 - Resolved : res.date -> reservatio0_.date
13:30:51,086 DEBUG FromReferenceNode:48 - Resolved : res -> reservatio0_.res_id
13:30:51,086 DEBUG DotNode:476 - getDataType() : timestamp -> org.hibernate.type.TimestampType@b05acd
13:30:51,086 DEBUG FromReferenceNode:48 - Resolved : res.timestamp -> reservatio0_.timestamp
13:30:51,086 DEBUG HqlSqlBaseWalker:125 - query() : finishing up , level = 1
13:30:51,086 DEBUG HqlSqlWalker:331 - processQuery() : ( SELECT ( FromClause{level=1} SW_res reservatio0_ ) ( where ( = ( reservatio0_.date reservatio0_.res_id date ) ? ) ) ( order ( reservatio0_.timestamp reservatio0_.res_id timestamp ) asc ) )
13:30:51,101 DEBUG HqlSqlWalker:451 - Derived SELECT clause created.
13:30:51,117 DEBUG JoinProcessor:112 - Using FROM fragment [SW_res reservatio0_]
13:30:51,117 DEBUG HqlSqlBaseWalker:128 - query() >> end, level = 1
13:30:51,133 DEBUG AST:193 - --- SQL AST ---
\-[SELECT] QueryNode: 'SELECT' querySpaces (SW_res)
+-[SELECT_CLAUSE] SelectClause: '{derived select clause}'
| +-[SELECT_EXPR] SelectExpressionImpl: 'reservatio0_.res_id as res1_' {FromElement{explicit,not a collection join,not a fetch join,fetch non-lazy properties,classAlias=res,role=null,tableName=SW_res,tableAlias=reservatio0_,colums={,className=com.cosmetto.ski.model.Reservation}}}
| \-[SQL_TOKEN] SqlFragment: 'reservatio0_.version as version0_, reservatio0_.timestamp as timestamp0_, reservatio0_.date as date0_, reservatio0_.note as note0_, reservatio0_.guests as guests0_, reservatio0_.user_id as user7_0_'
+-[FROM] FromClause: 'from' FromClause{level=1, fromElementCounter=1, fromElements=1, fromElementByClassAlias=[res], fromElementByTableAlias=[reservatio0_], fromElementsByPath=[], collectionJoinFromElementsByPath=[], impliedElements=[]}
| \-[FROM_FRAGMENT] FromElement: 'SW_res reservatio0_' FromElement{explicit,not a collection join,not a fetch join,fetch non-lazy properties,classAlias=res,role=null,tableName=SW_res,tableAlias=reservatio0_,colums={,className=com.cosmetto.ski.model.Reservation}}
+-[WHERE] SqlNode: 'where'
| \-[EQ] SqlNode: '='
| +-[DOT] DotNode: 'reservatio0_.date' {propertyName=date,dereferenceType=4,propertyPath=date,path=res.date,tableAlias=reservatio0_,className=com.cosmetto.ski.model.Reservation,classAlias=res}
| | +-[ALIAS_REF] IdentNode: 'reservatio0_.res_id' {alias=res, className=com.cosmetto.ski.model.Reservation, tableAlias=reservatio0_}
| | \-[IDENT] IdentNode: 'date' {originalText=date}
| \-[PARAM] SqlNode: '?'
\-[ORDER] OrderByClause: 'order'
+-[DOT] DotNode: 'reservatio0_.timestamp' {propertyName=timestamp,dereferenceType=4,propertyPath=timestamp,path=res.timestamp,tableAlias=reservatio0_,className=com.cosmetto.ski.model.Reservation,classAlias=res}
| +-[ALIAS_REF] IdentNode: 'reservatio0_.res_id' {alias=res, className=com.cosmetto.ski.model.Reservation, tableAlias=reservatio0_}
| \-[IDENT] IdentNode: 'timestamp' {originalText=timestamp}
\-[ASCENDING] SqlNode: 'asc'

13:30:51,133 DEBUG ErrorCounter:72 - throwQueryException() : no errors
13:30:51,148 DEBUG QueryTranslatorImpl:177 - HQL: from com.cosmetto.ski.model.Reservation as res where res.date = ? order by res.timestamp asc
13:30:51,148 DEBUG QueryTranslatorImpl:178 - SQL: select reservatio0_.res_id as res1_, reservatio0_.version as version0_, reservatio0_.timestamp as timestamp0_, reservatio0_.date as date0_, reservatio0_.note as note0_, reservatio0_.guests as guests0_, reservatio0_.user_id as user7_0_ from SW_res reservatio0_ where reservatio0_.date=? order by reservatio0_.timestamp asc
13:30:51,164 DEBUG ErrorCounter:72 - throwQueryException() : no errors
13:30:51,164 DEBUG AbstractBatcher:277 - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
13:30:51,164 DEBUG SQL:311 - select reservatio0_.res_id as res1_, reservatio0_.version as version0_, reservatio0_.timestamp as timestamp0_, reservatio0_.date as date0_, reservatio0_.note as note0_, reservatio0_.guests as guests0_, reservatio0_.user_id as user7_0_ from SW_res reservatio0_ where reservatio0_.date=? order by reservatio0_.timestamp asc
Hibernate: select reservatio0_.res_id as res1_, reservatio0_.version as version0_, reservatio0_.timestamp as timestamp0_, reservatio0_.date as date0_, reservatio0_.note as note0_, reservatio0_.guests as guests0_, reservatio0_.user_id as user7_0_ from SW_res reservatio0_ where reservatio0_.date=? order by reservatio0_.timestamp asc
13:30:51,180 DEBUG AbstractBatcher:365 - preparing statement
13:30:51,180 DEBUG CalendarType:59 - binding '2004-01-01 00:00:00' to parameter: 1
13:30:51,180 DEBUG AbstractBatcher:293 - about to open ResultSet (open ResultSets: 0, globally: 0)
13:30:51,195 DEBUG Loader:384 - processing result set
13:30:51,195 DEBUG Loader:389 - result set row: 0
13:30:51,195 DEBUG LongType:86 - returning '32769' as column: res1_
13:30:51,195 DEBUG Loader:791 - result row: EntityKey[com.cosmetto.ski.model.Reservation#32769]
13:30:51,195 DEBUG Loader:941 - Initializing object from ResultSet: [com.cosmetto.ski.model.Reservation#32769]
13:30:51,195 DEBUG BasicEntityPersister:1641 - Hydrating entity: [com.cosmetto.ski.model.Reservation#32769]
13:30:51,195 DEBUG IntegerType:86 - returning '0' as column: version0_
13:30:51,195 DEBUG TimestampType:86 - returning '2005-05-10 13:30:50' as column: timestamp0_
13:30:51,195 DEBUG CalendarDateType:86 - returning '01 January 2004' as column: date0_
13:30:51,211 DEBUG StringType:86 - returning '2nd reservation' as column: note0_
13:30:51,211 DEBUG IntegerType:86 - returning '2' as column: guests0_
13:30:51,211 DEBUG LongType:86 - returning '1' as column: user7_0_
13:30:51,211 DEBUG TwoPhaseLoad:67 - Version: 0
13:30:51,211 DEBUG Loader:408 - done processing result set (1 rows)
13:30:51,211 DEBUG AbstractBatcher:300 - about to close ResultSet (open ResultSets: 1, globally: 1)
13:30:51,211 DEBUG AbstractBatcher:285 - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
13:30:51,211 DEBUG AbstractBatcher:403 - closing statement
13:30:51,211 DEBUG Loader:504 - total objects hydrated: 1
13:30:51,226 DEBUG TwoPhaseLoad:96 - resolving associations for [com.cosmetto.ski.model.Reservation#32769]
13:30:51,226 DEBUG DefaultLoadEventListener:185 - loading entity: [com.cosmetto.ski.model.User#1]
13:30:51,226 DEBUG DefaultLoadEventListener:258 - creating new proxy for entity
13:30:51,226 DEBUG TwoPhaseLoad:167 - done materializing entity [com.cosmetto.ski.model.Reservation#32769]
13:30:51,226 DEBUG PersistenceContext:789 - initializing non-lazy collections
13:30:51,226 DEBUG ReservationDAOTest:166 - List [ note: 2nd reservation guests: 2 date: Thu Jan 01 00:00:00 PST 2004 id: 32769]
13:30:51,226 DEBUG ReservationDAOTest:170 - reservatioin note: 2nd reservation guests: 2 date: Thu Jan 01 00:00:00 PST 2004 id: 32769
13:30:51,242 DEBUG ReservationDAOTest:172 - resid 32769
13:30:51,242 DEBUG SessionImpl:237 - opened session at timestamp: 11157570512
13:30:51,242 DEBUG JDBCTransaction:46 - begin
13:30:51,242 DEBUG AbstractBatcher:422 - opening JDBC connection
13:30:51,242 DEBUG DriverManagerConnectionProvider:93 - total checked-out connections: 1
13:30:51,242 DEBUG DriverManagerConnectionProvider:109 - opening new JDBC connection
13:30:51,273 DEBUG DriverManagerConnectionProvider:115 - created connection to: jdbc:mysql:///test, Isolation Level: 2
13:30:51,273 DEBUG JDBCTransaction:50 - current autocommit status: false
13:30:51,289 DEBUG SessionImpl:237 - opened session at timestamp: 11157570512
13:30:51,289 DEBUG JDBCTransaction:46 - begin
13:30:51,289 DEBUG AbstractBatcher:422 - opening JDBC connection
13:30:51,289 DEBUG DriverManagerConnectionProvider:93 - total checked-out connections: 2
13:30:51,289 DEBUG DriverManagerConnectionProvider:109 - opening new JDBC connection
13:30:51,320 DEBUG DriverManagerConnectionProvider:115 - created connection to: jdbc:mysql:///test, Isolation Level: 2
13:30:51,320 DEBUG JDBCTransaction:50 - current autocommit status: false
13:30:51,320 DEBUG ReservationDAOTest:179 - ses1 org.hibernate.impl.SessionImpl(PersistentContext[entitiesByKey={}] ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[]]) 15855697
13:30:51,320 DEBUG ReservationDAOTest:180 - ses2 org.hibernate.impl.SessionImpl(PersistentContext[entitiesByKey={}] ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[]]) 30969271
13:30:51,336 DEBUG DefaultLoadEventListener:185 - loading entity: [com.cosmetto.ski.model.Reservation#32769]
13:30:51,336 DEBUG DefaultLoadEventListener:258 - creating new proxy for entity
13:30:51,336 DEBUG DefaultLoadEventListener:185 - loading entity: [com.cosmetto.ski.model.Reservation#32769]
13:30:51,351 DEBUG DefaultLoadEventListener:258 - creating new proxy for entity
13:30:51,351 DEBUG SessionImpl:589 - initializing proxy: [com.cosmetto.ski.model.Reservation#32769]
13:30:51,351 DEBUG DefaultLoadEventListener:331 - attempting to resolve: [com.cosmetto.ski.model.Reservation#32769]
13:30:51,351 DEBUG DefaultLoadEventListener:367 - object not resolved in any cache: [com.cosmetto.ski.model.Reservation#32769]
13:30:51,351 DEBUG BasicEntityPersister:2457 - Materializing entity: [com.cosmetto.ski.model.Reservation#32769]
13:30:51,351 DEBUG Loader:1302 - loading entity: [com.cosmetto.ski.model.Reservation#32769]
13:30:51,351 DEBUG AbstractBatcher:277 - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
13:30:51,367 DEBUG SQL:311 - select reservatio0_.res_id as res1_0_, reservatio0_.version as version0_0_, reservatio0_.timestamp as timestamp0_0_, reservatio0_.date as date0_0_, reservatio0_.note as note0_0_, reservatio0_.guests as guests0_0_, reservatio0_.user_id as user7_0_0_ from SW_res reservatio0_ where reservatio0_.res_id=?
Hibernate: select reservatio0_.res_id as res1_0_, reservatio0_.version as version0_0_, reservatio0_.timestamp as timestamp0_0_, reservatio0_.date as date0_0_, reservatio0_.note as note0_0_, reservatio0_.guests as guests0_0_, reservatio0_.user_id as user7_0_0_ from SW_res reservatio0_ where reservatio0_.res_id=?
13:30:51,367 DEBUG AbstractBatcher:365 - preparing statement
13:30:51,367 DEBUG LongType:59 - binding '32769' to parameter: 1
13:30:51,367 DEBUG AbstractBatcher:293 - about to open ResultSet (open ResultSets: 0, globally: 0)
13:30:51,383 DEBUG Loader:384 - processing result set
13:30:51,383 DEBUG Loader:389 - result set row: 0
13:30:51,383 DEBUG Loader:791 - result row: EntityKey[com.cosmetto.ski.model.Reservation#32769]
13:30:51,383 DEBUG Loader:941 - Initializing object from ResultSet: [com.cosmetto.ski.model.Reservation#32769]
13:30:51,383 DEBUG BasicEntityPersister:1641 - Hydrating entity: [com.cosmetto.ski.model.Reservation#32769]
13:30:51,383 DEBUG IntegerType:86 - returning '0' as column: version0_0_
13:30:51,383 DEBUG TimestampType:86 - returning '2005-05-10 13:30:50' as column: timestamp0_0_
13:30:51,383 DEBUG CalendarDateType:86 - returning '01 January 2004' as column: date0_0_
13:30:51,383 DEBUG StringType:86 - returning '2nd reservation' as column: note0_0_
13:30:51,383 DEBUG IntegerType:86 - returning '2' as column: guests0_0_
13:30:51,398 DEBUG LongType:86 - returning '1' as column: user7_0_0_
13:30:51,398 DEBUG TwoPhaseLoad:67 - Version: 0
13:30:51,398 DEBUG Loader:408 - done processing result set (1 rows)
13:30:51,398 DEBUG AbstractBatcher:300 - about to close ResultSet (open ResultSets: 1, globally: 1)
13:30:51,398 DEBUG AbstractBatcher:285 - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
13:30:51,398 DEBUG AbstractBatcher:403 - closing statement
13:30:51,398 DEBUG Loader:504 - total objects hydrated: 1
13:30:51,398 DEBUG TwoPhaseLoad:96 - resolving associations for [com.cosmetto.ski.model.Reservation#32769]
13:30:51,398 DEBUG DefaultLoadEventListener:185 - loading entity: [com.cosmetto.ski.model.User#1]
13:30:51,398 DEBUG DefaultLoadEventListener:258 - creating new proxy for entity
13:30:51,398 DEBUG TwoPhaseLoad:167 - done materializing entity [com.cosmetto.ski.model.Reservation#32769]
13:30:51,414 DEBUG PersistenceContext:789 - initializing non-lazy collections
13:30:51,414 DEBUG Loader:1330 - done entity load
13:30:51,414 DEBUG AbstractSaveEventListener:393 - persistent instance of: com.cosmetto.ski.model.Reservation
13:30:51,414 DEBUG DefaultSaveOrUpdateEventListener:103 - ignoring persistent instance
13:30:51,414 DEBUG DefaultSaveOrUpdateEventListener:140 - object already associated with session: [com.cosmetto.ski.model.Reservation#32769]
13:30:51,414 DEBUG JDBCTransaction:83 - commit
13:30:51,414 DEBUG SessionImpl:308 - automatically flushing session
13:30:51,414 DEBUG AbstractFlushingEventListener:52 - flushing session
13:30:51,414 DEBUG AbstractFlushingEventListener:102 - processing flush-time cascades
13:30:51,414 DEBUG Cascades:806 - processing cascade ACTION_SAVE_UPDATE for: com.cosmetto.ski.model.Reservation
13:30:51,414 DEBUG Cascades:152 - cascading to saveOrUpdate: com.cosmetto.ski.model.User
13:30:51,414 DEBUG DefaultSaveOrUpdateEventListener:58 - reassociated uninitialized proxy
13:30:51,414 DEBUG Cascades:831 - done processing cascade ACTION_SAVE_UPDATE for: com.cosmetto.ski.model.Reservation
13:30:51,414 DEBUG AbstractFlushingEventListener:150 - dirty checking collections
13:30:51,414 DEBUG AbstractFlushingEventListener:167 - Flushing entities and processing referenced collections
13:30:51,414 DEBUG BasicEntityPersister:2585 - com.cosmetto.ski.model.Reservation.guests is dirty
13:30:51,414 DEBUG DefaultFlushEntityEventListener:121 - Updating entity: [com.cosmetto.ski.model.Reservation#32769]
13:30:51,430 DEBUG Versioning:26 - Incrementing: 0 to 1
13:30:51,430 DEBUG AbstractFlushingEventListener:203 - Processing unreferenced collections
13:30:51,430 DEBUG AbstractFlushingEventListener:217 - Scheduling collection removes/(re)creates/updates
13:30:51,430 DEBUG AbstractFlushingEventListener:79 - Flushed: 0 insertions, 1 updates, 0 deletions to 1 objects
13:30:51,430 DEBUG AbstractFlushingEventListener:85 - Flushed: 0 (re)creations, 0 updates, 0 removals to 0 collections
13:30:51,430 DEBUG Printer:83 - listing entities:
13:30:51,430 DEBUG Printer:90 - com.cosmetto.ski.model.Reservation{guests=-1404756226, user=com.cosmetto.ski.model.User#1, timestamp=2005-05-10 13:30:50, note=2nd reservation, date=01 January 2004, id=32769, version=0}
13:30:51,430 DEBUG AbstractFlushingEventListener:267 - executing flush
13:30:51,430 DEBUG BasicEntityPersister:1930 - Updating entity: [com.cosmetto.ski.model.Reservation#32769]
13:30:51,430 DEBUG BasicEntityPersister:1931 - Existing version: 0 -> New version: 1
13:30:51,430 DEBUG AbstractBatcher:277 - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
13:30:51,445 DEBUG SQL:311 - update SW_res set version=?, timestamp=?, date=?, note=?, guests=?, user_id=? where res_id=? and version=?
Hibernate: update SW_res set version=?, timestamp=?, date=?, note=?, guests=?, user_id=? where res_id=? and version=?
13:30:51,445 DEBUG AbstractBatcher:365 - preparing statement
13:30:51,445 DEBUG BasicEntityPersister:1602 - Dehydrating entity: [com.cosmetto.ski.model.Reservation#32769]
13:30:51,445 DEBUG IntegerType:59 - binding '1' to parameter: 1
13:30:51,445 DEBUG TimestampType:59 - binding '2005-05-10 13:30:50' to parameter: 2
13:30:51,461 DEBUG CalendarDateType:59 - binding '01 January 2004' to parameter: 3
13:30:51,461 DEBUG StringType:59 - binding '2nd reservation' to parameter: 4
13:30:51,461 DEBUG IntegerType:59 - binding '-1404756226' to parameter: 5
13:30:51,461 DEBUG LongType:59 - binding '1' to parameter: 6
13:30:51,461 DEBUG LongType:59 - binding '32769' to parameter: 7
13:30:51,461 DEBUG IntegerType:59 - binding '0' to parameter: 8
13:30:51,461 DEBUG AbstractBatcher:285 - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
13:30:51,461 DEBUG AbstractBatcher:403 - closing statement
13:30:51,476 DEBUG AbstractFlushingEventListener:294 - post flush
13:30:51,476 DEBUG JDBCContext:216 - before transaction completion
13:30:51,476 DEBUG SessionImpl:353 - before transaction completion
13:30:51,523 DEBUG JDBCTransaction:96 - committed JDBC Connection
13:30:51,523 DEBUG JDBCContext:221 - after transaction completion
13:30:51,523 DEBUG SessionImpl:369 - after transaction completion
13:30:51,523 DEBUG SessionImpl:589 - initializing proxy: [com.cosmetto.ski.model.Reservation#32769]
13:30:51,523 DEBUG DefaultLoadEventListener:331 - attempting to resolve: [com.cosmetto.ski.model.Reservation#32769]
13:30:51,523 DEBUG DefaultLoadEventListener:367 - object not resolved in any cache: [com.cosmetto.ski.model.Reservation#32769]
13:30:51,523 DEBUG BasicEntityPersister:2457 - Materializing entity: [com.cosmetto.ski.model.Reservation#32769]
13:30:51,523 DEBUG Loader:1302 - loading entity: [com.cosmetto.ski.model.Reservation#32769]
13:30:51,523 DEBUG AbstractBatcher:277 - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
13:30:51,523 DEBUG SQL:311 - select reservatio0_.res_id as res1_0_, reservatio0_.version as version0_0_, reservatio0_.timestamp as timestamp0_0_, reservatio0_.date as date0_0_, reservatio0_.note as note0_0_, reservatio0_.guests as guests0_0_, reservatio0_.user_id as user7_0_0_ from SW_res reservatio0_ where reservatio0_.res_id=?
Hibernate: select reservatio0_.res_id as res1_0_, reservatio0_.version as version0_0_, reservatio0_.timestamp as timestamp0_0_, reservatio0_.date as date0_0_, reservatio0_.note as note0_0_, reservatio0_.guests as guests0_0_, reservatio0_.user_id as user7_0_0_ from SW_res reservatio0_ where reservatio0_.res_id=?
13:30:51,539 DEBUG AbstractBatcher:365 - preparing statement
13:30:51,539 DEBUG LongType:59 - binding '32769' to parameter: 1
13:30:51,539 DEBUG AbstractBatcher:293 - about to open ResultSet (open ResultSets: 0, globally: 0)
13:30:51,539 DEBUG Loader:384 - processing result set
13:30:51,539 DEBUG Loader:389 - result set row: 0
13:30:51,539 DEBUG Loader:791 - result row: EntityKey[com.cosmetto.ski.model.Reservation#32769]
13:30:51,539 DEBUG Loader:941 - Initializing object from ResultSet: [com.cosmetto.ski.model.Reservation#32769]
13:30:51,539 DEBUG BasicEntityPersister:1641 - Hydrating entity: [com.cosmetto.ski.model.Reservation#32769]
13:30:51,539 DEBUG IntegerType:86 - returning '1' as column: version0_0_
13:30:51,539 DEBUG TimestampType:86 - returning '2005-05-10 13:30:50' as column: timestamp0_0_
13:30:51,555 DEBUG CalendarDateType:86 - returning '01 January 2004' as column: date0_0_
13:30:51,555 DEBUG StringType:86 - returning '2nd reservation' as column: note0_0_
13:30:51,555 DEBUG IntegerType:86 - returning '-1404756226' as column: guests0_0_
13:30:51,555 DEBUG LongType:86 - returning '1' as column: user7_0_0_
13:30:51,555 DEBUG TwoPhaseLoad:67 - Version: 1
13:30:51,555 DEBUG Loader:408 - done processing result set (1 rows)
13:30:51,555 DEBUG AbstractBatcher:300 - about to close ResultSet (open ResultSets: 1, globally: 1)
13:30:51,555 DEBUG AbstractBatcher:285 - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
13:30:51,555 DEBUG AbstractBatcher:403 - closing statement
13:30:51,555 DEBUG Loader:504 - total objects hydrated: 1
13:30:51,555 DEBUG TwoPhaseLoad:96 - resolving associations for [com.cosmetto.ski.model.Reservation#32769]
13:30:51,555 DEBUG DefaultLoadEventListener:185 - loading entity: [com.cosmetto.ski.model.User#1]
13:30:51,555 DEBUG DefaultLoadEventListener:258 - creating new proxy for entity
13:30:51,570 DEBUG TwoPhaseLoad:167 - done materializing entity [com.cosmetto.ski.model.Reservation#32769]
13:30:51,570 DEBUG PersistenceContext:789 - initializing non-lazy collections
13:30:51,570 DEBUG Loader:1330 - done entity load
13:30:51,570 DEBUG AbstractSaveEventListener:393 - persistent instance of: com.cosmetto.ski.model.Reservation
13:30:51,570 DEBUG DefaultSaveOrUpdateEventListener:103 - ignoring persistent instance
13:30:51,570 DEBUG DefaultSaveOrUpdateEventListener:140 - object already associated with session: [com.cosmetto.ski.model.Reservation#32769]
13:30:51,570 DEBUG JDBCTransaction:83 - commit
13:30:51,570 DEBUG SessionImpl:308 - automatically flushing session
13:30:51,570 DEBUG AbstractFlushingEventListener:52 - flushing session
13:30:51,570 DEBUG AbstractFlushingEventListener:102 - processing flush-time cascades
13:30:51,570 DEBUG Cascades:806 - processing cascade ACTION_SAVE_UPDATE for: com.cosmetto.ski.model.Reservation
13:30:51,570 DEBUG Cascades:152 - cascading to saveOrUpdate: com.cosmetto.ski.model.User
13:30:51,570 DEBUG DefaultSaveOrUpdateEventListener:58 - reassociated uninitialized proxy
13:30:51,570 DEBUG Cascades:831 - done processing cascade ACTION_SAVE_UPDATE for: com.cosmetto.ski.model.Reservation
13:30:51,570 DEBUG AbstractFlushingEventListener:150 - dirty checking collections
13:30:51,570 DEBUG AbstractFlushingEventListener:167 - Flushing entities and processing referenced collections
13:30:51,570 DEBUG BasicEntityPersister:2585 - com.cosmetto.ski.model.Reservation.guests is dirty
13:30:51,586 DEBUG DefaultFlushEntityEventListener:121 - Updating entity: [com.cosmetto.ski.model.Reservation#32769]
13:30:51,586 DEBUG Versioning:26 - Incrementing: 1 to 2
13:30:51,586 DEBUG AbstractFlushingEventListener:203 - Processing unreferenced collections
13:30:51,586 DEBUG AbstractFlushingEventListener:217 - Scheduling collection removes/(re)creates/updates
13:30:51,586 DEBUG AbstractFlushingEventListener:79 - Flushed: 0 insertions, 1 updates, 0 deletions to 1 objects
13:30:51,586 DEBUG AbstractFlushingEventListener:85 - Flushed: 0 (re)creations, 0 updates, 0 removals to 0 collections
13:30:51,586 DEBUG Printer:83 - listing entities:
13:30:51,586 DEBUG Printer:90 - com.cosmetto.ski.model.Reservation{guests=-1404756225, user=com.cosmetto.ski.model.User#1, timestamp=2005-05-10 13:30:50, note=2nd reservation, date=01 January 2004, id=32769, version=1}
13:30:51,586 DEBUG AbstractFlushingEventListener:267 - executing flush
13:30:51,586 DEBUG BasicEntityPersister:1930 - Updating entity: [com.cosmetto.ski.model.Reservation#32769]
13:30:51,601 DEBUG BasicEntityPersister:1931 - Existing version: 1 -> New version: 2
13:30:51,601 DEBUG AbstractBatcher:277 - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
13:30:51,601 DEBUG SQL:311 - update SW_res set version=?, timestamp=?, date=?, note=?, guests=?, user_id=? where res_id=? and version=?
Hibernate: update SW_res set version=?, timestamp=?, date=?, note=?, guests=?, user_id=? where res_id=? and version=?
13:30:51,601 DEBUG AbstractBatcher:365 - preparing statement
13:30:51,601 DEBUG BasicEntityPersister:1602 - Dehydrating entity: [com.cosmetto.ski.model.Reservation#32769]
13:30:51,601 DEBUG IntegerType:59 - binding '2' to parameter: 1
13:30:51,601 DEBUG TimestampType:59 - binding '2005-05-10 13:30:50' to parameter: 2
13:30:51,601 DEBUG CalendarDateType:59 - binding '01 January 2004' to parameter: 3
13:30:51,601 DEBUG StringType:59 - binding '2nd reservation' to parameter: 4
13:30:51,601 DEBUG IntegerType:59 - binding '-1404756225' to parameter: 5
13:30:51,601 DEBUG LongType:59 - binding '1' to parameter: 6
13:30:51,601 DEBUG LongType:59 - binding '32769' to parameter: 7
13:30:51,601 DEBUG IntegerType:59 - binding '1' to parameter: 8
13:30:51,617 DEBUG AbstractBatcher:285 - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
13:30:51,617 DEBUG AbstractBatcher:403 - closing statement
13:30:51,617 DEBUG AbstractFlushingEventListener:294 - post flush
13:30:51,617 DEBUG JDBCContext:216 - before transaction completion
13:30:51,617 DEBUG SessionImpl:353 - before transaction completion
13:30:51,664 DEBUG JDBCTransaction:96 - committed JDBC Connection
13:30:51,664 DEBUG JDBCContext:221 - after transaction completion
13:30:51,680 DEBUG SessionImpl:369 - after transaction completion
13:30:51,680 DEBUG SessionImpl:254 - closing session
13:30:51,680 DEBUG AbstractBatcher:437 - closing JDBC connection (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: 0)
13:30:51,680 DEBUG DriverManagerConnectionProvider:129 - returning connection to pool, pool size: 1
13:30:51,680 DEBUG JDBCContext:221 - after transaction completion
13:30:51,680 DEBUG SessionImpl:369 - after transaction completion
13:30:51,680 DEBUG SessionImpl:254 - closing session
13:30:51,680 DEBUG AbstractBatcher:437 - closing JDBC connection (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: 0)
13:30:51,680 DEBUG DriverManagerConnectionProvider:135 - closing JDBC connection
13:30:51,711 DEBUG JDBCContext:221 - after transaction completion
13:30:51,711 DEBUG SessionImpl:369 - after transaction completion
13:30:51,711 DEBUG HibernateUtil:201 - Tyring to rollback database transaction of this thread.
13:30:51,711 DEBUG JDBCTransaction:124 - rollback
13:30:51,711 DEBUG JDBCContext:216 - before transaction completion
13:30:51,711 DEBUG SessionImpl:353 - before transaction completion
13:30:51,711 DEBUG JDBCTransaction:135 - rolled back JDBC Connection
13:30:51,711 DEBUG JDBCContext:221 - after transaction completion
13:30:51,711 DEBUG SessionImpl:369 - after transaction completion
13:30:51,711 DEBUG HibernateUtil:148 - Closing Session of this thread.
13:30:51,711 DEBUG SessionImpl:254 - closing session
13:30:51,726 DEBUG AbstractBatcher:437 - closing JDBC connection (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: 0)
13:30:51,726 DEBUG DriverManagerConnectionProvider:135 - closing JDBC connection
13:30:51,726 DEBUG JDBCContext:221 - after transaction completion
13:30:51,726 DEBUG SessionImpl:369 - after transaction completion
Testsuite: com.cosmetto.ski.dao.ReservationDAOTest
Tests run: 1, Failures: 1, Errors: 0, Time elapsed: 6.484 sec

------------- Standard Output ---------------
TestCase.setUp() export schema
config + org.hibernate.cfg.Configuration@95c083
Running test...
TestCaseWithData.initDAta()
Hibernate: insert into SW_user (version, email, first_name, last_name, user_name, password, label, street, city, state, country, zip, pn1_area_code, pn1_number, pn1_label, pn2_area_code, pn2_number, pn2_label, pn3_area_code, pn3_number, pn3_label, user_id) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into SW_res (version, timestamp, date, note, guests, user_id, res_id) values (?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into SW_res (version, timestamp, date, note, guests, user_id, res_id) values (?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into SW_user (version, email, first_name, last_name, user_name, password, label, street, city, state, country, zip, pn1_area_code, pn1_number, pn1_label, pn2_area_code, pn2_number, pn2_label, pn3_area_code, pn3_number, pn3_label, user_id) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into SW_res (version, timestamp, date, note, guests, user_id, res_id) values (?, ?, ?, ?, ?, ?, ?)
testIsolationAndVersioning
Hibernate: select reservatio0_.res_id as res1_, reservatio0_.version as version0_, reservatio0_.timestamp as timestamp0_, reservatio0_.date as date0_, reservatio0_.note as note0_, reservatio0_.guests as guests0_, reservatio0_.user_id as user7_0_ from SW_res reservatio0_ where reservatio0_.date=? order by reservatio0_.timestamp asc
Hibernate: select reservatio0_.res_id as res1_0_, reservatio0_.version as version0_0_, reservatio0_.timestamp as timestamp0_0_, reservatio0_.date as date0_0_, reservatio0_.note as note0_0_, reservatio0_.guests as guests0_0_, reservatio0_.user_id as user7_0_0_ from SW_res reservatio0_ where reservatio0_.res_id=?
Hibernate: update SW_res set version=?, timestamp=?, date=?, note=?, guests=?, user_id=? where res_id=? and version=?
Hibernate: select reservatio0_.res_id as res1_0_, reservatio0_.version as version0_0_, reservatio0_.timestamp as timestamp0_0_, reservatio0_.date as date0_0_, reservatio0_.note as note0_0_, reservatio0_.guests as guests0_0_, reservatio0_.user_id as user7_0_0_ from SW_res reservatio0_ where reservatio0_.res_id=?
Hibernate: update SW_res set version=?, timestamp=?, date=?, note=?, guests=?, user_id=? where res_id=? and version=?
------------- ---------------- ---------------
Testcase: testIsolationAndVersioning(com.cosmetto.ski.dao.ReservationDAOTest): FAILED
Should Raise a net.sf.hibernate.StaleObjectStateException
junit.framework.AssertionFailedError: Should Raise a net.sf.hibernate.StaleObjectStateException
at com.cosmetto.ski.dao.ReservationDAOTest.testIsolationAndVersioning(ReservationDAOTest.java:195)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at com.cosmetto.ski.dao.TestCase.runTest(TestCase.java:33)


Test com.cosmetto.ski.dao.ReservationDAOTest FAILED
C:\sandbox\skiReservations\nbproject\build-impl.xml:417: Some tests failed; see details above.
BUILD FAILED (total time: 7 seconds)

HibernateUtils
package com.cosmetto.ski.persistence;

import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.Interceptor;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.apache.log4j.Logger;
import com.cosmetto.ski.exceptions.InfrastructureException;

import javax.naming.*;

/**
* Basic Hibernate helper class, handles SessionFactory, Session and Transaction.
* <p>
* Uses a static initializer for the initial SessionFactory creation
* and holds Session and Transactions in thread local variables. All
* exceptions are wrapped in an unchecked InfrastructureException.
*
* @author christian@hibernate.org
*/
public class HibernateUtil {

private static Logger log = Logger.getLogger(HibernateUtil.class);

private static Configuration configuration;
private static SessionFactory sessionFactory;
private static final ThreadLocal threadSession = new ThreadLocal();
private static final ThreadLocal threadTransaction = new ThreadLocal();
private static final ThreadLocal threadInterceptor = new ThreadLocal();

// Create the initial SessionFactory from the default configuration files
static {
try {
configuration = new Configuration();
System.out.println("config + " + configuration);
sessionFactory = configuration.configure().buildSessionFactory();
// We could also let Hibernate bind it to JNDI:
// configuration.configure().buildSessionFactory()
} catch (Throwable ex) {
// We have to catch Throwable, otherwise we will miss
// NoClassDefFoundError and other subclasses of Error
log.error("Building SessionFactory failed.", ex);
throw new ExceptionInInitializerError(ex);
}
log.debug("static init - session factory built = " + sessionFactory);
}

/**
* Returns the SessionFactory used for this static class.
*
* @return SessionFactory
*/
public static SessionFactory getSessionFactory() {
/* Instead of a static variable, use JNDI:
SessionFactory sessions = null;
try {
Context ctx = new InitialContext();
String jndiName = "java:hibernate/HibernateFactory";
sessions = (SessionFactory)ctx.lookup(jndiName);
} catch (NamingException ex) {
throw new InfrastructureException(ex);
}
return sessions;
*/
return sessionFactory;
}

/**
* Returns the original Hibernate configuration.
*
* @return Configuration
*/
public static Configuration getConfiguration() {
return configuration;
}

/**
* Rebuild the SessionFactory with the static Configuration.
*
*/
public static void rebuildSessionFactory()
throws InfrastructureException {
synchronized(sessionFactory) {
try {
sessionFactory = getConfiguration().buildSessionFactory();
} catch (Exception ex) {
throw new InfrastructureException(ex);
}
}
}

/**
* Rebuild the SessionFactory with the given Hibernate Configuration.
*
* @param cfg
*/
public static void rebuildSessionFactory(Configuration cfg)
throws InfrastructureException {
synchronized(sessionFactory) {
try {
sessionFactory = cfg.buildSessionFactory();
configuration = cfg;
} catch (Exception ex) {
throw new InfrastructureException(ex);
}
}
}

/**
* Retrieves the current Session local to the thread.
* <p/>
* If no Session is open, opens a new Session for the running thread.
*
* @return Session
*/
public static Session getSession()
throws InfrastructureException {
Session s = (Session) threadSession.get();
try {
if (s == null) {
log.debug("Opening new Session for this thread.");
if (getInterceptor() != null) {
log.debug("Using interceptor: " + getInterceptor().getClass());
s = getSessionFactory().openSession(getInterceptor());
} else {
s = getSessionFactory().openSession();
}
threadSession.set(s);
}
} catch (HibernateException ex) {
throw new InfrastructureException(ex);
}

return s;
}

/**
* Closes the Session local to the thread.
*/
public static void closeSession()
throws InfrastructureException {
try {
Session s = (Session) threadSession.get();
threadSession.set(null);
if (s != null && s.isOpen()) {
log.debug("Closing Session of this thread.");
s.close();
}
} catch (HibernateException ex) {
throw new InfrastructureException(ex);
}
}

/**
* Start a new database transaction.
*/
public static void beginTransaction()
throws InfrastructureException {
Transaction tx = (Transaction) threadTransaction.get();
try {
if (tx == null) {
log.debug("Starting new database transaction in this thread.");
tx = getSession().beginTransaction();
threadTransaction.set(tx);
}
} catch (HibernateException ex) {
throw new InfrastructureException(ex);
}
}

/**
* Commit the database transaction.
*/
public static void commitTransaction()
throws InfrastructureException {
Transaction tx = (Transaction) threadTransaction.get();
try {
if ( tx != null && !tx.wasCommitted()
&& !tx.wasRolledBack() ) {
log.debug("Committing database transaction of this thread.");
tx.commit();
}
threadTransaction.set(null);
} catch (HibernateException ex) {
rollbackTransaction();
throw new InfrastructureException(ex);
}
}

/**
* Commit the database transaction.
*/
public static void rollbackTransaction()
throws InfrastructureException {
Transaction tx = (Transaction) threadTransaction.get();
try {
threadTransaction.set(null);
if ( tx != null && !tx.wasCommitted() && !tx.wasRolledBack() ) {
log.debug("Tyring to rollback database transaction of this thread.");
tx.rollback();
}
} catch (HibernateException ex) {
throw new InfrastructureException(ex);
} finally {
closeSession();
}
}

/**
* Reconnects a Hibernate Session to the current Thread.
*
* @param session The Hibernate Session to be reconnected.
*/
public static void reconnect(Session session)
throws InfrastructureException {
try {
session.reconnect();
threadSession.set(session);
} catch (HibernateException ex) {
throw new InfrastructureException(ex);
}
}

/**
* Disconnect and return Session from current Thread.
*
* @return Session the disconnected Session
*/
public static Session disconnectSession()
throws InfrastructureException {

Session session = getSession();
try {
threadSession.set(null);
if (session.isConnected() && session.isOpen())
session.disconnect();
} catch (HibernateException ex) {
throw new InfrastructureException(ex);
}
return session;
}

/**
* Register a Hibernate interceptor with the current thread.
* <p>
* Every Session opened is opened with this interceptor after
* registration. Has no effect if the current Session of the
* thread is already open, effective on next close()/getSession().
*/
public static void registerInterceptor(Interceptor interceptor) {
threadInterceptor.set(interceptor);
}

private static Interceptor getInterceptor() {
Interceptor interceptor =
(Interceptor) threadInterceptor.get();
return interceptor;
}

}


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

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.