Hibernate SVN: r18644 - core/trunk/entitymanager/src/main/java/org/hibernate/ejb.
by hibernate-commits@lists.jboss.org
Author: smarlow(a)redhat.com
Date: 2010-01-27 09:00:57 -0500 (Wed, 27 Jan 2010)
New Revision: 18644
Modified:
core/trunk/entitymanager/src/main/java/org/hibernate/ejb/AbstractEntityManagerImpl.java
Log:
HHH-4853 3.4.4.3 Lock Mode Properties and Uses, Vendor-specific hints must be ignored if they are not understood.
Modified: core/trunk/entitymanager/src/main/java/org/hibernate/ejb/AbstractEntityManagerImpl.java
===================================================================
--- core/trunk/entitymanager/src/main/java/org/hibernate/ejb/AbstractEntityManagerImpl.java 2010-01-27 09:26:42 UTC (rev 18643)
+++ core/trunk/entitymanager/src/main/java/org/hibernate/ejb/AbstractEntityManagerImpl.java 2010-01-27 14:00:57 UTC (rev 18644)
@@ -191,30 +191,35 @@
boolean extended = PessimisticLockScope.EXTENDED.equals( ( PessimisticLockScope ) lockScope );
options.setScope( extended );
}
- else {
+ else if ( lockScope != null ) {
throw new PersistenceException( "Unable to parse " + AvailableSettings.LOCK_SCOPE + ": " + lockScope );
}
Object lockTimeout = props.get( AvailableSettings.LOCK_TIMEOUT );
- int timeout;
+ int timeout = 0;
+ boolean timeoutSet = false;
if ( lockTimeout instanceof String ) {
timeout = Integer.parseInt( ( String ) lockTimeout );
+ timeoutSet = true;
}
else if ( lockTimeout instanceof Integer ) {
timeout = ( Integer ) lockTimeout;
+ timeoutSet = true;
}
- else {
+ else if ( lockTimeout != null ) {
throw new PersistenceException( "Unable to parse " + AvailableSettings.LOCK_TIMEOUT + ": " + lockTimeout );
}
- if ( timeout < 0 ) {
- options.setTimeOut( LockOptions.WAIT_FOREVER );
+ if ( timeoutSet != false ) {
+ if ( timeout < 0 ) {
+ options.setTimeOut( LockOptions.WAIT_FOREVER );
+ }
+ else if ( timeout == 0 ) {
+ options.setTimeOut( LockOptions.NO_WAIT );
+ }
+ else {
+ options.setTimeOut( timeout );
+ }
}
- else if ( timeout == 0 ) {
- options.setTimeOut( LockOptions.NO_WAIT );
- }
- else {
- options.setTimeOut( timeout );
- }
}
/**
15 years, 1 month
Hibernate SVN: r18643 - in core/trunk: testsuite/src/test/java/org/hibernate/test/readonly and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: gbadner
Date: 2010-01-27 04:26:42 -0500 (Wed, 27 Jan 2010)
New Revision: 18643
Modified:
core/trunk/core/src/main/java/org/hibernate/event/def/DefaultRefreshEventListener.java
core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlyProxyTest.java
core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlySessionLazyNonLazyTest.java
core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlySessionTest.java
core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlyTest.java
Log:
HHH-4781 : Read-only entities changed to modifiable on refresh
Modified: core/trunk/core/src/main/java/org/hibernate/event/def/DefaultRefreshEventListener.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/event/def/DefaultRefreshEventListener.java 2010-01-27 08:00:27 UTC (rev 18642)
+++ core/trunk/core/src/main/java/org/hibernate/event/def/DefaultRefreshEventListener.java 2010-01-27 09:26:42 UTC (rev 18643)
@@ -71,7 +71,13 @@
final EventSource source = event.getSession();
- if ( source.getPersistenceContext().reassociateIfUninitializedProxy( event.getObject() ) ) return;
+ boolean isTransient = ! source.contains( event.getObject() );
+ if ( source.getPersistenceContext().reassociateIfUninitializedProxy( event.getObject() ) ) {
+ if ( isTransient ) {
+ source.setReadOnly( event.getObject(), source.isDefaultReadOnly() );
+ }
+ return;
+ }
final Object object = source.getPersistenceContext().unproxyAndReassociate( event.getObject() );
@@ -143,6 +149,9 @@
String previousFetchProfile = source.getFetchProfile();
source.setFetchProfile("refresh");
Object result = persister.load( id, object, event.getLockOptions(), source );
+ // Keep the same read-only/modifiable setting for the entity that it had before refreshing;
+ // If it was transient, then set it to the default for the source.
+ source.setReadOnly( result, ( e == null ? source.isDefaultReadOnly() : e.isReadOnly() ) );
source.setFetchProfile(previousFetchProfile);
UnresolvableObjectException.throwIfNull( result, id, persister.getEntityName() );
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlyProxyTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlyProxyTest.java 2010-01-27 08:00:27 UTC (rev 18642)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlyProxyTest.java 2010-01-27 09:26:42 UTC (rev 18643)
@@ -840,6 +840,95 @@
s.close();
}
+ public void testReadOnlyRefresh() {
+
+ Session s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ DataPoint dp = new DataPoint();
+ dp.setDescription( "original" );
+ dp.setX( new BigDecimal(0.1d).setScale(19, BigDecimal.ROUND_DOWN) );
+ dp.setY( new BigDecimal( Math.cos( dp.getX().doubleValue() ) ).setScale(19, BigDecimal.ROUND_DOWN) );
+ s.save(dp);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ t = s.beginTransaction();
+ dp = ( DataPoint ) s.load( DataPoint.class, dp.getId() );
+ s.setReadOnly( dp, true );
+ assertFalse( Hibernate.isInitialized( dp ) );
+ s.refresh( dp );
+ assertFalse( Hibernate.isInitialized( dp ) );
+ assertEquals( "original", dp.getDescription() );
+ assertTrue( Hibernate.isInitialized( dp ) );
+ dp.setDescription( "changed" );
+ assertEquals( "changed", dp.getDescription() );
+ assertTrue( s.isReadOnly( dp ) );
+ assertTrue( s.isReadOnly( ( ( HibernateProxy ) dp ).getHibernateLazyInitializer().getImplementation() ) );
+ s.refresh( dp );
+ assertEquals( "original", dp.getDescription() );
+ dp.setDescription( "changed" );
+ assertEquals( "changed", dp.getDescription() );
+ assertTrue( s.isReadOnly( dp ) );
+ assertTrue( s.isReadOnly( ( ( HibernateProxy ) dp ).getHibernateLazyInitializer().getImplementation() ) );
+ t.commit();
+
+ s.clear();
+ t = s.beginTransaction();
+ dp = ( DataPoint ) s.get( DataPoint.class, dp.getId() );
+ assertEquals( "original", dp.getDescription() );
+ s.delete( dp );
+ t.commit();
+ s.close();
+
+ }
+
+ public void testReadOnlyRefreshDetached() {
+
+ Session s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ DataPoint dp = new DataPoint();
+ dp.setDescription( "original" );
+ dp.setX( new BigDecimal(0.1d).setScale(19, BigDecimal.ROUND_DOWN) );
+ dp.setY( new BigDecimal( Math.cos( dp.getX().doubleValue() ) ).setScale(19, BigDecimal.ROUND_DOWN) );
+ s.save(dp);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ t = s.beginTransaction();
+ dp = ( DataPoint ) s.load( DataPoint.class, dp.getId() );
+ assertFalse( Hibernate.isInitialized( dp ) );
+ assertFalse( s.isReadOnly( dp ) );
+ s.setReadOnly( dp, true );
+ assertTrue( s.isReadOnly( dp ) );
+ s.evict( dp );
+ s.refresh( dp );
+ assertFalse( Hibernate.isInitialized( dp ) );
+ assertFalse( s.isReadOnly( dp ) );
+ dp.setDescription( "changed" );
+ assertEquals( "changed", dp.getDescription() );
+ assertTrue( Hibernate.isInitialized( dp ) );
+ s.setReadOnly( dp, true );
+ s.evict( dp );
+ s.refresh( dp );
+ assertEquals( "original", dp.getDescription() );
+ assertFalse( s.isReadOnly( dp ) );
+ t.commit();
+
+ s.clear();
+ t = s.beginTransaction();
+ dp = ( DataPoint ) s.get( DataPoint.class, dp.getId() );
+ assertEquals( "original", dp.getDescription() );
+ s.delete( dp );
+ t.commit();
+ s.close();
+ }
+
public void testReadOnlyProxyMergeDetachedProxyWithChange() {
DataPoint dpOrig = createDataPoint( CacheMode.IGNORE );
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlySessionLazyNonLazyTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlySessionLazyNonLazyTest.java 2010-01-27 08:00:27 UTC (rev 18642)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlySessionLazyNonLazyTest.java 2010-01-27 09:26:42 UTC (rev 18643)
@@ -124,7 +124,7 @@
c = ( Container ) s.get( Container.class, cOrig.getId() );
assertSame( cOrig, c );
checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
- //s.refresh( cOrig );
+ s.refresh( cOrig );
assertSame( cOrig, c );
checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
s.evict( cOrig );
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlySessionTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlySessionTest.java 2010-01-27 08:00:27 UTC (rev 18642)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlySessionTest.java 2010-01-27 09:26:42 UTC (rev 18643)
@@ -40,6 +40,7 @@
import org.hibernate.cfg.Environment;
import org.hibernate.junit.functional.FunctionalTestCase;
import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+import org.hibernate.proxy.HibernateProxy;
/**
*
@@ -183,7 +184,7 @@
s.close();
}
- public void testReadOnlyRefreshFailureExpected() {
+ public void testReadOnlyRefresh() {
Session s = openSession();
s.setCacheMode(CacheMode.IGNORE);
@@ -201,11 +202,18 @@
s.setDefaultReadOnly( true );
t = s.beginTransaction();
dp = ( DataPoint ) s.get( DataPoint.class, dp.getId() );
+ assertTrue( s.isReadOnly( dp ) );
assertEquals( "original", dp.getDescription() );
dp.setDescription( "changed" );
assertEquals( "changed", dp.getDescription() );
+ s.refresh( dp );
+ assertTrue( s.isReadOnly( dp ) );
+ assertEquals( "original", dp.getDescription() );
+ dp.setDescription( "changed" );
+ assertEquals( "changed", dp.getDescription() );
s.setDefaultReadOnly( false );
s.refresh( dp );
+ assertTrue( s.isReadOnly( dp ) );
assertEquals( "original", dp.getDescription() );
dp.setDescription( "changed" );
assertEquals( "changed", dp.getDescription() );
@@ -218,9 +226,171 @@
s.delete( dp );
t.commit();
s.close();
+ }
+ public void testReadOnlyRefreshDetached() {
+
+ Session s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ DataPoint dp = new DataPoint();
+ dp.setDescription( "original" );
+ dp.setX( new BigDecimal(0.1d).setScale(19, BigDecimal.ROUND_DOWN) );
+ dp.setY( new BigDecimal( Math.cos( dp.getX().doubleValue() ) ).setScale(19, BigDecimal.ROUND_DOWN) );
+ s.save(dp);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ t = s.beginTransaction();
+ s.setDefaultReadOnly( false );
+ dp.setDescription( "changed" );
+ assertEquals( "changed", dp.getDescription() );
+ s.refresh( dp );
+ assertEquals( "original", dp.getDescription() );
+ assertFalse( s.isReadOnly( dp ) );
+ dp.setDescription( "changed" );
+ assertEquals( "changed", dp.getDescription() );
+ s.evict( dp );
+ s.refresh( dp );
+ assertEquals( "original", dp.getDescription() );
+ assertFalse( s.isReadOnly( dp ) );
+ dp.setDescription( "changed" );
+ assertEquals( "changed", dp.getDescription() );
+ s.setDefaultReadOnly( true );
+ s.evict( dp );
+ s.refresh( dp );
+ assertEquals( "original", dp.getDescription() );
+ assertTrue( s.isReadOnly( dp ) );
+ dp.setDescription( "changed" );
+ t.commit();
+
+ s.clear();
+ t = s.beginTransaction();
+ dp = ( DataPoint ) s.get( DataPoint.class, dp.getId() );
+ assertEquals( "original", dp.getDescription() );
+ s.delete( dp );
+ t.commit();
+ s.close();
}
+ public void testReadOnlyProxyRefresh() {
+
+ Session s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ DataPoint dp = new DataPoint();
+ dp.setDescription( "original" );
+ dp.setX( new BigDecimal(0.1d).setScale(19, BigDecimal.ROUND_DOWN) );
+ dp.setY( new BigDecimal( Math.cos( dp.getX().doubleValue() ) ).setScale(19, BigDecimal.ROUND_DOWN) );
+ s.save(dp);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ t = s.beginTransaction();
+ s.setDefaultReadOnly( true );
+ dp = ( DataPoint ) s.load( DataPoint.class, dp.getId() );
+ assertTrue( s.isReadOnly( dp ) );
+ assertFalse( Hibernate.isInitialized( dp ) );
+ s.refresh( dp );
+ assertFalse( Hibernate.isInitialized( dp ) );
+ assertTrue( s.isReadOnly( dp ) );
+ s.setDefaultReadOnly( false );
+ s.refresh( dp );
+ assertFalse( Hibernate.isInitialized( dp ) );
+ assertTrue( s.isReadOnly( dp ) );
+ assertEquals( "original", dp.getDescription() );
+ assertTrue( Hibernate.isInitialized( dp ) );
+ dp.setDescription( "changed" );
+ assertEquals( "changed", dp.getDescription() );
+ assertTrue( s.isReadOnly( dp ) );
+ assertTrue( s.isReadOnly( ( ( HibernateProxy ) dp ).getHibernateLazyInitializer().getImplementation() ) );
+ s.refresh( dp );
+ assertEquals( "original", dp.getDescription() );
+ assertTrue( s.isReadOnly( dp ) );
+ assertTrue( s.isReadOnly( ( ( HibernateProxy ) dp ).getHibernateLazyInitializer().getImplementation() ) );
+ s.setDefaultReadOnly( true );
+ dp.setDescription( "changed" );
+ assertEquals( "changed", dp.getDescription() );
+ s.refresh( dp );
+ assertTrue( s.isReadOnly( dp ) );
+ assertTrue( s.isReadOnly( ( ( HibernateProxy ) dp ).getHibernateLazyInitializer().getImplementation() ) );
+ assertEquals( "original", dp.getDescription() );
+ dp.setDescription( "changed" );
+ t.commit();
+
+ s.clear();
+ t = s.beginTransaction();
+ dp = ( DataPoint ) s.get( DataPoint.class, dp.getId() );
+ assertEquals( "original", dp.getDescription() );
+ s.delete( dp );
+ t.commit();
+ s.close();
+
+ }
+
+ public void testReadOnlyProxyRefreshDetached() {
+
+ Session s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ DataPoint dp = new DataPoint();
+ dp.setDescription( "original" );
+ dp.setX( new BigDecimal(0.1d).setScale(19, BigDecimal.ROUND_DOWN) );
+ dp.setY( new BigDecimal( Math.cos( dp.getX().doubleValue() ) ).setScale(19, BigDecimal.ROUND_DOWN) );
+ s.save(dp);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ t = s.beginTransaction();
+ s.setDefaultReadOnly( true );
+ dp = ( DataPoint ) s.load( DataPoint.class, dp.getId() );
+ assertFalse( Hibernate.isInitialized( dp ) );
+ assertTrue( s.isReadOnly( dp ) );
+ s.evict( dp );
+ s.refresh( dp );
+ assertFalse( Hibernate.isInitialized( dp ) );
+ s.setDefaultReadOnly( false );
+ assertTrue( s.isReadOnly( dp ) );
+ s.evict( dp );
+ s.refresh( dp );
+ assertFalse( Hibernate.isInitialized( dp ) );
+ assertFalse( s.isReadOnly( dp ) );
+ assertFalse( s.isReadOnly( ( ( HibernateProxy ) dp ).getHibernateLazyInitializer().getImplementation() ) );
+ dp.setDescription( "changed" );
+ assertEquals( "changed", dp.getDescription() );
+ assertTrue( Hibernate.isInitialized( dp ) );
+ s.evict( dp );
+ s.refresh( dp );
+ assertEquals( "original", dp.getDescription() );
+ assertFalse( s.isReadOnly( dp ) );
+ assertFalse( s.isReadOnly( ( ( HibernateProxy ) dp ).getHibernateLazyInitializer().getImplementation() ) );
+ dp.setDescription( "changed" );
+ assertEquals( "changed", dp.getDescription() );
+ s.setDefaultReadOnly( true );
+ s.evict( dp );
+ s.refresh( dp );
+ assertEquals( "original", dp.getDescription() );
+ assertTrue( s.isReadOnly( dp ) );
+ assertTrue( s.isReadOnly( ( ( HibernateProxy ) dp ).getHibernateLazyInitializer().getImplementation() ) );
+ dp.setDescription( "changed" );
+ assertEquals( "changed", dp.getDescription() );
+ t.commit();
+
+ s.clear();
+ t = s.beginTransaction();
+ dp = ( DataPoint ) s.get( DataPoint.class, dp.getId() );
+ assertEquals( "original", dp.getDescription() );
+ s.delete( dp );
+ t.commit();
+ s.close();
+ }
+
public void testReadOnlyDelete() {
Session s = openSession();
@@ -453,4 +623,56 @@
s.close();
}
+
+ public void testMergeWithReadOnlyProxy() {
+
+ Session s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ DataPoint dp = new DataPoint();
+ dp.setX( new BigDecimal(0.1d).setScale(19, BigDecimal.ROUND_DOWN) );
+ dp.setY( new BigDecimal( Math.cos( dp.getX().doubleValue() ) ).setScale(19, BigDecimal.ROUND_DOWN) );
+ s.save(dp);
+ t.commit();
+ s.close();
+
+ dp.setDescription( "description" );
+
+ s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ t = s.beginTransaction();
+ s.setDefaultReadOnly( true );
+ DataPoint dpProxy = ( DataPoint ) s.load( DataPoint.class, new Long( dp.getId() ) );
+ assertTrue( s.isReadOnly( dpProxy ) );
+ assertFalse( Hibernate.isInitialized( dpProxy ) );
+ s.evict( dpProxy );
+ dpProxy = ( DataPoint ) s.merge( dpProxy );
+ assertTrue( s.isReadOnly( dpProxy ) );
+ assertFalse( Hibernate.isInitialized( dpProxy ) );
+ dpProxy = ( DataPoint ) s.merge( dp );
+ assertTrue( s.isReadOnly( dpProxy ) );
+ assertTrue( Hibernate.isInitialized( dpProxy ) );
+ assertEquals( "description", dpProxy.getDescription() );
+ s.evict( dpProxy );
+ dpProxy = ( DataPoint ) s.merge( dpProxy );
+ assertTrue( s.isReadOnly( dpProxy ) );
+ assertTrue( Hibernate.isInitialized( dpProxy ) );
+ assertEquals( "description", dpProxy.getDescription() );
+ dpProxy.setDescription( null );
+ dpProxy = ( DataPoint ) s.merge( dp );
+ assertTrue( s.isReadOnly( dpProxy ) );
+ assertTrue( Hibernate.isInitialized( dpProxy ) );
+ assertEquals( "description", dpProxy.getDescription() );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ dp = ( DataPoint ) s.get( DataPoint.class, new Long( dp.getId() ) );
+ assertNull( dp.getDescription() );
+ s.delete( dp );
+ t.commit();
+ s.close();
+
+ }
}
\ No newline at end of file
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlyTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlyTest.java 2010-01-27 08:00:27 UTC (rev 18642)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlyTest.java 2010-01-27 09:26:42 UTC (rev 18643)
@@ -169,7 +169,7 @@
}
- public void testReadOnlyRefreshFailureExpected() {
+ public void testReadOnlyRefresh() {
Session s = openSession();
s.setCacheMode(CacheMode.IGNORE);
@@ -206,6 +206,45 @@
}
+ public void testReadOnlyRefreshDetached() {
+
+ Session s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ DataPoint dp = new DataPoint();
+ dp.setDescription( "original" );
+ dp.setX( new BigDecimal(0.1d).setScale(19, BigDecimal.ROUND_DOWN) );
+ dp.setY( new BigDecimal( Math.cos( dp.getX().doubleValue() ) ).setScale(19, BigDecimal.ROUND_DOWN) );
+ s.save(dp);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ t = s.beginTransaction();
+ dp.setDescription( "changed" );
+ assertEquals( "changed", dp.getDescription() );
+ s.refresh( dp );
+ assertEquals( "original", dp.getDescription() );
+ assertFalse( s.isReadOnly( dp ) );
+ s.setReadOnly( dp, true );
+ dp.setDescription( "changed" );
+ assertEquals( "changed", dp.getDescription() );
+ s.evict( dp );
+ s.refresh( dp );
+ assertEquals( "original", dp.getDescription() );
+ assertFalse( s.isReadOnly( dp ) );
+ t.commit();
+
+ s.clear();
+ t = s.beginTransaction();
+ dp = ( DataPoint ) s.get( DataPoint.class, dp.getId() );
+ assertEquals( "original", dp.getDescription() );
+ s.delete( dp );
+ t.commit();
+ s.close();
+ }
+
public void testReadOnlyDelete() {
Session s = openSession();
15 years, 1 month
Hibernate SVN: r18642 - in core/trunk: annotations/src/test/java/org/hibernate/test/annotations and 4 other directories.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2010-01-27 03:00:27 -0500 (Wed, 27 Jan 2010)
New Revision: 18642
Added:
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/id/generationmappings/
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/id/generationmappings/AutoEntity.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/id/generationmappings/CompleteSequenceEntity.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/id/generationmappings/MinimalSequenceEntity.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/id/generationmappings/MinimalTableEntity.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/id/generationmappings/NewGeneratorMappingsTest.java
Modified:
core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationBinder.java
core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationConfiguration.java
core/trunk/annotations/src/main/java/org/hibernate/cfg/ExtendedMappings.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/TestCase.java
core/trunk/annotations/src/test/resources/hibernate.properties
core/trunk/core/src/main/java/org/hibernate/id/enhanced/DatabaseStructure.java
core/trunk/core/src/main/java/org/hibernate/id/enhanced/SequenceStructure.java
core/trunk/core/src/main/java/org/hibernate/id/enhanced/TableStructure.java
Log:
HHH-4690 - Consider adding a flag for legacy/new generators
Modified: core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationBinder.java
===================================================================
--- core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationBinder.java 2010-01-27 06:36:55 UTC (rev 18641)
+++ core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationBinder.java 2010-01-27 08:00:27 UTC (rev 18642)
@@ -146,6 +146,7 @@
import org.hibernate.id.PersistentIdentifierGenerator;
import org.hibernate.id.SequenceHiLoGenerator;
import org.hibernate.id.TableHiLoGenerator;
+import org.hibernate.id.enhanced.SequenceStyleGenerator;
import org.hibernate.mapping.Any;
import org.hibernate.mapping.Component;
import org.hibernate.mapping.DependantValue;
@@ -348,7 +349,7 @@
}
}
- private static IdGenerator buildIdGenerator(java.lang.annotation.Annotation ann, Mappings mappings) {
+ private static IdGenerator buildIdGenerator(java.lang.annotation.Annotation ann, ExtendedMappings mappings) {
IdGenerator idGen = new IdGenerator();
if ( mappings.getSchemaName() != null ) {
idGen.addParam( PersistentIdentifierGenerator.SCHEMA, mappings.getSchemaName() );
@@ -356,54 +357,106 @@
if ( mappings.getCatalogName() != null ) {
idGen.addParam( PersistentIdentifierGenerator.CATALOG, mappings.getCatalogName() );
}
+ final boolean useNewGeneratorMappings = mappings.useNewGeneratorMappings();
if ( ann == null ) {
idGen = null;
}
else if ( ann instanceof TableGenerator ) {
TableGenerator tabGen = (TableGenerator) ann;
idGen.setName( tabGen.name() );
- idGen.setIdentifierGeneratorStrategy( MultipleHiLoPerTableGenerator.class.getName() );
+ if ( useNewGeneratorMappings ) {
+ idGen.setIdentifierGeneratorStrategy( org.hibernate.id.enhanced.TableGenerator.class.getName() );
+ idGen.addParam( org.hibernate.id.enhanced.TableGenerator.CONFIG_PREFER_SEGMENT_PER_ENTITY, "true" );
- if ( !BinderHelper.isDefault( tabGen.table() ) ) {
- idGen.addParam( MultipleHiLoPerTableGenerator.ID_TABLE, tabGen.table() );
+ if ( !BinderHelper.isDefault( tabGen.catalog() ) ) {
+ idGen.addParam( org.hibernate.id.enhanced.TableGenerator.CATALOG, tabGen.catalog() );
+ }
+ if ( !BinderHelper.isDefault( tabGen.schema() ) ) {
+ idGen.addParam( org.hibernate.id.enhanced.TableGenerator.SCHEMA, tabGen.schema() );
+ }
+ if ( !BinderHelper.isDefault( tabGen.table() ) ) {
+ idGen.addParam( org.hibernate.id.enhanced.TableGenerator.TABLE_PARAM, tabGen.table() );
+ }
+ if ( !BinderHelper.isDefault( tabGen.pkColumnName() ) ) {
+ idGen.addParam( org.hibernate.id.enhanced.TableGenerator.SEGMENT_COLUMN_PARAM, tabGen.pkColumnName() );
+ }
+ if ( !BinderHelper.isDefault( tabGen.pkColumnValue() ) ) {
+ idGen.addParam( org.hibernate.id.enhanced.TableGenerator.SEGMENT_VALUE_PARAM, tabGen.pkColumnValue() );
+ }
+ if ( !BinderHelper.isDefault( tabGen.valueColumnName() ) ) {
+ idGen.addParam( org.hibernate.id.enhanced.TableGenerator.VALUE_COLUMN_PARAM, tabGen.valueColumnName() );
+ }
+ idGen.addParam( org.hibernate.id.enhanced.TableGenerator.INCREMENT_PARAM, String.valueOf( tabGen.allocationSize() ) );
+ idGen.addParam( org.hibernate.id.enhanced.TableGenerator.INITIAL_PARAM, String.valueOf( tabGen.initialValue() ) );
+ if ( tabGen.uniqueConstraints() != null && tabGen.uniqueConstraints().length > 0 ) {
+ log.warn( "Ignoring unique constraints specified on table generator [{}]", tabGen.name() );
+ }
}
- if ( !BinderHelper.isDefault( tabGen.catalog() ) ) {
- idGen.addParam( MultipleHiLoPerTableGenerator.CATALOG, tabGen.catalog() );
- }
- if ( !BinderHelper.isDefault( tabGen.schema() ) ) {
- idGen.addParam( MultipleHiLoPerTableGenerator.SCHEMA, tabGen.schema() );
- }
- //FIXME implements uniqueconstrains
+ else {
+ idGen.setIdentifierGeneratorStrategy( MultipleHiLoPerTableGenerator.class.getName() );
- if ( !BinderHelper.isDefault( tabGen.pkColumnName() ) ) {
- idGen.addParam( MultipleHiLoPerTableGenerator.PK_COLUMN_NAME, tabGen.pkColumnName() );
+ if ( !BinderHelper.isDefault( tabGen.table() ) ) {
+ idGen.addParam( MultipleHiLoPerTableGenerator.ID_TABLE, tabGen.table() );
+ }
+ if ( !BinderHelper.isDefault( tabGen.catalog() ) ) {
+ idGen.addParam( MultipleHiLoPerTableGenerator.CATALOG, tabGen.catalog() );
+ }
+ if ( !BinderHelper.isDefault( tabGen.schema() ) ) {
+ idGen.addParam( MultipleHiLoPerTableGenerator.SCHEMA, tabGen.schema() );
+ }
+ //FIXME implement uniqueconstrains
+ if ( tabGen.uniqueConstraints() != null && tabGen.uniqueConstraints().length > 0 ) {
+ log.warn( "Ignoring unique constraints specified on table generator [{}]", tabGen.name() );
+ }
+
+ if ( !BinderHelper.isDefault( tabGen.pkColumnName() ) ) {
+ idGen.addParam( MultipleHiLoPerTableGenerator.PK_COLUMN_NAME, tabGen.pkColumnName() );
+ }
+ if ( !BinderHelper.isDefault( tabGen.valueColumnName() ) ) {
+ idGen.addParam( MultipleHiLoPerTableGenerator.VALUE_COLUMN_NAME, tabGen.valueColumnName() );
+ }
+ if ( !BinderHelper.isDefault( tabGen.pkColumnValue() ) ) {
+ idGen.addParam( MultipleHiLoPerTableGenerator.PK_VALUE_NAME, tabGen.pkColumnValue() );
+ }
+ idGen.addParam( TableHiLoGenerator.MAX_LO, String.valueOf( tabGen.allocationSize() - 1 ) );
}
- if ( !BinderHelper.isDefault( tabGen.valueColumnName() ) ) {
- idGen.addParam( MultipleHiLoPerTableGenerator.VALUE_COLUMN_NAME, tabGen.valueColumnName() );
- }
- if ( !BinderHelper.isDefault( tabGen.pkColumnValue() ) ) {
- idGen.addParam( MultipleHiLoPerTableGenerator.PK_VALUE_NAME, tabGen.pkColumnValue() );
- }
- idGen.addParam( TableHiLoGenerator.MAX_LO, String.valueOf( tabGen.allocationSize() - 1 ) );
log.trace( "Add table generator with name: {}", idGen.getName() );
}
else if ( ann instanceof SequenceGenerator ) {
SequenceGenerator seqGen = (SequenceGenerator) ann;
idGen.setName( seqGen.name() );
- idGen.setIdentifierGeneratorStrategy( "seqhilo" );
+ if ( useNewGeneratorMappings ) {
+ idGen.setIdentifierGeneratorStrategy( SequenceStyleGenerator.class.getName() );
- if ( !BinderHelper.isDefault( seqGen.sequenceName() ) ) {
- idGen.addParam( org.hibernate.id.SequenceGenerator.SEQUENCE, seqGen.sequenceName() );
+ if ( !BinderHelper.isDefault( seqGen.catalog() ) ) {
+ idGen.addParam( SequenceStyleGenerator.CATALOG, seqGen.catalog() );
+ }
+ if ( !BinderHelper.isDefault( seqGen.schema() ) ) {
+ idGen.addParam( SequenceStyleGenerator.SCHEMA, seqGen.schema() );
+ }
+ if ( !BinderHelper.isDefault( seqGen.sequenceName() ) ) {
+ idGen.addParam( SequenceStyleGenerator.SEQUENCE_PARAM, seqGen.sequenceName() );
+ }
+ idGen.addParam( SequenceStyleGenerator.INCREMENT_PARAM, String.valueOf( seqGen.allocationSize() ) );
+ idGen.addParam( SequenceStyleGenerator.INITIAL_PARAM, String.valueOf( seqGen.initialValue() ) );
}
- //FIXME: work on initialValue() through SequenceGenerator.PARAMETERS
- // steve : or just use o.h.id.enhanced.SequenceStyleGenerator
- if ( seqGen.initialValue() != 1 ) {
- log.warn(
- "Hibernate does not support SequenceGenerator.initialValue()"
- );
+ else {
+ idGen.setIdentifierGeneratorStrategy( "seqhilo" );
+
+ if ( !BinderHelper.isDefault( seqGen.sequenceName() ) ) {
+ idGen.addParam( org.hibernate.id.SequenceGenerator.SEQUENCE, seqGen.sequenceName() );
+ }
+ //FIXME: work on initialValue() through SequenceGenerator.PARAMETERS
+ // steve : or just use o.h.id.enhanced.SequenceStyleGenerator
+ if ( seqGen.initialValue() != 1 ) {
+ log.warn(
+ "Hibernate does not support SequenceGenerator.initialValue() unless '{}' set",
+ AnnotationConfiguration.USE_NEW_ID_GENERATOR_MAPPINGS
+ );
+ }
+ idGen.addParam( SequenceHiLoGenerator.MAX_LO, String.valueOf( seqGen.allocationSize() - 1 ) );
+ log.trace( "Add sequence generator with name: {}", idGen.getName() );
}
- idGen.addParam( SequenceHiLoGenerator.MAX_LO, String.valueOf( seqGen.allocationSize() - 1 ) );
- log.trace( "Add sequence generator with name: {}", idGen.getName() );
}
else if ( ann instanceof GenericGenerator ) {
GenericGenerator genGen = (GenericGenerator) ann;
@@ -1804,7 +1857,7 @@
GeneratedValue generatedValue = property.getAnnotation( GeneratedValue.class );
String generatorType = generatedValue != null ?
- generatorType( generatedValue.strategy() ) :
+ generatorType( generatedValue.strategy(), mappings ) :
"assigned";
String generatorName = generatedValue != null ?
generatedValue.generator() :
@@ -2032,7 +2085,7 @@
localGenerators.putAll( buildLocalGenerators( property, mappings ) );
GeneratedValue generatedValue = property.getAnnotation( GeneratedValue.class );
- String generatorType = generatedValue != null ? generatorType( generatedValue.strategy() ) : "assigned";
+ String generatorType = generatedValue != null ? generatorType( generatedValue.strategy(), mappings ) : "assigned";
String generator = generatedValue != null ? generatedValue.generator() : BinderHelper.ANNOTATION_STRING_DEFAULT;
BinderHelper.makeIdGenerator( (SimpleValue) comp.getProperty(property.getName()).getValue(), generatorType, generator, mappings, localGenerators);
@@ -2395,16 +2448,23 @@
propertyHolder.addProperty( prop, columns, inferredData.getDeclaringClass() );
}
- private static String generatorType(GenerationType generatorEnum) {
+ private static String generatorType(GenerationType generatorEnum, ExtendedMappings mappings) {
+ boolean useNewGeneratorMappings = mappings.useNewGeneratorMappings();
switch ( generatorEnum ) {
case IDENTITY:
return "identity";
case AUTO:
- return "native";
+ return useNewGeneratorMappings
+ ? org.hibernate.id.enhanced.SequenceStyleGenerator.class.getName()
+ : "native";
case TABLE:
- return MultipleHiLoPerTableGenerator.class.getName();
+ return useNewGeneratorMappings
+ ? org.hibernate.id.enhanced.TableGenerator.class.getName()
+ : MultipleHiLoPerTableGenerator.class.getName();
case SEQUENCE:
- return "seqhilo";
+ return useNewGeneratorMappings
+ ? org.hibernate.id.enhanced.SequenceStyleGenerator.class.getName()
+ : "seqhilo";
}
throw new AssertionFailure( "Unknown GeneratorType: " + generatorEnum );
}
@@ -2509,7 +2569,7 @@
}
}
- private static HashMap<String, IdGenerator> buildLocalGenerators(XAnnotatedElement annElt, Mappings mappings) {
+ private static HashMap<String, IdGenerator> buildLocalGenerators(XAnnotatedElement annElt, ExtendedMappings mappings) {
HashMap<String, IdGenerator> generators = new HashMap<String, IdGenerator>();
TableGenerator tabGen = annElt.getAnnotation( TableGenerator.class );
SequenceGenerator seqGen = annElt.getAnnotation( SequenceGenerator.class );
Modified: core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationConfiguration.java
===================================================================
--- core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationConfiguration.java 2010-01-27 06:36:55 UTC (rev 18641)
+++ core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationConfiguration.java 2010-01-27 08:00:27 UTC (rev 18642)
@@ -108,11 +108,17 @@
/**
* Setting used to give the name of the default {@link org.hibernate.annotations.CacheConcurrencyStrategy}
* to use when either {@link javax.persistence.Cacheable @Cacheable} or
- * {@link Cache @Cache} is used. {@link Cache @Cache(strategy=".."} is used to override.
+ * {@link Cache @Cache} is used. {@link Cache @Cache(strategy="..")} is used to override.
*/
public static final String DEFAULT_CACHE_CONCURRENCY_STRATEGY = "org.hibernate.cache.default_cache_concurrency_strategy";
/**
+ * Setting which indicates the Hibernate {@link org.hibernate.id.IdentifierGenerator} name to use as the mapping
+ * for {@link javax.persistence.GenerationType#AUTO @GeneratedValue(strategy=AUTO...)}
+ */
+ public static final String USE_NEW_ID_GENERATOR_MAPPINGS = "org.hibernate.id.new_generator_mappings";
+
+ /**
* Class name of the class needed to enable Search.
*/
private static final String SEARCH_STARTUP_CLASS = "org.hibernate.search.event.EventListenerRegister";
@@ -1286,6 +1292,17 @@
map.put( property.getProperty().getAnnotation( MapsId.class ).value(), property );
}
+ private Boolean useNewGeneratorMappings;
+
+ @SuppressWarnings({ "UnnecessaryUnboxing" })
+ public boolean useNewGeneratorMappings() {
+ if ( useNewGeneratorMappings == null ) {
+ final String booleanName = getConfigurationProperties().getProperty( USE_NEW_ID_GENERATOR_MAPPINGS );
+ useNewGeneratorMappings = Boolean.valueOf( booleanName );
+ }
+ return useNewGeneratorMappings.booleanValue();
+ }
+
public IdGenerator getGenerator(String name) {
return getGenerator( name, null );
}
Modified: core/trunk/annotations/src/main/java/org/hibernate/cfg/ExtendedMappings.java
===================================================================
--- core/trunk/annotations/src/main/java/org/hibernate/cfg/ExtendedMappings.java 2010-01-27 06:36:55 UTC (rev 18641)
+++ core/trunk/annotations/src/main/java/org/hibernate/cfg/ExtendedMappings.java 2010-01-27 08:00:27 UTC (rev 18642)
@@ -180,4 +180,12 @@
public PropertyData getPropertyAnnotatedWithMapsId(XClass entityType, String propertyName);
public void addPropertyAnnotatedWithMapsId(XClass entityType, PropertyData property);
+
+ /**
+ * Should we use the new generator strategy mappings. This is controlled by the
+ * {@link AnnotationConfiguration#USE_NEW_ID_GENERATOR_MAPPINGS} setting.
+ *
+ * @return True if the new generators should be used, false otherwise.
+ */
+ public boolean useNewGeneratorMappings();
}
\ No newline at end of file
Modified: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/TestCase.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/TestCase.java 2010-01-27 06:36:55 UTC (rev 18641)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/TestCase.java 2010-01-27 08:00:27 UTC (rev 18642)
@@ -32,6 +32,7 @@
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Environment;
+import org.hibernate.engine.SessionFactoryImplementor;
/**
* A base class for all annotation tests.
@@ -83,6 +84,10 @@
return sessions;
}
+ protected SessionFactoryImplementor sfi() {
+ return (SessionFactoryImplementor) getSessions();
+ }
+
@Override
protected void buildConfiguration() throws Exception {
if ( getSessions() != null ) {
Added: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/id/generationmappings/AutoEntity.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/id/generationmappings/AutoEntity.java (rev 0)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/id/generationmappings/AutoEntity.java 2010-01-27 08:00:27 UTC (rev 18642)
@@ -0,0 +1,48 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2010, Red Hat Inc. or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.test.annotations.id.generationmappings;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+
+/**
+ * TODO : javadoc
+ *
+ * @author Steve Ebersole
+ */
+@Entity
+public class AutoEntity {
+ private Long id;
+
+ @Id @GeneratedValue
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long long1) {
+ id = long1;
+ }
+}
Added: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/id/generationmappings/CompleteSequenceEntity.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/id/generationmappings/CompleteSequenceEntity.java (rev 0)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/id/generationmappings/CompleteSequenceEntity.java 2010-01-27 08:00:27 UTC (rev 18642)
@@ -0,0 +1,58 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2010, Red Hat Inc. or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.test.annotations.id.generationmappings;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+
+/**
+ * TODO : javadoc
+ *
+ * @author Steve Ebersole
+ */
+@Entity
+public class CompleteSequenceEntity {
+ public static final String SEQ_NAME = "some_other_sequence";
+ private Long id;
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "COMPLETE_SEQ")
+ @javax.persistence.SequenceGenerator(
+ name = "COMPLETE_SEQ",
+ sequenceName = SEQ_NAME,
+ initialValue = 1000,
+ allocationSize = 52,
+ catalog = "my_catalog",
+ schema = "my_schema"
+ )
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long long1) {
+ id = long1;
+ }
+}
\ No newline at end of file
Added: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/id/generationmappings/MinimalSequenceEntity.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/id/generationmappings/MinimalSequenceEntity.java (rev 0)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/id/generationmappings/MinimalSequenceEntity.java 2010-01-27 08:00:27 UTC (rev 18642)
@@ -0,0 +1,51 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2010, Red Hat Inc. or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.test.annotations.id.generationmappings;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+
+/**
+ * TODO : javadoc
+ *
+ * @author Steve Ebersole
+ */
+@Entity
+public class MinimalSequenceEntity {
+ public static final String SEQ_NAME = "some_sequence";
+ private Long id;
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "MINIMAL_SEQ")
+ @javax.persistence.SequenceGenerator( name = "MINIMAL_SEQ", sequenceName = SEQ_NAME )
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long long1) {
+ id = long1;
+ }
+}
Added: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/id/generationmappings/MinimalTableEntity.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/id/generationmappings/MinimalTableEntity.java (rev 0)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/id/generationmappings/MinimalTableEntity.java 2010-01-27 08:00:27 UTC (rev 18642)
@@ -0,0 +1,55 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2010, Red Hat Inc. or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.test.annotations.id.generationmappings;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Table;
+import javax.persistence.TableGenerator;
+
+/**
+ * TODO : javadoc
+ *
+ * @author Steve Ebersole
+ */
+@Entity
+@Table( name = "MINIMAL_TBL" )
+public class MinimalTableEntity {
+ public static final String TBL_NAME = "minimal_tbl";
+
+ private Long id;
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.TABLE, generator = "MINIMAL_TBL")
+ @TableGenerator( name = "MINIMAL_TBL", table = TBL_NAME )
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long long1) {
+ id = long1;
+ }
+}
\ No newline at end of file
Added: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/id/generationmappings/NewGeneratorMappingsTest.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/id/generationmappings/NewGeneratorMappingsTest.java (rev 0)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/id/generationmappings/NewGeneratorMappingsTest.java 2010-01-27 08:00:27 UTC (rev 18642)
@@ -0,0 +1,122 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2010, Red Hat Inc. or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.test.annotations.id.generationmappings;
+
+import org.hibernate.cfg.AnnotationConfiguration;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.cfg.Environment;
+import org.hibernate.id.IdentifierGenerator;
+import org.hibernate.id.enhanced.OptimizerFactory;
+import org.hibernate.id.enhanced.SequenceStyleGenerator;
+import org.hibernate.id.enhanced.TableGenerator;
+import org.hibernate.persister.entity.EntityPersister;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * Test mapping the {@link javax.persistence.GenerationType GenerationTypes} to the corresponding
+ * hibernate generators using the new scheme
+ *
+ * @author Steve Ebersole
+ */
+public class NewGeneratorMappingsTest extends TestCase {
+ @Override
+ protected Class<?>[] getAnnotatedClasses() {
+ return new Class[] {
+ MinimalSequenceEntity.class,
+ CompleteSequenceEntity.class,
+ AutoEntity.class,
+ MinimalTableEntity.class
+ };
+ }
+
+ @Override
+ protected void configure(Configuration cfg) {
+ super.configure( cfg );
+ cfg.setProperty( AnnotationConfiguration.USE_NEW_ID_GENERATOR_MAPPINGS, "true" );
+ cfg.setProperty( Environment.HBM2DDL_AUTO, "" );
+ }
+
+ @Override
+ protected boolean recreateSchema() {
+ return false;
+ }
+
+ @Override
+ protected void runSchemaGeneration() {
+ }
+
+ @Override
+ protected void runSchemaDrop() {
+ }
+
+ public void testMinimalSequenceEntity() {
+ final EntityPersister persister = sfi().getEntityPersister( MinimalSequenceEntity.class.getName() );
+ IdentifierGenerator generator = persister.getIdentifierGenerator();
+ assertTrue( SequenceStyleGenerator.class.isInstance( generator ) );
+ SequenceStyleGenerator seqGenerator = (SequenceStyleGenerator) generator;
+ assertEquals( MinimalSequenceEntity.SEQ_NAME, seqGenerator.getDatabaseStructure().getName() );
+ // 1 is the annotation default
+ assertEquals( 1, seqGenerator.getDatabaseStructure().getInitialValue() );
+ // 50 is the annotation default
+ assertEquals( 50, seqGenerator.getDatabaseStructure().getIncrementSize() );
+ assertFalse( OptimizerFactory.NoopOptimizer.class.isInstance( seqGenerator.getOptimizer() ) );
+ }
+
+ public void testCompleteSequenceEntity() {
+ final EntityPersister persister = sfi().getEntityPersister( CompleteSequenceEntity.class.getName() );
+ IdentifierGenerator generator = persister.getIdentifierGenerator();
+ assertTrue( SequenceStyleGenerator.class.isInstance( generator ) );
+ SequenceStyleGenerator seqGenerator = (SequenceStyleGenerator) generator;
+ assertEquals( "my_catalog.my_schema."+CompleteSequenceEntity.SEQ_NAME, seqGenerator.getDatabaseStructure().getName() );
+ assertEquals( 1000, seqGenerator.getDatabaseStructure().getInitialValue() );
+ assertEquals( 52, seqGenerator.getDatabaseStructure().getIncrementSize() );
+ assertFalse( OptimizerFactory.NoopOptimizer.class.isInstance( seqGenerator.getOptimizer() ) );
+ }
+
+ public void testAutoEntity() {
+ final EntityPersister persister = sfi().getEntityPersister( AutoEntity.class.getName() );
+ IdentifierGenerator generator = persister.getIdentifierGenerator();
+ assertTrue( SequenceStyleGenerator.class.isInstance( generator ) );
+ SequenceStyleGenerator seqGenerator = (SequenceStyleGenerator) generator;
+ assertEquals( SequenceStyleGenerator.DEF_SEQUENCE_NAME, seqGenerator.getDatabaseStructure().getName() );
+ assertEquals( SequenceStyleGenerator.DEFAULT_INITIAL_VALUE, seqGenerator.getDatabaseStructure().getInitialValue() );
+ assertEquals( SequenceStyleGenerator.DEFAULT_INCREMENT_SIZE, seqGenerator.getDatabaseStructure().getIncrementSize() );
+ }
+
+ public void testMinimalTableEntity() {
+ final EntityPersister persister = sfi().getEntityPersister( MinimalTableEntity.class.getName() );
+ IdentifierGenerator generator = persister.getIdentifierGenerator();
+ assertTrue( TableGenerator.class.isInstance( generator ) );
+ TableGenerator tabGenerator = (TableGenerator) generator;
+ assertEquals( MinimalTableEntity.TBL_NAME, tabGenerator.getTableName() );
+ assertEquals( TableGenerator.DEF_SEGMENT_COLUMN, tabGenerator.getSegmentColumnName() );
+ assertEquals( "MINIMAL_TBL", tabGenerator.getSegmentValue() );
+ assertEquals( TableGenerator.DEF_VALUE_COLUMN, tabGenerator.getValueColumnName() );
+ // 0 is the annotation default
+ assertEquals( 0, tabGenerator.getInitialValue() );
+ // 50 is the annotation default
+ assertEquals( 50, tabGenerator.getIncrementSize() );
+ assertTrue( OptimizerFactory.PooledOptimizer.class.isInstance( tabGenerator.getOptimizer() ) );
+ }
+}
Modified: core/trunk/annotations/src/test/resources/hibernate.properties
===================================================================
--- core/trunk/annotations/src/test/resources/hibernate.properties 2010-01-27 06:36:55 UTC (rev 18641)
+++ core/trunk/annotations/src/test/resources/hibernate.properties 2010-01-27 08:00:27 UTC (rev 18642)
@@ -1,18 +1,26 @@
-################################################################################
-# Copyright (c) 2007, Red Hat Middleware, LLC. All rights reserved. #
-# #
-# This copyrighted material is made available to anyone wishing to use, modify,#
-# copy, or redistribute it subject to the terms and conditions of the GNU #
-# Lesser General Public License, v. 2.1. This program is distributed in the #
-# hope that it will be useful, but WITHOUT A WARRANTY; without even the implied#
-# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU #
-# Lesser General Public License for more details. You should have received a #
-# copy of the GNU Lesser General Public License, v.2.1 along with this #
-# distribution; if not, write to the Free Software Foundation, Inc., #
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. #
-# #
-# Red Hat Author(s): Steve Ebersole #
-################################################################################
+#
+# Hibernate, Relational Persistence for Idiomatic Java
+#
+# Copyright (c) 2010, Red Hat Inc. or third-party contributors as
+# indicated by the @author tags or express copyright attribution
+# statements applied by the authors. All third-party contributions are
+# distributed under license by Red Hat Inc.
+#
+# This copyrighted material is made available to anyone wishing to use, modify,
+# copy, or redistribute it subject to the terms and conditions of the GNU
+# Lesser General Public License, as published by the Free Software Foundation.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+# for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with this distribution; if not, write to:
+# Free Software Foundation, Inc.
+# 51 Franklin Street, Fifth Floor
+# Boston, MA 02110-1301 USA
+#
hibernate.dialect ${db.dialect}
hibernate.connection.driver_class ${jdbc.driver}
hibernate.connection.url ${jdbc.url}
Modified: core/trunk/core/src/main/java/org/hibernate/id/enhanced/DatabaseStructure.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/id/enhanced/DatabaseStructure.java 2010-01-27 06:36:55 UTC (rev 18641)
+++ core/trunk/core/src/main/java/org/hibernate/id/enhanced/DatabaseStructure.java 2010-01-27 08:00:27 UTC (rev 18642)
@@ -47,6 +47,12 @@
public int getTimesAccessed();
/**
+ * The configured initial value
+ * @return The configured initial value
+ */
+ public int getInitialValue();
+
+ /**
* The configured increment size
* @return The configured increment size
*/
Modified: core/trunk/core/src/main/java/org/hibernate/id/enhanced/SequenceStructure.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/id/enhanced/SequenceStructure.java 2010-01-27 06:36:55 UTC (rev 18641)
+++ core/trunk/core/src/main/java/org/hibernate/id/enhanced/SequenceStructure.java 2010-01-27 08:00:27 UTC (rev 18642)
@@ -82,6 +82,13 @@
/**
* {@inheritDoc}
*/
+ public int getInitialValue() {
+ return initialValue;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
public AccessCallback buildCallback(final SessionImplementor session) {
return new AccessCallback() {
public long getNextValue() {
Modified: core/trunk/core/src/main/java/org/hibernate/id/enhanced/TableStructure.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/id/enhanced/TableStructure.java 2010-01-27 06:36:55 UTC (rev 18641)
+++ core/trunk/core/src/main/java/org/hibernate/id/enhanced/TableStructure.java 2010-01-27 08:00:27 UTC (rev 18642)
@@ -87,6 +87,13 @@
/**
* {@inheritDoc}
*/
+ public int getInitialValue() {
+ return initialValue;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
public int getIncrementSize() {
return incrementSize;
}
15 years, 1 month
Hibernate SVN: r18641 - in core/trunk: core/src/main/java/org/hibernate/engine and 9 other directories.
by hibernate-commits@lists.jboss.org
Author: gbadner
Date: 2010-01-27 01:36:55 -0500 (Wed, 27 Jan 2010)
New Revision: 18641
Added:
core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/Container.java
core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/Info.java
core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/Owner.java
core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlySessionLazyNonLazyTest.java
core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlySessionTest.java
Modified:
core/trunk/core/src/main/java/org/hibernate/Query.java
core/trunk/core/src/main/java/org/hibernate/Session.java
core/trunk/core/src/main/java/org/hibernate/engine/PersistenceContext.java
core/trunk/core/src/main/java/org/hibernate/engine/QueryParameters.java
core/trunk/core/src/main/java/org/hibernate/engine/StatefulPersistenceContext.java
core/trunk/core/src/main/java/org/hibernate/event/def/DefaultLoadEventListener.java
core/trunk/core/src/main/java/org/hibernate/impl/AbstractQueryImpl.java
core/trunk/core/src/main/java/org/hibernate/impl/SessionImpl.java
core/trunk/core/src/main/java/org/hibernate/impl/StatelessSessionImpl.java
core/trunk/core/src/main/java/org/hibernate/loader/Loader.java
core/trunk/core/src/main/java/org/hibernate/proxy/AbstractLazyInitializer.java
core/trunk/core/src/main/java/org/hibernate/proxy/pojo/cglib/CGLIBLazyInitializer.java
core/trunk/core/src/main/java/org/hibernate/proxy/pojo/cglib/SerializableProxy.java
core/trunk/core/src/main/java/org/hibernate/proxy/pojo/javassist/JavassistLazyInitializer.java
core/trunk/core/src/main/java/org/hibernate/proxy/pojo/javassist/SerializableProxy.java
core/trunk/testsuite/src/test/java/org/hibernate/test/immutable/ImmutableTest.java
core/trunk/testsuite/src/test/java/org/hibernate/test/nonflushedchanges/GetLoadTest.java
core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/DataPoint.hbm.xml
core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/DataPoint.java
core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlyTest.java
Log:
HHH-2501 HHH-4804 : Add default read-only/modifiable setting for session; fix setting for non-lazy associations loaded from Query
Modified: core/trunk/core/src/main/java/org/hibernate/Query.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/Query.java 2010-01-26 21:49:51 UTC (rev 18640)
+++ core/trunk/core/src/main/java/org/hibernate/Query.java 2010-01-27 06:36:55 UTC (rev 18641)
@@ -175,11 +175,46 @@
public Query setFirstResult(int firstResult);
/**
- * Entities retrieved by this query will be loaded in
- * a read-only mode where Hibernate will never dirty-check
- * them or make changes persistent.
+ * Should entities and proxies loaded by this Query be put in read-only mode? If the
+ * read-only/modifiable setting was not initialized, then the default
+ * read-only/modifiable setting for the persistence context is returned instead.
+ * @see Query#setReadOnly(boolean)
+ * @see org.hibernate.engine.PersistenceContext#isDefaultReadOnly()
*
+ * The read-only/modifiable setting has no impact on entities/proxies returned by the
+ * query that existed in the session before the query was executed.
+ *
+ * @return true, entities and proxies loaded by the query will be put in read-only mode
+ * false, entities and proxies loaded by the query will be put in modifiable mode
*/
+ public boolean isReadOnly();
+
+ /**
+ * Set the read-only/modifiable mode for entities and proxies
+ * loaded by this Query. This setting overrides the default setting
+ * for the persistence context.
+ * @see org.hibernate.engine.PersistenceContext#isDefaultReadOnly()
+ *
+ * To set the default read-only/modifiable setting used for
+ * entities and proxies that are loaded into the session:
+ * @see org.hibernate.engine.PersistenceContext#setDefaultReadOnly(boolean)
+ * @see org.hibernate.Session#setDefaultReadOnly(boolean)
+ *
+ * Read-only entities are not dirty-checked and snapshots of persistent
+ * state are not maintained. Read-only entities can be modified, but
+ * changes are not persisted.
+ *
+ * When a proxy is initialized, the loaded entity will have the same
+ * read-only/modifiable setting as the uninitialized
+ * proxy has, regardless of the session's current setting.
+ *
+ * The read-only/modifiable setting has no impact on entities/proxies
+ * returned by the query that existed in the session before the query was executed.
+ *
+ * @return true, entities and proxies loaded by the query will be put in read-only mode
+ * false, entities and proxies loaded by the query will be put in modifiable mode
+ */
+
public Query setReadOnly(boolean readOnly);
/**
Modified: core/trunk/core/src/main/java/org/hibernate/Session.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/Session.java 2010-01-26 21:49:51 UTC (rev 18640)
+++ core/trunk/core/src/main/java/org/hibernate/Session.java 2010-01-27 06:36:55 UTC (rev 18641)
@@ -232,6 +232,44 @@
public boolean isDirty() throws HibernateException;
/**
+ * Will entities and proxies that are loaded into this session be made
+ * read-only by default?
+ *
+ * To determine the read-only/modifiable setting for a particular entity
+ * or proxy:
+ * @see Session#isReadOnly(Object)
+ *
+ * @return true, loaded entities/proxies will be made read-only by default;
+ * false, loaded entities/proxies will be made modifiable by default.
+ */
+ public boolean isDefaultReadOnly();
+
+ /**
+ * Change the default for entities and proxies loaded into this session
+ * from modifiable to read-only mode, or from modifiable to read-only mode.
+ *
+ * Read-only entities are not dirty-checked and snapshots of persistent
+ * state are not maintained. Read-only entities can be modified, but
+ * changes are not persisted.
+ *
+ * When a proxy is initialized, the loaded entity will have the same
+ * read-only/modifiable setting as the uninitialized
+ * proxy has, regardless of the session's current setting.
+ *
+ * To change the read-only/modifiable setting for a particular entity
+ * or proxy that is already in this session:
+ * @see Session#setReadOnly(Object,boolean)
+ *
+ * To override this session's read-only/modifiable setting for entities
+ * and proxies loaded by a Query:
+ * @see Query#setReadOnly(boolean)
+ *
+ * @param readOnly true, the default for loaded entities/proxies is read-only;
+ * false, the default for loaded entities/proxies is modifiable
+ */
+ public void setDefaultReadOnly(boolean readOnly);
+
+ /**
* Return the identifier value of the given entity as associated with this
* session. An exception is thrown if the given entity instance is transient
* or detached in relation to this session.
@@ -842,6 +880,11 @@
/**
* Is the specified entity or proxy read-only?
+ *
+ * To get the default read-only/modifiable setting used for
+ * entities and proxies that are loaded into the session:
+ * @see org.hibernate.Session#isDefaultReadOnly()
+ *
* @param entityOrProxy, an entity or HibernateProxy
* @return true, the entity or proxy is read-only;
* false, the entity or proxy is modifiable.
@@ -850,16 +893,23 @@
/**
* Set an unmodified persistent object to read-only mode, or a read-only
- * object to modifiable mode. In read-only mode, no snapshot is maintained
- * and the instance is never dirty checked.
+ * object to modifiable mode. In read-only mode, no snapshot is maintained,
+ * the instance is never dirty checked, and changes are not persisted.
*
* If the entity or proxy already has the specified read-only/modifiable
* setting, then this method does nothing.
*
+ * To set the default read-only/modifiable setting used for
+ * entities and proxies that are loaded into the session:
+ * @see org.hibernate.Session#setDefaultReadOnly(boolean)
+ *
+ * To override this session's read-only/modifiable setting for entities
+ * and proxies loaded by a Query:
+ * @see Query#setReadOnly(boolean)
+ *
* @param entityOrProxy, an entity or HibernateProxy
* @param readOnly, if true, the entity or proxy is made read-only;
* if false, the entity or proxy is made modifiable.
- * @see Query#setReadOnly(boolean)
*/
public void setReadOnly(Object entityOrProxy, boolean readOnly);
Modified: core/trunk/core/src/main/java/org/hibernate/engine/PersistenceContext.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/engine/PersistenceContext.java 2010-01-26 21:49:51 UTC (rev 18640)
+++ core/trunk/core/src/main/java/org/hibernate/engine/PersistenceContext.java 2010-01-27 06:36:55 UTC (rev 18641)
@@ -477,22 +477,91 @@
public boolean isPropertyNull(EntityKey ownerKey, String propertyName);
/**
+ * Will entities and proxies that are loaded into this persistence
+ * context be made read-only by default?
+ *
+ * To determine the read-only/modifiable setting for a particular entity
+ * or proxy:
+ * @see PersistenceContext#isReadOnly(Object)
+ * @see org.hibernate.Session#isReadOnly(Object)
+ *
+ * @return true, loaded entities/proxies will be made read-only by default;
+ * false, loaded entities/proxies will be made modifiable by default.
+ *
+ * @see org.hibernate.Session#isDefaultReadOnly()
+ */
+ public boolean isDefaultReadOnly();
+
+ /**
+ * Change the default for entities and proxies loaded into this persistence
+ * context from modifiable to read-only mode, or from modifiable to read-only
+ * mode.
+ *
+ * Read-only entities are not dirty-checked and snapshots of persistent
+ * state are not maintained. Read-only entities can be modified, but
+ * changes are not persisted.
+ *
+ * When a proxy is initialized, the loaded entity will have the same
+ * read-only/modifiable setting as the uninitialized
+ * proxy has, regardless of the persistence context's current setting.
+ *
+ * To change the read-only/modifiable setting for a particular entity
+ * or proxy that is already in this session:
++ * @see PersistenceContext#setReadOnly(Object,boolean)
+ * @see org.hibernate.Session#setReadOnly(Object, boolean)
+ *
+ * To override this session's read-only/modifiable setting for entities
+ * and proxies loaded by a Query:
+ * @see org.hibernate.Query#setReadOnly(boolean)
+ *
+ * @param readOnly true, the default for loaded entities/proxies is read-only;
+ * false, the default for loaded entities/proxies is modifiable
+ *
+ * @see org.hibernate.Session#setDefaultReadOnly(boolean)
+ */
+ public void setDefaultReadOnly(boolean readOnly);
+
+ /**
* Is the entity or proxy read-only?
*
+ * To get the default read-only/modifiable setting used for
+ * entities and proxies that are loaded into the session:
+ * @see org.hibernate.Session#isDefaultReadOnly()
+ *
* @param entityOrProxy
* @return true, the object is read-only; false, the object is modifiable.
*/
public boolean isReadOnly(Object entityOrProxy);
/**
- * Set the entity or proxy to read only and discard it's snapshot.
+ * Set an unmodified persistent object to read-only mode, or a read-only
+ * object to modifiable mode.
*
+ * Read-only entities are not dirty-checked and snapshots of persistent
+ * state are not maintained. Read-only entities can be modified, but
+ * changes are not persisted.
+ *
+ * When a proxy is initialized, the loaded entity will have the same
+ * read-only/modifiable setting as the uninitialized
+ * proxy has, regardless of the session's current setting.
+ *
* If the entity or proxy already has the specified read-only/modifiable
* setting, then this method does nothing.
*
+ * To set the default read-only/modifiable setting used for
+ * entities and proxies that are loaded into this persistence context:
+ * @see PersistenceContext#setDefaultReadOnly(boolean)
+ * @see org.hibernate.Session#setDefaultReadOnly(boolean)
+ *
+ * To override this persistence context's read-only/modifiable setting
+ * for entities and proxies loaded by a Query:
+ * @see org.hibernate.Query#setReadOnly(boolean)
+ *
* @param entityOrProxy, an entity or HibernateProxy
* @param readOnly, if true, the entity or proxy is made read-only;
* if false, the entity or proxy is made modifiable.
+ *
+ * @see org.hibernate.Session#setReadOnly(Object, boolean)
*/
public void setReadOnly(Object entityOrProxy, boolean readOnly);
Modified: core/trunk/core/src/main/java/org/hibernate/engine/QueryParameters.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/engine/QueryParameters.java 2010-01-26 21:49:51 UTC (rev 18640)
+++ core/trunk/core/src/main/java/org/hibernate/engine/QueryParameters.java 2010-01-27 06:36:55 UTC (rev 18641)
@@ -66,6 +66,7 @@
private Object optionalObject;
private String optionalEntityName;
private Serializable optionalId;
+ private boolean isReadOnlyInitialized;
private boolean readOnly;
private boolean callable = false;
private boolean autodiscovertypes = false;
@@ -124,6 +125,7 @@
null,
false,
false,
+ false,
null,
null,
collectionKeys,
@@ -149,6 +151,7 @@
lockOptions,
rowSelection,
false,
+ false,
cacheable,
cacheRegion,
comment,
@@ -164,6 +167,7 @@
final Map namedParameters,
final LockOptions lockOptions,
final RowSelection rowSelection,
+ final boolean isReadOnlyInitialized,
final boolean readOnly,
final boolean cacheable,
final String cacheRegion,
@@ -181,6 +185,7 @@
//this.forceCacheRefresh = forceCacheRefresh;
this.comment = comment;
this.collectionKeys = collectionKeys;
+ this.isReadOnlyInitialized = isReadOnlyInitialized;
this.readOnly = readOnly;
this.resultTransformer = transformer;
}
@@ -191,6 +196,7 @@
final Map namedParameters,
final LockOptions lockOptions,
final RowSelection rowSelection,
+ final boolean isReadOnlyInitialized,
final boolean readOnly,
final boolean cacheable,
final String cacheRegion,
@@ -207,6 +213,7 @@
namedParameters,
lockOptions,
rowSelection,
+ isReadOnlyInitialized,
readOnly,
cacheable,
cacheRegion,
@@ -351,12 +358,82 @@
this.optionalObject = optionalObject;
}
+ /**
+ * Has the read-only/modifiable mode been explicitly set?
+ * @see QueryParameters#setReadOnly(boolean)
+ * @see QueryParameters#isReadOnly(SessionImplementor)
+ *
+ * @return true, the read-only/modifiable mode was explicitly set
+ * false, the read-only/modifiable mode was not explicitly set
+ */
+ public boolean isReadOnlyInitialized() {
+ return isReadOnlyInitialized;
+ }
+
+ /**
+ * Should entities and proxies loaded by the Query be put in read-only mode? The
+ * read-only/modifiable setting must be initialized via QueryParameters#setReadOnly(boolean)
+ * before calling this method.
+ *
+ * @see QueryParameters#isReadOnlyInitialized()
+ * @see QueryParameters#isReadOnly(SessionImplementor)
+ * @see QueryParameters#setReadOnly(boolean)
+ *
+ * The read-only/modifiable setting has no impact on entities/proxies returned by the
+ * query that existed in the session before the query was executed.
+ *
+ * @return true, entities and proxies loaded by the Query will be put in read-only mode
+ * false, entities and proxies loaded by the Query will be put in modifiable mode
+ * @throws IllegalStateException if the read-only/modifiable setting has not been
+ * initialized (i.e., isReadOnlyInitialized() == false).
+ */
public boolean isReadOnly() {
+ if ( ! isReadOnlyInitialized() ) {
+ throw new IllegalStateException( "cannot call isReadOnly() when isReadOnlyInitialized() returns false" );
+ }
return readOnly;
}
+ /**
+ * Should entities and proxies loaded by the Query be put in read-only mode? If the
+ * read-only/modifiable setting was not initialized
+ * (i.e., QueryParameters#isReadOnlyInitialized() == false), then the default
+ * read-only/modifiable setting for the persistence context is returned instead.
+ *
+ * @see QueryParameters#isReadOnlyInitialized()
+ * @see QueryParameters#setReadOnly(boolean)
+ * @see org.hibernate.engine.PersistenceContext#isDefaultReadOnly()
+ *
+ * The read-only/modifiable setting has no impact on entities/proxies returned by the
+ * query that existed in the session before the query was executed.
+ *
+ * @return true, entities and proxies loaded by the query will be put in read-only mode
+ * false, entities and proxies loaded by the query will be put in modifiable mode
+ */
+ public boolean isReadOnly(SessionImplementor session) {
+ return ( isReadOnlyInitialized ?
+ isReadOnly() :
+ session.getPersistenceContext().isDefaultReadOnly()
+ );
+ }
+
+ /**
+ * Set the read-only/modifiable mode for entities and proxies loaded by the query.
+ * *
+ * @see QueryParameters#isReadOnlyInitialized()
+ * @see QueryParameters#isReadOnly(SessionImplementor)
+ * @see QueryParameters#setReadOnly(boolean)
+ * @see org.hibernate.engine.PersistenceContext#isDefaultReadOnly()
+ *
+ * The read-only/modifiable setting has no impact on entities/proxies returned by the
+ * query that existed in the session before the query was executed.
+ *
+ * @return true, entities and proxies loaded by the query will be put in read-only mode
+ * false, entities and proxies loaded by the query will be put in modifiable mode
+ */
public void setReadOnly(boolean readOnly) {
this.readOnly = readOnly;
+ this.isReadOnlyInitialized = true;
}
public void setCallable(boolean callable) {
@@ -467,6 +544,7 @@
this.namedParameters,
this.lockOptions,
selection,
+ this.isReadOnlyInitialized,
this.readOnly,
this.cacheable,
this.cacheRegion,
Modified: core/trunk/core/src/main/java/org/hibernate/engine/StatefulPersistenceContext.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/engine/StatefulPersistenceContext.java 2010-01-26 21:49:51 UTC (rev 18640)
+++ core/trunk/core/src/main/java/org/hibernate/engine/StatefulPersistenceContext.java 2010-01-27 06:36:55 UTC (rev 18641)
@@ -127,6 +127,7 @@
private int loadCounter = 0;
private boolean flushing = false;
+ private boolean defaultReadOnly = false;
private boolean hasNonReadOnlyEntities = false;
private LoadContexts loadContexts;
@@ -231,12 +232,27 @@
if ( batchFetchQueue != null ) {
batchFetchQueue.clear();
}
+ // defaultReadOnly is unaffected by clear()
hasNonReadOnlyEntities = false;
if ( loadContexts != null ) {
loadContexts.cleanup();
}
}
-
+
+ /**
+ * {@inheritDoc}
+ */
+ public boolean isDefaultReadOnly() {
+ return defaultReadOnly;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public void setDefaultReadOnly(boolean defaultReadOnly) {
+ this.defaultReadOnly = defaultReadOnly;
+ }
+
public boolean hasNonReadOnlyEntities() {
return hasNonReadOnlyEntities;
}
@@ -1396,6 +1412,7 @@
public void serialize(ObjectOutputStream oos) throws IOException {
log.trace( "serializing persistent-context" );
+ oos.writeBoolean( defaultReadOnly );
oos.writeBoolean( hasNonReadOnlyEntities );
oos.writeInt( entitiesByKey.size() );
@@ -1491,6 +1508,7 @@
// because serialization is used for different things.
try {
+ rtn.defaultReadOnly = ois.readBoolean();
// todo : we can actually just determine this from the incoming EntityEntry-s
rtn.hasNonReadOnlyEntities = ois.readBoolean();
Modified: core/trunk/core/src/main/java/org/hibernate/event/def/DefaultLoadEventListener.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/event/def/DefaultLoadEventListener.java 2010-01-26 21:49:51 UTC (rev 18640)
+++ core/trunk/core/src/main/java/org/hibernate/event/def/DefaultLoadEventListener.java 2010-01-27 06:36:55 UTC (rev 18641)
@@ -298,6 +298,9 @@
Object proxy = persister.createProxy( event.getEntityId(), event.getSession() );
persistenceContext.getBatchFetchQueue().addBatchLoadableEntityKey(keyToLoad);
persistenceContext.addProxy(keyToLoad, proxy);
+ ( ( HibernateProxy ) proxy )
+ .getHibernateLazyInitializer()
+ .setReadOnly( event.getSession().isDefaultReadOnly() || ! persister.isMutable() );
return proxy;
}
}
@@ -599,7 +602,10 @@
final PersistenceContext persistenceContext = session.getPersistenceContext();
persistenceContext.addEntry(
result,
- Status.MANAGED,
+ ( session.isDefaultReadOnly() || ! persister.isMutable() ?
+ Status.READ_ONLY :
+ Status.MANAGED
+ ),
values,
null,
id,
Modified: core/trunk/core/src/main/java/org/hibernate/impl/AbstractQueryImpl.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/impl/AbstractQueryImpl.java 2010-01-26 21:49:51 UTC (rev 18640)
+++ core/trunk/core/src/main/java/org/hibernate/impl/AbstractQueryImpl.java 2010-01-27 06:36:55 UTC (rev 18641)
@@ -101,7 +101,7 @@
private FlushMode sessionFlushMode;
private CacheMode sessionCacheMode;
private Serializable collectionKey;
- private boolean readOnly;
+ private Boolean readOnly;
private ResultTransformer resultTransformer;
public AbstractQueryImpl(
@@ -202,12 +202,21 @@
return this;
}
+ /**
+ * {@inheritDoc}
+ */
public boolean isReadOnly() {
- return readOnly;
+ return ( readOnly == null ?
+ getSession().getPersistenceContext().isDefaultReadOnly() :
+ readOnly.booleanValue()
+ );
}
+ /**
+ * {@inheritDoc}
+ */
public Query setReadOnly(boolean readOnly) {
- this.readOnly = readOnly;
+ this.readOnly = Boolean.valueOf( readOnly );
return this;
}
@@ -881,7 +890,8 @@
namedParams,
getLockOptions(),
getSelection(),
- readOnly,
+ true,
+ isReadOnly(),
cacheable,
cacheRegion,
comment,
Modified: core/trunk/core/src/main/java/org/hibernate/impl/SessionImpl.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/impl/SessionImpl.java 2010-01-26 21:49:51 UTC (rev 18640)
+++ core/trunk/core/src/main/java/org/hibernate/impl/SessionImpl.java 2010-01-27 06:36:55 UTC (rev 18641)
@@ -1956,6 +1956,20 @@
return true;
}
+ /**
+ * {@inheritDoc}
+ */
+ public boolean isDefaultReadOnly() {
+ return persistenceContext.isDefaultReadOnly();
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public void setDefaultReadOnly(boolean defaultReadOnly) {
+ persistenceContext.setDefaultReadOnly( defaultReadOnly );
+ }
+
public boolean isReadOnly(Object entityOrProxy) {
errorIfClosed();
checkTransactionSynchStatus();
Modified: core/trunk/core/src/main/java/org/hibernate/impl/StatelessSessionImpl.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/impl/StatelessSessionImpl.java 2010-01-26 21:49:51 UTC (rev 18640)
+++ core/trunk/core/src/main/java/org/hibernate/impl/StatelessSessionImpl.java 2010-01-27 06:36:55 UTC (rev 18641)
@@ -483,6 +483,22 @@
return false;
}
+ /**
+ * {@inheritDoc}
+ */
+ public boolean isDefaultReadOnly() {
+ return false;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public void setDefaultReadOnly(boolean readOnly) throws HibernateException {
+ if ( readOnly == true ) {
+ throw new UnsupportedOperationException();
+ }
+ }
+
/////////////////////////////////////////////////////////////////////////////////////////////////////
//TODO: COPY/PASTE FROM SessionImpl, pull up!
Modified: core/trunk/core/src/main/java/org/hibernate/loader/Loader.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/loader/Loader.java 2010-01-26 21:49:51 UTC (rev 18640)
+++ core/trunk/core/src/main/java/org/hibernate/loader/Loader.java 2010-01-27 06:36:55 UTC (rev 18641)
@@ -253,15 +253,32 @@
throws HibernateException, SQLException {
final PersistenceContext persistenceContext = session.getPersistenceContext();
+ boolean defaultReadOnlyOrig = persistenceContext.isDefaultReadOnly();
+ if ( queryParameters.isReadOnlyInitialized() ) {
+ // The read-only/modifiable mode for the query was explicitly set.
+ // Temporarily set the default read-only/modifiable setting to the query's setting.
+ persistenceContext.setDefaultReadOnly( queryParameters.isReadOnly() );
+ }
+ else {
+ // The read-only/modifiable setting for the query was not initialized.
+ // Use the default read-only/modifiable from the persistence context instead.
+ queryParameters.setReadOnly( persistenceContext.isDefaultReadOnly() );
+ }
persistenceContext.beforeLoad();
List result;
try {
- result = doQuery( session, queryParameters, returnProxies );
+ try {
+ result = doQuery( session, queryParameters, returnProxies );
+ }
+ finally {
+ persistenceContext.afterLoad();
+ }
+ persistenceContext.initializeNonLazyCollections();
}
finally {
- persistenceContext.afterLoad();
+ // Restore the original default
+ persistenceContext.setDefaultReadOnly( defaultReadOnlyOrig );
}
- persistenceContext.initializeNonLazyCollections();
return result;
}
@@ -312,7 +329,7 @@
hydratedObjects,
resultSet,
session,
- queryParameters.isReadOnly()
+ queryParameters.isReadOnly( session )
);
session.getPersistenceContext().initializeNonLazyCollections();
return result;
@@ -363,7 +380,7 @@
hydratedObjects,
resultSet,
session,
- queryParameters.isReadOnly()
+ queryParameters.isReadOnly( session )
);
session.getPersistenceContext().initializeNonLazyCollections();
return result;
@@ -749,7 +766,7 @@
session.getBatcher().closeQueryStatement( st, rs );
}
- initializeEntitiesAndCollections( hydratedObjects, rs, session, queryParameters.isReadOnly() );
+ initializeEntitiesAndCollections( hydratedObjects, rs, session, queryParameters.isReadOnly( session ) );
if ( createSubselects ) createSubselects( subselectResultKeys, queryParameters, session );
@@ -1884,7 +1901,7 @@
try {
result = doQueryAndInitializeNonLazyCollections(
session,
- new QueryParameters(
+ new QueryParameters(
new Type[] { identifierType },
new Object[] { id },
optionalObject,
Modified: core/trunk/core/src/main/java/org/hibernate/proxy/AbstractLazyInitializer.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/proxy/AbstractLazyInitializer.java 2010-01-26 21:49:51 UTC (rev 18640)
+++ core/trunk/core/src/main/java/org/hibernate/proxy/AbstractLazyInitializer.java 2010-01-27 06:36:55 UTC (rev 18641)
@@ -65,11 +65,11 @@
protected AbstractLazyInitializer(String entityName, Serializable id, SessionImplementor session) {
this.entityName = entityName;
this.id = id;
+ this.readOnly = false;
// initialize other fields depending on session state
if ( session == null ) {
// would be better to call unsetSession(), but it is not final...
session = null;
- readOnly = false;
}
else {
setSession( session );
@@ -116,11 +116,11 @@
*/
public final void setSession(SessionImplementor s) throws HibernateException {
if ( s != session ) {
+ readOnly = false;
// check for s == null first, since it is least expensive
if ( s == null ){
// would be better to call unsetSession(), but it is not final...
session = null;
- readOnly = false;
}
else if ( isConnectedToSession() ) {
//TODO: perhaps this should be some other RuntimeException...
@@ -128,8 +128,6 @@
}
else {
session = s;
- // NOTE: the proxy may not be connected to the session yet, so set readOnly directly
- readOnly = ! session.getFactory().getEntityPersister( entityName ).isMutable();
}
}
}
Modified: core/trunk/core/src/main/java/org/hibernate/proxy/pojo/cglib/CGLIBLazyInitializer.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/proxy/pojo/cglib/CGLIBLazyInitializer.java 2010-01-26 21:49:51 UTC (rev 18640)
+++ core/trunk/core/src/main/java/org/hibernate/proxy/pojo/cglib/CGLIBLazyInitializer.java 2010-01-27 06:36:55 UTC (rev 18641)
@@ -212,6 +212,7 @@
persistentClass,
interfaces,
getIdentifier(),
+ ( getSession() != null && getSession().isOpen() ? isReadOnly() : false ),
getIdentifierMethod,
setIdentifierMethod,
componentIdType
Modified: core/trunk/core/src/main/java/org/hibernate/proxy/pojo/cglib/SerializableProxy.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/proxy/pojo/cglib/SerializableProxy.java 2010-01-26 21:49:51 UTC (rev 18640)
+++ core/trunk/core/src/main/java/org/hibernate/proxy/pojo/cglib/SerializableProxy.java 2010-01-27 06:36:55 UTC (rev 18641)
@@ -28,6 +28,7 @@
import java.lang.reflect.Method;
import org.hibernate.HibernateException;
+import org.hibernate.proxy.HibernateProxy;
import org.hibernate.type.AbstractComponentType;
/**
@@ -39,6 +40,7 @@
private Class persistentClass;
private Class[] interfaces;
private Serializable id;
+ private boolean readOnly;
private Class getIdentifierMethodClass;
private Class setIdentifierMethodClass;
private String getIdentifierMethodName;
@@ -53,6 +55,7 @@
final Class persistentClass,
final Class[] interfaces,
final Serializable id,
+ final boolean readOnly,
final Method getIdentifierMethod,
final Method setIdentifierMethod,
AbstractComponentType componentIdType
@@ -61,6 +64,7 @@
this.persistentClass = persistentClass;
this.interfaces = interfaces;
this.id = id;
+ this.readOnly = readOnly;
if (getIdentifierMethod!=null) {
getIdentifierMethodClass = getIdentifierMethod.getDeclaringClass();
getIdentifierMethodName = getIdentifierMethod.getName();
Modified: core/trunk/core/src/main/java/org/hibernate/proxy/pojo/javassist/JavassistLazyInitializer.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/proxy/pojo/javassist/JavassistLazyInitializer.java 2010-01-26 21:49:51 UTC (rev 18640)
+++ core/trunk/core/src/main/java/org/hibernate/proxy/pojo/javassist/JavassistLazyInitializer.java 2010-01-27 06:36:55 UTC (rev 18641)
@@ -229,6 +229,7 @@
persistentClass,
interfaces,
getIdentifier(),
+ ( getSession() != null && getSession().isOpen() ? isReadOnly() : false ),
getIdentifierMethod,
setIdentifierMethod,
componentIdType
Modified: core/trunk/core/src/main/java/org/hibernate/proxy/pojo/javassist/SerializableProxy.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/proxy/pojo/javassist/SerializableProxy.java 2010-01-26 21:49:51 UTC (rev 18640)
+++ core/trunk/core/src/main/java/org/hibernate/proxy/pojo/javassist/SerializableProxy.java 2010-01-27 06:36:55 UTC (rev 18641)
@@ -28,6 +28,7 @@
import java.lang.reflect.Method;
import org.hibernate.HibernateException;
+import org.hibernate.proxy.HibernateProxy;
import org.hibernate.type.AbstractComponentType;
/**
@@ -39,6 +40,7 @@
private Class persistentClass;
private Class[] interfaces;
private Serializable id;
+ private boolean readOnly;
private Class getIdentifierMethodClass;
private Class setIdentifierMethodClass;
private String getIdentifierMethodName;
@@ -53,6 +55,7 @@
final Class persistentClass,
final Class[] interfaces,
final Serializable id,
+ final boolean readOnly,
final Method getIdentifierMethod,
final Method setIdentifierMethod,
AbstractComponentType componentIdType
@@ -61,6 +64,7 @@
this.persistentClass = persistentClass;
this.interfaces = interfaces;
this.id = id;
+ this.readOnly = readOnly;
if (getIdentifierMethod!=null) {
getIdentifierMethodClass = getIdentifierMethod.getDeclaringClass();
getIdentifierMethodName = getIdentifierMethod.getName();
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/immutable/ImmutableTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/immutable/ImmutableTest.java 2010-01-26 21:49:51 UTC (rev 18640)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/immutable/ImmutableTest.java 2010-01-27 06:36:55 UTC (rev 18641)
@@ -29,6 +29,7 @@
import junit.framework.Test;
+import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
@@ -53,6 +54,120 @@
return new FunctionalTestClassTestSuite( ImmutableTest.class );
}
+ public void testPersistImmutable() {
+ Contract c = new Contract("gavin", "phone");
+ ContractVariation cv1 = new ContractVariation(1, c);
+ cv1.setText("expensive");
+ ContractVariation cv2 = new ContractVariation(2, c);
+ cv2.setText("more expensive");
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ s.persist(c);
+ // c, cv1, and cv2 were added to s by s.persist(c) (not hibernate), so they are modifiable
+ assertFalse( s.isReadOnly( c ) );
+ assertFalse( s.isReadOnly( cv1 ) );
+ assertFalse( s.isReadOnly( cv2 ) );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ c = (Contract) s.createCriteria(Contract.class).uniqueResult();
+ // c was loaded into s by hibernate, so it should be read-only
+ assertTrue( s.isReadOnly( c ) );
+ assertEquals( c.getCustomerName(), "gavin" );
+ assertEquals( c.getVariations().size(), 2 );
+ Iterator it = c.getVariations().iterator();
+ cv1 = (ContractVariation) it.next();
+ assertEquals( cv1.getText(), "expensive" );
+ cv2 = (ContractVariation) it.next();
+ assertEquals( cv2.getText(), "more expensive" );
+ // cv1 and cv2 were loaded into s by hibernate, so they should be read-only
+ assertTrue( s.isReadOnly( cv1 ) );
+ assertTrue( s.isReadOnly( cv2 ) );
+ s.delete(c);
+ assertEquals( s.createCriteria(Contract.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
+ assertEquals( s.createCriteria(ContractVariation.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
+ t.commit();
+ s.close();
+ }
+
+ public void testSaveImmutable() {
+ Contract c = new Contract("gavin", "phone");
+ ContractVariation cv1 = new ContractVariation(1, c);
+ cv1.setText("expensive");
+ ContractVariation cv2 = new ContractVariation(2, c);
+ cv2.setText("more expensive");
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ s.save(c);
+ // c, cv1, and cv2 were added to s by s.persist(c) (not hibernate), so they are modifiable
+ assertFalse( s.isReadOnly( c ) );
+ assertFalse( s.isReadOnly( cv1 ) );
+ assertFalse( s.isReadOnly( cv2 ) );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ c = (Contract) s.createCriteria(Contract.class).uniqueResult();
+ // c was loaded into s by hibernate, so it should be read-only
+ assertTrue( s.isReadOnly( c ) );
+ assertEquals( c.getCustomerName(), "gavin" );
+ assertEquals( c.getVariations().size(), 2 );
+ Iterator it = c.getVariations().iterator();
+ cv1 = (ContractVariation) it.next();
+ assertEquals( cv1.getText(), "expensive" );
+ cv2 = (ContractVariation) it.next();
+ assertEquals( cv2.getText(), "more expensive" );
+ // cv1 and cv2 were loaded into s by hibernate, so they should be read-only
+ assertTrue( s.isReadOnly( cv1 ) );
+ assertTrue( s.isReadOnly( cv2 ) );
+ s.delete(c);
+ assertEquals( s.createCriteria(Contract.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
+ assertEquals( s.createCriteria(ContractVariation.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
+ t.commit();
+ s.close();
+ }
+
+ public void testSaveOrUpdateImmutable() {
+ Contract c = new Contract("gavin", "phone");
+ ContractVariation cv1 = new ContractVariation(1, c);
+ cv1.setText("expensive");
+ ContractVariation cv2 = new ContractVariation(2, c);
+ cv2.setText("more expensive");
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ s.saveOrUpdate(c);
+ // c, cv1, and cv2 were added to s by s.persist(c) (not hibernate), so they are modifiable
+ assertFalse( s.isReadOnly( c ) );
+ assertFalse( s.isReadOnly( cv1 ) );
+ assertFalse( s.isReadOnly( cv2 ) );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ c = (Contract) s.createCriteria(Contract.class).uniqueResult();
+ // c was loaded into s by hibernate, so it should be read-only
+ assertTrue( s.isReadOnly( c ) );
+ assertEquals( c.getCustomerName(), "gavin" );
+ assertEquals( c.getVariations().size(), 2 );
+ Iterator it = c.getVariations().iterator();
+ cv1 = (ContractVariation) it.next();
+ assertEquals( cv1.getText(), "expensive" );
+ cv2 = (ContractVariation) it.next();
+ assertEquals( cv2.getText(), "more expensive" );
+ // cv1 and cv2 were loaded into s by hibernate, so they should be read-only
+ assertTrue( s.isReadOnly( cv1 ) );
+ assertTrue( s.isReadOnly( cv2 ) );
+ s.delete(c);
+ assertEquals( s.createCriteria(Contract.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
+ assertEquals( s.createCriteria(ContractVariation.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
+ t.commit();
+ s.close();
+ }
+
public void testImmutable() {
Contract c = new Contract("gavin", "phone");
ContractVariation cv1 = new ContractVariation(1, c);
@@ -62,22 +177,36 @@
Session s = openSession();
Transaction t = s.beginTransaction();
s.persist(c);
+ // c, cv1, and cv2 were added to s by s.persist(c) (not hibernate), so they are modifiable
+ assertFalse( s.isReadOnly( c ) );
+ assertFalse( s.isReadOnly( cv1 ) );
+ assertFalse( s.isReadOnly( cv2 ) );
t.commit();
s.close();
s = openSession();
t = s.beginTransaction();
c = (Contract) s.createCriteria(Contract.class).uniqueResult();
+ // c was loaded into s, so it should be read-only
+ assertTrue( s.isReadOnly( c ) );
c.setCustomerName("foo bar");
c.getVariations().add( new ContractVariation(3, c) );
cv1 = (ContractVariation) c.getVariations().iterator().next();
cv1.setText("blah blah");
+ // cv1 and cv2 were loaded into s by hibernate, so they should be read-only
+ assertTrue( s.isReadOnly( cv1 ) );
+ assertFalse( s.contains( cv2 ) );
t.commit();
+ assertTrue( s.isReadOnly( c ) );
+ assertTrue( s.isReadOnly( cv1 ) );
+ assertFalse( s.contains( cv2 ) );
s.close();
s = openSession();
t = s.beginTransaction();
c = (Contract) s.createCriteria(Contract.class).uniqueResult();
+ // c was loaded into s by hibernate, so it should be read-only
+ assertTrue( s.isReadOnly( c ) );
assertEquals( c.getCustomerName(), "gavin" );
assertEquals( c.getVariations().size(), 2 );
Iterator it = c.getVariations().iterator();
@@ -85,6 +214,9 @@
assertEquals( cv1.getText(), "expensive" );
cv2 = (ContractVariation) it.next();
assertEquals( cv2.getText(), "more expensive" );
+ // cv1 and cv2 were loaded into s by hibernate, so they should be read-only
+ assertTrue( s.isReadOnly( cv1 ) );
+ assertTrue( s.isReadOnly( cv2 ) );
s.delete(c);
assertEquals( s.createCriteria(Contract.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
assertEquals( s.createCriteria(ContractVariation.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
@@ -92,6 +224,209 @@
s.close();
}
+ public void testPersistAndUpdateImmutable() {
+ Contract c = new Contract("gavin", "phone");
+ ContractVariation cv1 = new ContractVariation(1, c);
+ cv1.setText("expensive");
+ ContractVariation cv2 = new ContractVariation(2, c);
+ cv2.setText("more expensive");
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ s.persist(c);
+ // c, cv1, and cv2 were added to s by s.persist(c) (not hibernate), so they are modifiable
+ assertFalse( s.isReadOnly( c ) );
+ assertFalse( s.isReadOnly( cv1 ) );
+ assertFalse( s.isReadOnly( cv2 ) );
+ c.setCustomerName( "Sherman" );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ c = (Contract) s.createCriteria(Contract.class).uniqueResult();
+ // c was loaded into s, so it should be read-only
+ assertTrue( s.isReadOnly( c ) );
+ c.setCustomerName("foo bar");
+ c.getVariations().add( new ContractVariation(3, c) );
+ cv1 = (ContractVariation) c.getVariations().iterator().next();
+ cv1.setText("blah blah");
+ // cv1 and cv2 were loaded into s by hibernate, so they should be read-only
+ assertTrue( s.isReadOnly( cv1 ) );
+ assertFalse( s.contains( cv2 ) );
+ t.commit();
+ assertTrue( s.isReadOnly( c ) );
+ assertTrue( s.isReadOnly( cv1 ) );
+ assertFalse( s.contains( cv2 ) );
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ c = (Contract) s.createCriteria(Contract.class).uniqueResult();
+ // c was loaded into s by hibernate, so it should be read-only
+ assertTrue( s.isReadOnly( c ) );
+ assertEquals( c.getCustomerName(), "gavin" );
+ assertEquals( c.getVariations().size(), 2 );
+ Iterator it = c.getVariations().iterator();
+ cv1 = (ContractVariation) it.next();
+ assertEquals( cv1.getText(), "expensive" );
+ cv2 = (ContractVariation) it.next();
+ assertEquals( cv2.getText(), "more expensive" );
+ // cv1 and cv2 were loaded into s by hibernate, so they should be read-only
+ assertTrue( s.isReadOnly( cv1 ) );
+ assertTrue( s.isReadOnly( cv2 ) );
+ s.delete(c);
+ assertEquals( s.createCriteria(Contract.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
+ assertEquals( s.createCriteria(ContractVariation.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
+ t.commit();
+ s.close();
+ }
+
+ public void testUpdateAndDeleteManagedImmutable() {
+ Contract c = new Contract("gavin", "phone");
+ ContractVariation cv1 = new ContractVariation(1, c);
+ cv1.setText("expensive");
+ ContractVariation cv2 = new ContractVariation(2, c);
+ cv2.setText("more expensive");
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ s.persist(c);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ c = (Contract) s.createCriteria(Contract.class).uniqueResult();
+ // c was loaded into s by hibernate, so it should be read-only
+ assertTrue( s.isReadOnly( c ) );
+ assertEquals( c.getCustomerName(), "gavin" );
+ assertEquals( c.getVariations().size(), 2 );
+ Iterator it = c.getVariations().iterator();
+ cv1 = (ContractVariation) it.next();
+ assertEquals( cv1.getText(), "expensive" );
+ cv2 = (ContractVariation) it.next();
+ assertEquals( cv2.getText(), "more expensive" );
+ // cv1 and cv2 were loaded into s by hibernate, so they should be read-only
+ assertTrue( s.isReadOnly( cv1 ) );
+ assertTrue( s.isReadOnly( cv2 ) );
+ c.setCustomerName( "Sherman" );
+ s.delete(c);
+ assertEquals( s.createCriteria(Contract.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
+ assertEquals( s.createCriteria(ContractVariation.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
+ t.commit();
+ s.close();
+ }
+
+ public void testGetAndDeleteManagedImmutable() {
+ Contract c = new Contract("gavin", "phone");
+ ContractVariation cv1 = new ContractVariation(1, c);
+ cv1.setText("expensive");
+ ContractVariation cv2 = new ContractVariation(2, c);
+ cv2.setText("more expensive");
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ s.persist(c);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ c = (Contract) s.get( Contract.class, c.getId() );
+ // c was loaded into s by hibernate, so it should be read-only
+ assertTrue( s.isReadOnly( c ) );
+ assertEquals( c.getCustomerName(), "gavin" );
+ assertEquals( c.getVariations().size(), 2 );
+ Iterator it = c.getVariations().iterator();
+ cv1 = (ContractVariation) it.next();
+ assertEquals( cv1.getText(), "expensive" );
+ cv2 = (ContractVariation) it.next();
+ assertEquals( cv2.getText(), "more expensive" );
+ // cv1 and cv2 were loaded into s by hibernate, so they should be read-only
+ assertTrue( s.isReadOnly( cv1 ) );
+ assertTrue( s.isReadOnly( cv2 ) );
+ c.setCustomerName( "Sherman" );
+ s.delete(c);
+ assertEquals( s.createCriteria(Contract.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
+ assertEquals( s.createCriteria(ContractVariation.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
+ t.commit();
+ s.close();
+ }
+
+ public void testDeleteDetachedImmutable() {
+ Contract c = new Contract("gavin", "phone");
+ ContractVariation cv1 = new ContractVariation(1, c);
+ cv1.setText("expensive");
+ ContractVariation cv2 = new ContractVariation(2, c);
+ cv2.setText("more expensive");
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ s.persist(c);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.delete( c );
+ /*
+ c = (Contract) s.createCriteria(Contract.class).uniqueResult();
+ // c was loaded into s by hibernate, so it should be read-only
+ assertTrue( s.isReadOnly( c ) );
+ assertEquals( c.getCustomerName(), "gavin" );
+ assertEquals( c.getVariations().size(), 2 );
+ Iterator it = c.getVariations().iterator();
+ cv1 = (ContractVariation) it.next();
+ assertEquals( cv1.getText(), "expensive" );
+ cv2 = (ContractVariation) it.next();
+ assertEquals( cv2.getText(), "more expensive" );
+ // cv1 and cv2 were loaded into s by hibernate, so they should be read-only
+ assertTrue( s.isReadOnly( cv1 ) );
+ assertTrue( s.isReadOnly( cv2 ) );
+ s.delete(c);
+ assertEquals( s.createCriteria(Contract.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
+ assertEquals( s.createCriteria(ContractVariation.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
+ */
+ t.commit();
+ s.close();
+ }
+
+ public void testDeleteDetachedModifiedImmutable() {
+ Contract c = new Contract("gavin", "phone");
+ ContractVariation cv1 = new ContractVariation(1, c);
+ cv1.setText("expensive");
+ ContractVariation cv2 = new ContractVariation(2, c);
+ cv2.setText("more expensive");
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ s.persist(c);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ c.setCustomerName( "sherman" );
+ s.delete( c );
+ /*
+ c = (Contract) s.createCriteria(Contract.class).uniqueResult();
+ // c was loaded into s by hibernate, so it should be read-only
+ assertTrue( s.isReadOnly( c ) );
+ assertEquals( c.getCustomerName(), "gavin" );
+ assertEquals( c.getVariations().size(), 2 );
+ Iterator it = c.getVariations().iterator();
+ cv1 = (ContractVariation) it.next();
+ assertEquals( cv1.getText(), "expensive" );
+ cv2 = (ContractVariation) it.next();
+ assertEquals( cv2.getText(), "more expensive" );
+ // cv1 and cv2 were loaded into s by hibernate, so they should be read-only
+ assertTrue( s.isReadOnly( cv1 ) );
+ assertTrue( s.isReadOnly( cv2 ) );
+ s.delete(c);
+ assertEquals( s.createCriteria(Contract.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
+ assertEquals( s.createCriteria(ContractVariation.class).setProjection( Projections.rowCount() ).uniqueResult(), new Long(0) );
+ */
+ t.commit();
+ s.close();
+ }
+
+
public void testImmutableParentEntityWithUpdate() {
Contract c = new Contract("gavin", "phone");
ContractVariation cv1 = new ContractVariation(1, c);
@@ -108,7 +443,15 @@
t = s.beginTransaction();
c.setCustomerName("foo bar");
s.update( c );
+ // c was not loaded into s by hibernate, so it should be modifiable
+ assertFalse( s.isReadOnly( c ) );
+ assertFalse( s.contains( cv1 ) );
+ assertFalse( s.contains( cv2 ) );
t.commit();
+ // c, cv1, and cv2 were not loaded into s by hibernate, so they are modifiable
+ assertFalse( s.isReadOnly( c ) );
+ assertFalse( s.isReadOnly( cv1 ) );
+ assertFalse( s.isReadOnly( cv2 ) );
s.close();
s = openSession();
@@ -145,7 +488,14 @@
cv1 = (ContractVariation) c.getVariations().iterator().next();
cv1.setText("blah blah");
s.update( c );
+ // c was not loaded into s by hibernate, so it should be modifiable
+ assertFalse( s.isReadOnly( c ) );
+ assertFalse( s.contains( cv1 ) );
+ assertFalse( s.contains( cv2 ) );
t.commit();
+ assertFalse( s.isReadOnly( c ) );
+ assertFalse( s.isReadOnly( cv1 ) );
+ assertFalse( s.isReadOnly( cv2 ) );
s.close();
s = openSession();
@@ -224,7 +574,16 @@
s = openSession();
t = s.beginTransaction();
c.setCustomerName("foo bar");
- s.merge( c );
+ c = ( Contract ) s.merge( c );
+ // c was loaded into s by hibernate in the merge process, so it is read-only
+ assertTrue( s.isReadOnly( c ) );
+ assertTrue( Hibernate.isInitialized( c.getVariations() ) );
+ Iterator it = c.getVariations().iterator();
+ cv1 = (ContractVariation) it.next();
+ cv2 = (ContractVariation) it.next();
+ // cv1 and cv2 were loaded into s by hibernate in the merge process, so they are read-only
+ assertTrue( s.isReadOnly( c ) );
+ assertTrue( s.isReadOnly( c ) );
t.commit();
s.close();
@@ -233,7 +592,7 @@
c = (Contract) s.createCriteria(Contract.class).uniqueResult();
assertEquals( c.getCustomerName(), "gavin" );
assertEquals( c.getVariations().size(), 2 );
- Iterator it = c.getVariations().iterator();
+ it = c.getVariations().iterator();
cv1 = (ContractVariation) it.next();
assertEquals( cv1.getText(), "expensive" );
cv2 = (ContractVariation) it.next();
@@ -261,7 +620,16 @@
t = s.beginTransaction();
cv1 = (ContractVariation) c.getVariations().iterator().next();
cv1.setText("blah blah");
- s.merge( c );
+ c = ( Contract ) s.merge( c );
+ // c was loaded into s by hibernate in the merge process, so it is read-only
+ assertTrue( s.isReadOnly( c ) );
+ assertTrue( Hibernate.isInitialized( c.getVariations() ) );
+ Iterator it = c.getVariations().iterator();
+ cv1 = (ContractVariation) it.next();
+ cv2 = (ContractVariation) it.next();
+ // cv1 and cv2 were loaded into s by hibernate in the merge process, so they are read-only
+ assertTrue( s.isReadOnly( c ) );
+ assertTrue( s.isReadOnly( c ) );
t.commit();
s.close();
@@ -270,7 +638,7 @@
c = (Contract) s.createCriteria(Contract.class).uniqueResult();
assertEquals( c.getCustomerName(), "gavin" );
assertEquals( c.getVariations().size(), 2 );
- Iterator it = c.getVariations().iterator();
+ it = c.getVariations().iterator();
cv1 = (ContractVariation) it.next();
assertEquals( cv1.getText(), "expensive" );
cv2 = (ContractVariation) it.next();
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/nonflushedchanges/GetLoadTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/nonflushedchanges/GetLoadTest.java 2010-01-26 21:49:51 UTC (rev 18640)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/nonflushedchanges/GetLoadTest.java 2010-01-27 06:36:55 UTC (rev 18641)
@@ -1,6 +1,9 @@
//$Id: GetLoadTest.java 10977 2006-12-12 23:28:04Z steve.ebersole(a)jboss.com $
package org.hibernate.test.nonflushedchanges;
+import java.util.Iterator;
+import java.util.List;
+
import junit.framework.Test;
import org.hibernate.Hibernate;
@@ -8,6 +11,7 @@
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+import org.hibernate.proxy.HibernateProxy;
import org.hibernate.test.tm.SimpleJtaTransactionManagerImpl;
@@ -92,8 +96,133 @@
SimpleJtaTransactionManagerImpl.getInstance().commit();
assertFetchCount( 0 );
+
+ SimpleJtaTransactionManagerImpl.getInstance().begin();
+ s = openSession();
+ s.createQuery( "delete from Employer" ).executeUpdate();
+ List list = s.createQuery( "from Node" ).list();
+ for ( Iterator it=list.iterator(); it.hasNext(); ) {
+ s.delete( it.next() );
+ }
+ SimpleJtaTransactionManagerImpl.getInstance().commit();
}
+ public void testGetReadOnly() throws Exception {
+ clearCounts();
+
+ SimpleJtaTransactionManagerImpl.getInstance().begin();
+ Session s = openSession();
+ Employer emp = new Employer();
+ s.persist( emp );
+ Node node = new Node( "foo" );
+ Node parent = new Node( "bar" );
+ parent.addChild( node );
+ s.persist( parent );
+ SimpleJtaTransactionManagerImpl.getInstance().commit();
+
+ SimpleJtaTransactionManagerImpl.getInstance().begin();
+ s = openSession();
+ assertFalse( s.isDefaultReadOnly() );
+ s.setDefaultReadOnly( true );
+ emp = ( Employer ) s.get( Employer.class, emp.getId() );
+ assertTrue( s.isDefaultReadOnly() );
+ s = applyNonFlushedChangesToNewSessionCloseOldSession( s );
+ assertTrue( s.isDefaultReadOnly() );
+ emp = ( Employer ) getOldToNewEntityRefMap().get( emp );
+ assertTrue( Hibernate.isInitialized( emp ) );
+ assertFalse( Hibernate.isInitialized( emp.getEmployees() ) );
+ node = ( Node ) s.get( Node.class, node.getName() );
+ assertTrue( s.isReadOnly( emp ) );
+ assertTrue( s.isReadOnly( node ) );
+ s.setDefaultReadOnly( false );
+ s = applyNonFlushedChangesToNewSessionCloseOldSession( s );
+ assertFalse( s.isDefaultReadOnly() );
+ node = ( Node ) getOldToNewEntityRefMap().get( node );
+ emp = ( Employer ) getOldToNewEntityRefMap().get( emp );
+ assertTrue( Hibernate.isInitialized( node ) );
+ assertTrue( s.isReadOnly( node ) );
+ assertFalse( Hibernate.isInitialized( node.getParent() ) );
+ assertTrue( s.isReadOnly( emp ) );
+ assertFalse( Hibernate.isInitialized( node.getChildren() ) );
+ Hibernate.initialize( node.getChildren() );
+ for ( Iterator it=node.getChildren().iterator(); it.hasNext(); ) {
+ assertFalse( s.isReadOnly( it.next() ) );
+ }
+ assertFalse( Hibernate.isInitialized( node.getParent() ) );
+ assertNull( s.get( Node.class, "xyz" ) );
+ SimpleJtaTransactionManagerImpl.getInstance().commit();
+
+ SimpleJtaTransactionManagerImpl.getInstance().begin();
+ s = openSession();
+ assertFalse( s.isDefaultReadOnly() );
+ emp = ( Employer ) s.get( "org.hibernate.test.nonflushedchanges.Employer", emp.getId() );
+ s = applyNonFlushedChangesToNewSessionCloseOldSession( s );
+ assertFalse( s.isDefaultReadOnly() );
+ emp = ( Employer ) getOldToNewEntityRefMap().get( emp );
+ assertTrue( Hibernate.isInitialized( emp ) );
+ assertFalse( s.isReadOnly( emp ) );
+ s.setReadOnly( emp, true );
+ node = ( Node ) s.get( "org.hibernate.test.nonflushedchanges.Node", node.getName() );
+ assertFalse( s.isReadOnly( node ) );
+ s.setReadOnly( node, true );
+ s = applyNonFlushedChangesToNewSessionCloseOldSession( s );
+ emp = ( Employer ) getOldToNewEntityRefMap().get( emp );
+ assertTrue( s.isReadOnly( emp ) );
+ node = ( Node ) getOldToNewEntityRefMap().get( node );
+ assertTrue( Hibernate.isInitialized( node ) );
+ assertTrue( s.isReadOnly( node ) );
+ SimpleJtaTransactionManagerImpl.getInstance().commit();
+
+ assertFetchCount( 0 );
+
+ SimpleJtaTransactionManagerImpl.getInstance().begin();
+ s = openSession();
+ s.createQuery( "delete from Employer" ).executeUpdate();
+ List list = s.createQuery( "from Node" ).list();
+ for ( Iterator it=list.iterator(); it.hasNext(); ) {
+ s.delete( it.next() );
+ }
+ SimpleJtaTransactionManagerImpl.getInstance().commit();
+ }
+
+ public void testLoadReadOnlyFailureExpected() throws Exception {
+ clearCounts();
+
+ SimpleJtaTransactionManagerImpl.getInstance().begin();
+ Session s = openSession();
+ Employer emp = new Employer();
+ s.persist( emp );
+ Node node = new Node( "foo" );
+ Node parent = new Node( "bar" );
+ parent.addChild( node );
+ s.persist( parent );
+ SimpleJtaTransactionManagerImpl.getInstance().commit();
+
+ SimpleJtaTransactionManagerImpl.getInstance().begin();
+ s = openSession();
+ assertFalse( s.isDefaultReadOnly() );
+ s.setDefaultReadOnly( true );
+ emp = ( Employer ) s.load( Employer.class, emp.getId() );
+ assertFalse( Hibernate.isInitialized( emp ) );
+ assertTrue( s.isReadOnly( emp ) );
+ assertTrue( s.isDefaultReadOnly() );
+ s = applyNonFlushedChangesToNewSessionCloseOldSession( s );
+ assertTrue( s.isDefaultReadOnly() );
+ emp = ( Employer ) getOldToNewEntityRefMap().get( emp );
+ assertFalse( Hibernate.isInitialized( emp ) );
+ assertTrue( s.isReadOnly( emp ) );
+ SimpleJtaTransactionManagerImpl.getInstance().commit();
+
+ SimpleJtaTransactionManagerImpl.getInstance().begin();
+ s = openSession();
+ s.createQuery( "delete from Employer" ).executeUpdate();
+ List list = s.createQuery( "from Node" ).list();
+ for ( Iterator it=list.iterator(); it.hasNext(); ) {
+ s.delete( it.next() );
+ }
+ SimpleJtaTransactionManagerImpl.getInstance().commit();
+ }
+
public void testGetAfterDelete() throws Exception {
clearCounts();
Added: core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/Container.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/Container.java (rev 0)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/Container.java 2010-01-27 06:36:55 UTC (rev 18641)
@@ -0,0 +1,117 @@
+package org.hibernate.test.readonly;
+
+import java.util.Set;
+import java.util.HashSet;
+import java.io.Serializable;
+
+/**
+ * @author Steve Ebersole, Gail Badner (adapted this from "proxy" tests version)
+ */
+public class Container implements Serializable {
+ private Long id;
+ private String name;
+ private Owner noProxyOwner;
+ private Owner proxyOwner;
+ private Owner nonLazyOwner;
+ private Info noProxyInfo;
+ private Info proxyInfo;
+ private Info nonLazyInfo;
+ private Set lazyDataPoints = new HashSet();
+ private Set nonLazyJoinDataPoints = new HashSet();
+ private Set nonLazySelectDataPoints = new HashSet();
+
+ public Container() {
+ }
+
+ public Container(String name) {
+ this.name = name;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public Owner getNoProxyOwner() {
+ return noProxyOwner;
+ }
+
+ public void setNoProxyOwner(Owner noProxyOwner) {
+ this.noProxyOwner = noProxyOwner;
+ }
+
+ public Owner getProxyOwner() {
+ return proxyOwner;
+ }
+
+ public void setProxyOwner(Owner proxyOwner) {
+ this.proxyOwner = proxyOwner;
+ }
+
+ public Owner getNonLazyOwner() {
+ return nonLazyOwner;
+ }
+
+ public void setNonLazyOwner(Owner nonLazyOwner) {
+ this.nonLazyOwner = nonLazyOwner;
+ }
+
+ public Info getNoProxyInfo() {
+ return noProxyInfo;
+ }
+
+ public void setNoProxyInfo(Info noProxyInfo) {
+ this.noProxyInfo = noProxyInfo;
+ }
+
+ public Info getProxyInfo() {
+ return proxyInfo;
+ }
+
+ public void setProxyInfo(Info proxyInfo) {
+ this.proxyInfo = proxyInfo;
+ }
+
+ public Info getNonLazyInfo() {
+ return nonLazyInfo;
+ }
+
+ public void setNonLazyInfo(Info nonLazyInfo) {
+ this.nonLazyInfo = nonLazyInfo;
+ }
+
+ public Set getLazyDataPoints() {
+ return lazyDataPoints;
+ }
+
+ public void setLazyDataPoints(Set lazyDataPoints) {
+ this.lazyDataPoints = lazyDataPoints;
+ }
+
+ public Set getNonLazyJoinDataPoints() {
+ return nonLazyJoinDataPoints;
+ }
+
+ public void setNonLazyJoinDataPoints(Set nonLazyJoinDataPoints) {
+ this.nonLazyJoinDataPoints = nonLazyJoinDataPoints;
+ }
+
+ public Set getNonLazySelectDataPoints() {
+ return nonLazySelectDataPoints;
+ }
+
+ public void setNonLazySelectDataPoints(Set nonLazySelectDataPoints) {
+ this.nonLazySelectDataPoints = nonLazySelectDataPoints;
+ }
+}
\ No newline at end of file
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/DataPoint.hbm.xml
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/DataPoint.hbm.xml 2010-01-26 21:49:51 UTC (rev 18640)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/DataPoint.hbm.xml 2010-01-27 06:36:55 UTC (rev 18641)
@@ -21,4 +21,43 @@
<property name="description"/>
</class>
+ <class name="Owner">
+ <id name="id">
+ <generator class="increment"/>
+ </id>
+ <property name="name" unique="true"/>
+ </class>
+
+ <class name="Info">
+ <id name="id">
+ <generator class="increment"/>
+ </id>
+ <property name="details"/>
+ </class>
+
+ <class name="Container">
+ <id name="id">
+ <generator class="increment"/>
+ </id>
+ <property name="name"/>
+ <many-to-one name="noProxyOwner" class="Owner" column="no_proxy_owner_name" property-ref="name" lazy="no-proxy" cascade="all"/>
+ <many-to-one name="proxyOwner" class="Owner" column="proxy_owner_name" property-ref="name" lazy="proxy" cascade="all"/>
+ <many-to-one name="nonLazyOwner" class="Owner" column="non_lazy_owner_name" property-ref="name" lazy="false" cascade="all"/>
+ <many-to-one name="noProxyInfo" class="Info" column="no_proxy_info_id" lazy="no-proxy" cascade="all"/>
+ <many-to-one name="proxyInfo" class="Info" column="proxy_info_id" lazy="proxy" cascade="all"/>
+ <many-to-one name="nonLazyInfo" class="Info" column="non_lazy_info_id" lazy="false" cascade="all"/>
+ <set name="lazyDataPoints" lazy="true" inverse="false" cascade="all">
+ <key column="c_lazy_id"/>
+ <one-to-many class="DataPoint"/>
+ </set>
+ <set name="nonLazySelectDataPoints" lazy="false" inverse="false" cascade="all" fetch="select">
+ <key column="c_non_lazy_select_id"/>
+ <one-to-many class="DataPoint"/>
+ </set>
+ <set name="nonLazyJoinDataPoints" lazy="false" inverse="false" cascade="all" fetch="join">
+ <key column="c_non_lazy_join_id"/>
+ <one-to-many class="DataPoint"/>
+ </set>
+ </class>
+
</hibernate-mapping>
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/DataPoint.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/DataPoint.java 2010-01-26 21:49:51 UTC (rev 18640)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/DataPoint.java 2010-01-27 06:36:55 UTC (rev 18641)
@@ -2,15 +2,25 @@
package org.hibernate.test.readonly;
import java.math.BigDecimal;
+import java.io.Serializable;
/**
* @author Gavin King
*/
-public class DataPoint {
+public class DataPoint implements Serializable {
private long id;
private BigDecimal x;
private BigDecimal y;
private String description;
+
+ public DataPoint() {}
+
+ public DataPoint(BigDecimal x, BigDecimal y, String description) {
+ this.x = x;
+ this.y = y;
+ this.description = description;
+ }
+
/**
* @return Returns the description.
*/
@@ -59,4 +69,7 @@
public void setY(BigDecimal y) {
this.y = y;
}
+ void exception() throws Exception {
+ throw new Exception("foo");
+ }
}
Added: core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/Info.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/Info.java (rev 0)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/Info.java 2010-01-27 06:36:55 UTC (rev 18641)
@@ -0,0 +1,34 @@
+package org.hibernate.test.readonly;
+
+/**
+ * todo: describe Info
+ *
+ * @author Steve Ebersole, Gail Badner (adapted this from "proxy" tests version)
+ */
+public class Info {
+ private Long id;
+ private String details;
+
+ public Info() {
+ }
+
+ public Info(String details) {
+ this.details = details;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getDetails() {
+ return details;
+ }
+
+ public void setDetails(String details) {
+ this.details = details;
+ }
+}
\ No newline at end of file
Added: core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/Owner.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/Owner.java (rev 0)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/Owner.java 2010-01-27 06:36:55 UTC (rev 18641)
@@ -0,0 +1,34 @@
+package org.hibernate.test.readonly;
+
+import java.io.Serializable;
+
+/**
+ * @author Steve Ebersole, Gail Badner (adapted this from "proxy" tests version)
+ */
+public class Owner implements Serializable {
+ private Long id;
+ private String name;
+
+ public Owner() {
+ }
+
+ public Owner(String name) {
+ this.name = name;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
\ No newline at end of file
Added: core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlySessionLazyNonLazyTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlySessionLazyNonLazyTest.java (rev 0)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlySessionLazyNonLazyTest.java 2010-01-27 06:36:55 UTC (rev 18641)
@@ -0,0 +1,1446 @@
+//$Id: ReadOnlyTest.java 10977 2006-12-12 23:28:04Z steve.ebersole(a)jboss.com $
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ *
+ */
+package org.hibernate.test.readonly;
+
+import java.math.BigDecimal;
+import java.util.List;
+import java.util.Set;
+import java.util.HashSet;
+import java.util.Arrays;
+import java.util.Iterator;
+
+import junit.framework.Test;
+
+import org.hibernate.CacheMode;
+import org.hibernate.Hibernate;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.proxy.HibernateProxy;
+import org.hibernate.engine.SessionImplementor;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.cfg.Environment;
+import org.hibernate.junit.functional.FunctionalTestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+
+/**
+ * Model:
+ *
+ * Container
+ * |-- N : 1 -- noProxyOwner (property-ref="name" lazy="no-proxy" cascade="all")
+ * |-- N : 1 -- proxyOwner (property-ref="name" lazy="proxy" cascade="all")
+ * |-- N : 1 -- nonLazyOwner (property-ref="name" lazy="false" cascade="all")
+ * |-- N : 1 -- noProxyInfo" (lazy="no-proxy" cascade="all")
+ * |-- N : 1 -- proxyInfo (lazy="proxy" cascade="all"
+ * |-- N : 1 -- nonLazyInfo" (lazy="false" cascade="all")
+ * |
+ * |-- 1 : N -- lazyDataPoints" (lazy="true" inverse="false" cascade="all")
+ * |-- 1 : N -- nonLazySelectDataPoints" (lazy="false" inverse="false" cascade="all" fetch="select")
+ * |-- 1 : N -- nonLazyJoinDataPoints" (lazy="false" inverse="false" cascade="all" fetch="join")
+ *
+ * Note: the following many-to-one properties use a property-ref so they are
+ * initialized, regardless of how the lazy attribute is mapped:
+ * noProxyOwner, proxyOwner, nonLazyOwner
+ *
+ * @author Gail Badner
+ */
+public class ReadOnlySessionLazyNonLazyTest extends FunctionalTestCase {
+
+ public ReadOnlySessionLazyNonLazyTest(String str) {
+ super(str);
+ }
+
+ public String[] getMappings() {
+ return new String[] { "readonly/DataPoint.hbm.xml" };
+ }
+
+ public void configure(Configuration cfg) {
+ cfg.setProperty(Environment.STATEMENT_BATCH_SIZE, "20");
+ }
+
+ public String getCacheConcurrencyStrategy() {
+ return null;
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( ReadOnlySessionLazyNonLazyTest.class );
+ }
+
+ public void testExistingModifiableAfterSetSessionReadOnly() {
+
+ Container cOrig = createContainer();
+ Set expectedInitializedObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ cOrig, cOrig.getNoProxyInfo(), cOrig.getProxyInfo(), cOrig.getNonLazyInfo(),
+ cOrig.getNoProxyOwner(), cOrig.getProxyOwner(), cOrig.getNonLazyOwner(),
+ cOrig.getLazyDataPoints().iterator().next(),
+ cOrig.getNonLazyJoinDataPoints().iterator().next(),
+ cOrig.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ Set expectedReadOnlyObjects = new HashSet();
+
+ Session s = openSession();
+ assertFalse( s.isDefaultReadOnly() );
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ s.save( cOrig );
+ checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ s.setDefaultReadOnly( true );
+ assertTrue( s.isDefaultReadOnly() );
+ checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ t.commit();
+
+ t = s.beginTransaction();
+ assertTrue( s.isDefaultReadOnly() );
+ checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ Container c = ( Container ) s.load( Container.class, cOrig.getId() );
+ assertSame( cOrig, c );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ c = ( Container ) s.get( Container.class, cOrig.getId() );
+ assertSame( cOrig, c );
+ checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ //s.refresh( cOrig );
+ assertSame( cOrig, c );
+ checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ s.evict( cOrig );
+ c = ( Container ) s.get( Container.class, cOrig.getId() );
+ assertNotSame( cOrig, c );
+ expectedInitializedObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ c, c.getNonLazyInfo(),
+ c.getNoProxyOwner(), c.getProxyOwner(), c.getNonLazyOwner(),
+ c.getNonLazyJoinDataPoints().iterator().next(),
+ c.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ expectedReadOnlyObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ c, c.getNoProxyInfo(), c.getProxyInfo(), c.getNonLazyInfo(),
+ c.getNoProxyOwner(), c.getProxyOwner(), c.getNonLazyOwner(),
+ //c.getLazyDataPoints(),
+ c.getNonLazyJoinDataPoints().iterator().next(),
+ c.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ assertFalse( Hibernate.isInitialized( c.getNoProxyInfo() ) );
+ Hibernate.initialize( c.getNoProxyInfo() );
+ expectedInitializedObjects.add( c.getNoProxyInfo() );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ assertFalse( Hibernate.isInitialized( c.getProxyInfo() ) );
+ Hibernate.initialize( c.getProxyInfo() );
+ expectedInitializedObjects.add( c.getProxyInfo() );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ assertFalse( Hibernate.isInitialized( c.getLazyDataPoints() ) );
+ Hibernate.initialize( c.getLazyDataPoints() );
+ expectedInitializedObjects.add( c.getLazyDataPoints().iterator().next() );
+ expectedReadOnlyObjects.add(c.getLazyDataPoints().iterator().next() );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ t.commit();
+ s.close();
+ s = openSession();
+ t = s.beginTransaction();
+ s.createQuery("delete from DataPoint").executeUpdate();
+ s.createQuery("delete from Container").executeUpdate();
+ s.createQuery("delete from Info").executeUpdate();
+ s.createQuery("delete from Owner").executeUpdate();
+ t.commit();
+ s.close();
+
+ }
+
+ public void testExistingReadOnlyAfterSetSessionModifiable() {
+
+ Container cOrig = createContainer();
+ Set expectedInitializedObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ cOrig, cOrig.getNoProxyInfo(), cOrig.getProxyInfo(), cOrig.getNonLazyInfo(),
+ cOrig.getNoProxyOwner(), cOrig.getProxyOwner(), cOrig.getNonLazyOwner(),
+ cOrig.getLazyDataPoints().iterator().next(),
+ cOrig.getNonLazyJoinDataPoints().iterator().next(),
+ cOrig.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ Set expectedReadOnlyObjects = new HashSet();
+ Session s = openSession();
+ assertFalse( s.isDefaultReadOnly() );
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ s.save( cOrig );
+ checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ s.setDefaultReadOnly( true );
+ assertTrue( s.isDefaultReadOnly() );
+ checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.setDefaultReadOnly( true );
+ Container c = ( Container ) s.get( Container.class, cOrig.getId() );
+ assertNotSame( cOrig, c );
+ expectedInitializedObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ c, c.getNonLazyInfo(),
+ c.getNoProxyOwner(), c.getProxyOwner(), c.getNonLazyOwner(),
+ c.getNonLazyJoinDataPoints().iterator().next(),
+ c.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ expectedReadOnlyObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ c, c.getNoProxyInfo(), c.getProxyInfo(), c.getNonLazyInfo(),
+ c.getNoProxyOwner(), c.getProxyOwner(), c.getNonLazyOwner(),
+ //c.getLazyDataPoints(),
+ c.getNonLazyJoinDataPoints().iterator().next(),
+ c.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ s.setDefaultReadOnly( false );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ assertFalse( Hibernate.isInitialized( c.getNoProxyInfo() ) );
+ Hibernate.initialize( c.getNoProxyInfo() );
+ expectedInitializedObjects.add( c.getNoProxyInfo() );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ assertFalse( Hibernate.isInitialized( c.getProxyInfo() ) );
+ Hibernate.initialize( c.getProxyInfo() );
+ expectedInitializedObjects.add( c.getProxyInfo() );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ assertFalse( Hibernate.isInitialized( c.getLazyDataPoints() ) );
+ Hibernate.initialize( c.getLazyDataPoints() );
+ expectedInitializedObjects.add( c.getLazyDataPoints().iterator().next() );
+ //expectedReadOnlyObjects.add(c.getLazyDataPoints().iterator().next() );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ t.commit();
+ s.close();
+ s = openSession();
+ t = s.beginTransaction();
+ s.createQuery("delete from DataPoint").executeUpdate();
+ s.createQuery("delete from Container").executeUpdate();
+ s.createQuery("delete from Info").executeUpdate();
+ s.createQuery("delete from Owner").executeUpdate();
+ t.commit();
+ s.close();
+
+ }
+
+ public void testExistingReadOnlyAfterSetSessionModifiableExisting() {
+
+ Container cOrig = createContainer();
+ Set expectedInitializedObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ cOrig, cOrig.getNoProxyInfo(), cOrig.getProxyInfo(), cOrig.getNonLazyInfo(),
+ cOrig.getNoProxyOwner(), cOrig.getProxyOwner(), cOrig.getNonLazyOwner(),
+ cOrig.getLazyDataPoints().iterator().next(),
+ cOrig.getNonLazyJoinDataPoints().iterator().next(),
+ cOrig.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ Set expectedReadOnlyObjects = new HashSet();
+ DataPoint lazyDataPointOrig = ( DataPoint ) cOrig.getLazyDataPoints().iterator().next();
+ Session s = openSession();
+ assertFalse( s.isDefaultReadOnly() );
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ s.save( cOrig );
+ checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ s.setDefaultReadOnly( true );
+ assertTrue( s.isDefaultReadOnly() );
+ checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.setDefaultReadOnly( true );
+ Container c = ( Container ) s.get( Container.class, cOrig.getId() );
+ assertNotSame( cOrig, c );
+ expectedInitializedObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ c, c.getNonLazyInfo(),
+ c.getNoProxyOwner(), c.getProxyOwner(), c.getNonLazyOwner(),
+ c.getNonLazyJoinDataPoints().iterator().next(),
+ c.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ expectedReadOnlyObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ c, c.getNoProxyInfo(), c.getProxyInfo(), c.getNonLazyInfo(),
+ c.getNoProxyOwner(), c.getProxyOwner(), c.getNonLazyOwner(),
+ //c.getLazyDataPoints(),
+ c.getNonLazyJoinDataPoints().iterator().next(),
+ c.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ s.setDefaultReadOnly( false );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ assertFalse( Hibernate.isInitialized( c.getNoProxyInfo() ) );
+ Hibernate.initialize( c.getNoProxyInfo() );
+ expectedInitializedObjects.add( c.getNoProxyInfo() );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ assertFalse( Hibernate.isInitialized( c.getProxyInfo() ) );
+ Hibernate.initialize( c.getProxyInfo() );
+ expectedInitializedObjects.add( c.getProxyInfo() );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ DataPoint lazyDataPoint = ( DataPoint ) s.get( DataPoint.class, lazyDataPointOrig.getId() );
+ assertFalse( Hibernate.isInitialized( c.getLazyDataPoints() ) );
+ Hibernate.initialize( c.getLazyDataPoints() );
+ assertSame( lazyDataPoint, c.getLazyDataPoints().iterator().next() );
+ expectedInitializedObjects.add( c.getLazyDataPoints().iterator().next() );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ t.commit();
+ s.close();
+ s = openSession();
+ t = s.beginTransaction();
+ s.createQuery("delete from DataPoint").executeUpdate();
+ s.createQuery("delete from Container").executeUpdate();
+ s.createQuery("delete from Info").executeUpdate();
+ s.createQuery("delete from Owner").executeUpdate();
+ t.commit();
+ s.close();
+
+ }
+
+ public void testExistingReadOnlyAfterSetSessionModifiableExistingEntityReadOnly() {
+
+ Container cOrig = createContainer();
+ Set expectedInitializedObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ cOrig, cOrig.getNoProxyInfo(), cOrig.getProxyInfo(), cOrig.getNonLazyInfo(),
+ cOrig.getNoProxyOwner(), cOrig.getProxyOwner(), cOrig.getNonLazyOwner(),
+ cOrig.getLazyDataPoints().iterator().next(),
+ cOrig.getNonLazyJoinDataPoints().iterator().next(),
+ cOrig.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ Set expectedReadOnlyObjects = new HashSet();
+ DataPoint lazyDataPointOrig = ( DataPoint ) cOrig.getLazyDataPoints().iterator().next();
+ Session s = openSession();
+ assertFalse( s.isDefaultReadOnly() );
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ s.save( cOrig );
+ checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ s.setDefaultReadOnly( true );
+ assertTrue( s.isDefaultReadOnly() );
+ checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.setDefaultReadOnly( true );
+ Container c = ( Container ) s.get( Container.class, cOrig.getId() );
+ assertNotSame( cOrig, c );
+ expectedInitializedObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ c, c.getNonLazyInfo(),
+ c.getNoProxyOwner(), c.getProxyOwner(), c.getNonLazyOwner(),
+ c.getNonLazyJoinDataPoints().iterator().next(),
+ c.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ expectedReadOnlyObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ c, c.getNoProxyInfo(), c.getProxyInfo(), c.getNonLazyInfo(),
+ c.getNoProxyOwner(), c.getProxyOwner(), c.getNonLazyOwner(),
+ //c.getLazyDataPoints(),
+ c.getNonLazyJoinDataPoints().iterator().next(),
+ c.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ s.setDefaultReadOnly( false );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ assertFalse( Hibernate.isInitialized( c.getNoProxyInfo() ) );
+ Hibernate.initialize( c.getNoProxyInfo() );
+ expectedInitializedObjects.add( c.getNoProxyInfo() );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ assertFalse( Hibernate.isInitialized( c.getProxyInfo() ) );
+ Hibernate.initialize( c.getProxyInfo() );
+ expectedInitializedObjects.add( c.getProxyInfo() );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ s.setDefaultReadOnly( true );
+ DataPoint lazyDataPoint = ( DataPoint ) s.get( DataPoint.class, lazyDataPointOrig.getId() );
+ s.setDefaultReadOnly( false );
+ assertFalse( Hibernate.isInitialized( c.getLazyDataPoints() ) );
+ Hibernate.initialize( c.getLazyDataPoints() );
+ assertSame( lazyDataPoint, c.getLazyDataPoints().iterator().next() );
+ expectedInitializedObjects.add( c.getLazyDataPoints().iterator().next() );
+ expectedReadOnlyObjects.add( lazyDataPoint );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ t.commit();
+ s.close();
+ s = openSession();
+ t = s.beginTransaction();
+ s.createQuery("delete from DataPoint").executeUpdate();
+ s.createQuery("delete from Container").executeUpdate();
+ s.createQuery("delete from Info").executeUpdate();
+ s.createQuery("delete from Owner").executeUpdate();
+ t.commit();
+ s.close();
+ }
+
+
+ public void testExistingReadOnlyAfterSetSessionModifiableProxyExisting() {
+
+ Container cOrig = createContainer();
+ Set expectedInitializedObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ cOrig, cOrig.getNoProxyInfo(), cOrig.getProxyInfo(), cOrig.getNonLazyInfo(),
+ cOrig.getNoProxyOwner(), cOrig.getProxyOwner(), cOrig.getNonLazyOwner(),
+ cOrig.getLazyDataPoints().iterator().next(),
+ cOrig.getNonLazyJoinDataPoints().iterator().next(),
+ cOrig.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ Set expectedReadOnlyObjects = new HashSet();
+ DataPoint lazyDataPointOrig = ( DataPoint ) cOrig.getLazyDataPoints().iterator().next();
+ Session s = openSession();
+ assertFalse( s.isDefaultReadOnly() );
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ s.save( cOrig );
+ checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ s.setDefaultReadOnly( true );
+ assertTrue( s.isDefaultReadOnly() );
+ checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.setDefaultReadOnly( true );
+ Container c = ( Container ) s.get( Container.class, cOrig.getId() );
+ assertNotSame( cOrig, c );
+ expectedInitializedObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ c, c.getNonLazyInfo(),
+ c.getNoProxyOwner(), c.getProxyOwner(), c.getNonLazyOwner(),
+ c.getNonLazyJoinDataPoints().iterator().next(),
+ c.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ expectedReadOnlyObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ c, c.getNoProxyInfo(), c.getProxyInfo(), c.getNonLazyInfo(),
+ c.getNoProxyOwner(), c.getProxyOwner(), c.getNonLazyOwner(),
+ //c.getLazyDataPoints(),
+ c.getNonLazyJoinDataPoints().iterator().next(),
+ c.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ s.setDefaultReadOnly( false );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ assertFalse( Hibernate.isInitialized( c.getNoProxyInfo() ) );
+ Hibernate.initialize( c.getNoProxyInfo() );
+ expectedInitializedObjects.add( c.getNoProxyInfo() );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ assertFalse( Hibernate.isInitialized( c.getProxyInfo() ) );
+ Hibernate.initialize( c.getProxyInfo() );
+ expectedInitializedObjects.add( c.getProxyInfo() );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ DataPoint lazyDataPoint = ( DataPoint ) s.load( DataPoint.class, lazyDataPointOrig.getId() );
+ assertFalse( Hibernate.isInitialized( c.getLazyDataPoints() ) );
+ Hibernate.initialize( c.getLazyDataPoints() );
+ assertSame( lazyDataPoint, c.getLazyDataPoints().iterator().next() );
+ expectedInitializedObjects.add( c.getLazyDataPoints().iterator().next() );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ t.commit();
+ s.close();
+ s = openSession();
+ t = s.beginTransaction();
+ s.createQuery("delete from DataPoint").executeUpdate();
+ s.createQuery("delete from Container").executeUpdate();
+ s.createQuery("delete from Info").executeUpdate();
+ s.createQuery("delete from Owner").executeUpdate();
+ t.commit();
+ s.close();
+
+ }
+
+ public void testExistingReadOnlyAfterSetSessionModifiableExistingProxyReadOnly() {
+
+ Container cOrig = createContainer();
+ Set expectedInitializedObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ cOrig, cOrig.getNoProxyInfo(), cOrig.getProxyInfo(), cOrig.getNonLazyInfo(),
+ cOrig.getNoProxyOwner(), cOrig.getProxyOwner(), cOrig.getNonLazyOwner(),
+ cOrig.getLazyDataPoints().iterator().next(),
+ cOrig.getNonLazyJoinDataPoints().iterator().next(),
+ cOrig.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ Set expectedReadOnlyObjects = new HashSet();
+ DataPoint lazyDataPointOrig = ( DataPoint ) cOrig.getLazyDataPoints().iterator().next();
+ Session s = openSession();
+ assertFalse( s.isDefaultReadOnly() );
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ s.save( cOrig );
+ checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ s.setDefaultReadOnly( true );
+ assertTrue( s.isDefaultReadOnly() );
+ checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.setDefaultReadOnly( true );
+ Container c = ( Container ) s.get( Container.class, cOrig.getId() );
+ assertNotSame( cOrig, c );
+ expectedInitializedObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ c, c.getNonLazyInfo(),
+ c.getNoProxyOwner(), c.getProxyOwner(), c.getNonLazyOwner(),
+ c.getNonLazyJoinDataPoints().iterator().next(),
+ c.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ expectedReadOnlyObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ c, c.getNoProxyInfo(), c.getProxyInfo(), c.getNonLazyInfo(),
+ c.getNoProxyOwner(), c.getProxyOwner(), c.getNonLazyOwner(),
+ //c.getLazyDataPoints(),
+ c.getNonLazyJoinDataPoints().iterator().next(),
+ c.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ s.setDefaultReadOnly( false );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ assertFalse( Hibernate.isInitialized( c.getNoProxyInfo() ) );
+ Hibernate.initialize( c.getNoProxyInfo() );
+ expectedInitializedObjects.add( c.getNoProxyInfo() );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ assertFalse( Hibernate.isInitialized( c.getProxyInfo() ) );
+ Hibernate.initialize( c.getProxyInfo() );
+ expectedInitializedObjects.add( c.getProxyInfo() );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ s.setDefaultReadOnly( true );
+ DataPoint lazyDataPoint = ( DataPoint ) s.load( DataPoint.class, lazyDataPointOrig.getId() );
+ s.setDefaultReadOnly( false );
+ assertFalse( Hibernate.isInitialized( c.getLazyDataPoints() ) );
+ Hibernate.initialize( c.getLazyDataPoints() );
+ assertSame( lazyDataPoint, c.getLazyDataPoints().iterator().next() );
+ expectedInitializedObjects.add( c.getLazyDataPoints().iterator().next() );
+ expectedReadOnlyObjects.add( lazyDataPoint );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ t.commit();
+ s.close();
+ s = openSession();
+ t = s.beginTransaction();
+ s.createQuery("delete from DataPoint").executeUpdate();
+ s.createQuery("delete from Container").executeUpdate();
+ s.createQuery("delete from Info").executeUpdate();
+ s.createQuery("delete from Owner").executeUpdate();
+ t.commit();
+ s.close();
+ }
+
+ public void testDefaultModifiableWithReadOnlyQueryForEntity() {
+ Container cOrig = createContainer();
+ Set expectedInitializedObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ cOrig, cOrig.getNoProxyInfo(), cOrig.getProxyInfo(), cOrig.getNonLazyInfo(),
+ cOrig.getNoProxyOwner(), cOrig.getProxyOwner(), cOrig.getNonLazyOwner(),
+ cOrig.getLazyDataPoints().iterator().next(),
+ cOrig.getNonLazyJoinDataPoints().iterator().next(),
+ cOrig.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ Set expectedReadOnlyObjects = new HashSet();
+
+ Session s = openSession();
+ assertFalse( s.isDefaultReadOnly() );
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ s.save( cOrig );
+ checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ s.setDefaultReadOnly( true );
+ assertTrue( s.isDefaultReadOnly() );
+ checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ assertFalse( s.isDefaultReadOnly() );
+ Container c = ( Container ) s.createQuery( "from Container where id=" + cOrig.getId() )
+ .setReadOnly( true ).uniqueResult();
+ expectedInitializedObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ c, c.getNonLazyInfo(),
+ c.getNoProxyOwner(), c.getProxyOwner(), c.getNonLazyOwner(),
+ c.getNonLazyJoinDataPoints().iterator().next(),
+ c.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ expectedReadOnlyObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ c, c.getNoProxyInfo(), c.getProxyInfo(), c.getNonLazyInfo(),
+ c.getNoProxyOwner(), c.getProxyOwner(), c.getNonLazyOwner(),
+ //c.getLazyDataPoints(),
+ c.getNonLazyJoinDataPoints().iterator().next(),
+ c.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ assertFalse( Hibernate.isInitialized( c.getNoProxyInfo() ) );
+ Hibernate.initialize( c.getNoProxyInfo() );
+ expectedInitializedObjects.add( c.getNoProxyInfo() );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ assertFalse( Hibernate.isInitialized( c.getProxyInfo() ) );
+ Hibernate.initialize( c.getProxyInfo() );
+ expectedInitializedObjects.add( c.getProxyInfo() );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ assertFalse( Hibernate.isInitialized( c.getLazyDataPoints() ) );
+ Hibernate.initialize( c.getLazyDataPoints() );
+ expectedInitializedObjects.add( c.getLazyDataPoints().iterator().next() );
+ //expectedReadOnlyObjects.add(c.getLazyDataPoints().iterator().next() );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ t.commit();
+ s.close();
+ s = openSession();
+ t = s.beginTransaction();
+ s.createQuery("delete from DataPoint").executeUpdate();
+ s.createQuery("delete from Container").executeUpdate();
+ s.createQuery("delete from Info").executeUpdate();
+ s.createQuery("delete from Owner").executeUpdate();
+ t.commit();
+ s.close();
+ }
+
+ public void testDefaultReadOnlyWithModifiableQueryForEntity() {
+ Container cOrig = createContainer();
+ Set expectedInitializedObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ cOrig, cOrig.getNoProxyInfo(), cOrig.getProxyInfo(), cOrig.getNonLazyInfo(),
+ cOrig.getNoProxyOwner(), cOrig.getProxyOwner(), cOrig.getNonLazyOwner(),
+ cOrig.getLazyDataPoints().iterator().next(),
+ cOrig.getNonLazyJoinDataPoints().iterator().next(),
+ cOrig.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ Set expectedReadOnlyObjects = new HashSet();
+
+ Session s = openSession();
+ assertFalse( s.isDefaultReadOnly() );
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ s.save( cOrig );
+ checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ s.setDefaultReadOnly( true );
+ assertTrue( s.isDefaultReadOnly() );
+ checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.setDefaultReadOnly( true );
+ assertTrue( s.isDefaultReadOnly() );
+ Container c = ( Container ) s.createQuery( "from Container where id=" + cOrig.getId() )
+ .setReadOnly( false ).uniqueResult();
+ expectedInitializedObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ c, c.getNonLazyInfo(),
+ c.getNoProxyOwner(), c.getProxyOwner(), c.getNonLazyOwner(),
+ c.getNonLazyJoinDataPoints().iterator().next(),
+ c.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ expectedReadOnlyObjects = new HashSet();
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ assertFalse( Hibernate.isInitialized( c.getNoProxyInfo() ) );
+ Hibernate.initialize( c.getNoProxyInfo() );
+ expectedInitializedObjects.add( c.getNoProxyInfo() );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ assertFalse( Hibernate.isInitialized( c.getProxyInfo() ) );
+ Hibernate.initialize( c.getProxyInfo() );
+ expectedInitializedObjects.add( c.getProxyInfo() );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ assertFalse( Hibernate.isInitialized( c.getLazyDataPoints() ) );
+ Hibernate.initialize( c.getLazyDataPoints() );
+ expectedInitializedObjects.add( c.getLazyDataPoints().iterator().next() );
+ expectedReadOnlyObjects.add(c.getLazyDataPoints().iterator().next() );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ t.commit();
+ s.close();
+ s = openSession();
+ t = s.beginTransaction();
+ s.createQuery("delete from DataPoint").executeUpdate();
+ s.createQuery("delete from Container").executeUpdate();
+ s.createQuery("delete from Info").executeUpdate();
+ s.createQuery("delete from Owner").executeUpdate();
+ t.commit();
+ s.close();
+ }
+
+ public void testDefaultReadOnlyWithQueryForEntity() {
+ Container cOrig = createContainer();
+ Set expectedInitializedObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ cOrig, cOrig.getNoProxyInfo(), cOrig.getProxyInfo(), cOrig.getNonLazyInfo(),
+ cOrig.getNoProxyOwner(), cOrig.getProxyOwner(), cOrig.getNonLazyOwner(),
+ cOrig.getLazyDataPoints().iterator().next(),
+ cOrig.getNonLazyJoinDataPoints().iterator().next(),
+ cOrig.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ Set expectedReadOnlyObjects = new HashSet();
+
+ Session s = openSession();
+ assertFalse( s.isDefaultReadOnly() );
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ s.save( cOrig );
+ checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ s.setDefaultReadOnly( true );
+ assertTrue( s.isDefaultReadOnly() );
+ checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.setDefaultReadOnly( true );
+ assertTrue( s.isDefaultReadOnly() );
+ Container c = ( Container ) s.createQuery( "from Container where id=" + cOrig.getId() )
+ .uniqueResult();
+ expectedInitializedObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ c, c.getNonLazyInfo(),
+ c.getNoProxyOwner(), c.getProxyOwner(), c.getNonLazyOwner(),
+ c.getNonLazyJoinDataPoints().iterator().next(),
+ c.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ expectedReadOnlyObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ c, c.getNoProxyInfo(), c.getProxyInfo(), c.getNonLazyInfo(),
+ c.getNoProxyOwner(), c.getProxyOwner(), c.getNonLazyOwner(),
+ //c.getLazyDataPoints(),
+ c.getNonLazyJoinDataPoints().iterator().next(),
+ c.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ assertFalse( Hibernate.isInitialized( c.getNoProxyInfo() ) );
+ Hibernate.initialize( c.getNoProxyInfo() );
+ expectedInitializedObjects.add( c.getNoProxyInfo() );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ assertFalse( Hibernate.isInitialized( c.getProxyInfo() ) );
+ Hibernate.initialize( c.getProxyInfo() );
+ expectedInitializedObjects.add( c.getProxyInfo() );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ assertFalse( Hibernate.isInitialized( c.getLazyDataPoints() ) );
+ Hibernate.initialize( c.getLazyDataPoints() );
+ expectedInitializedObjects.add( c.getLazyDataPoints().iterator().next() );
+ expectedReadOnlyObjects.add(c.getLazyDataPoints().iterator().next() );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ t.commit();
+ s.close();
+ s = openSession();
+ t = s.beginTransaction();
+ s.createQuery("delete from DataPoint").executeUpdate();
+ s.createQuery("delete from Container").executeUpdate();
+ s.createQuery("delete from Info").executeUpdate();
+ s.createQuery("delete from Owner").executeUpdate();
+ t.commit();
+ s.close();
+ }
+
+ public void testDefaultModifiableWithQueryForEntity() {
+ Container cOrig = createContainer();
+ Set expectedInitializedObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ cOrig, cOrig.getNoProxyInfo(), cOrig.getProxyInfo(), cOrig.getNonLazyInfo(),
+ cOrig.getNoProxyOwner(), cOrig.getProxyOwner(), cOrig.getNonLazyOwner(),
+ cOrig.getLazyDataPoints().iterator().next(),
+ cOrig.getNonLazyJoinDataPoints().iterator().next(),
+ cOrig.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ Set expectedReadOnlyObjects = new HashSet();
+
+ Session s = openSession();
+ assertFalse( s.isDefaultReadOnly() );
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ s.save( cOrig );
+ checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ s.setDefaultReadOnly( true );
+ assertTrue( s.isDefaultReadOnly() );
+ checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ assertFalse( s.isDefaultReadOnly() );
+ Container c = ( Container ) s.createQuery( "from Container where id=" + cOrig.getId() )
+ .uniqueResult();
+ expectedInitializedObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ c, c.getNonLazyInfo(),
+ c.getNoProxyOwner(), c.getProxyOwner(), c.getNonLazyOwner(),
+ c.getNonLazyJoinDataPoints().iterator().next(),
+ c.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ expectedReadOnlyObjects = new HashSet();
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ assertFalse( Hibernate.isInitialized( c.getNoProxyInfo() ) );
+ Hibernate.initialize( c.getNoProxyInfo() );
+ expectedInitializedObjects.add( c.getNoProxyInfo() );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ assertFalse( Hibernate.isInitialized( c.getProxyInfo() ) );
+ Hibernate.initialize( c.getProxyInfo() );
+ expectedInitializedObjects.add( c.getProxyInfo() );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ assertFalse( Hibernate.isInitialized( c.getLazyDataPoints() ) );
+ Hibernate.initialize( c.getLazyDataPoints() );
+ expectedInitializedObjects.add( c.getLazyDataPoints().iterator().next() );
+ //expectedReadOnlyObjects.add(c.getLazyDataPoints().iterator().next() );
+ checkContainer( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ t.commit();
+ s.close();
+ s = openSession();
+ t = s.beginTransaction();
+ s.createQuery("delete from DataPoint").executeUpdate();
+ s.createQuery("delete from Container").executeUpdate();
+ s.createQuery("delete from Info").executeUpdate();
+ s.createQuery("delete from Owner").executeUpdate();
+ t.commit();
+ s.close();
+ }
+
+ public void testDefaultModifiableWithReadOnlyQueryForCollectionEntities() {
+ Container cOrig = createContainer();
+ Set expectedInitializedObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ cOrig, cOrig.getNoProxyInfo(), cOrig.getProxyInfo(), cOrig.getNonLazyInfo(),
+ cOrig.getNoProxyOwner(), cOrig.getProxyOwner(), cOrig.getNonLazyOwner(),
+ cOrig.getLazyDataPoints().iterator().next(),
+ cOrig.getNonLazyJoinDataPoints().iterator().next(),
+ cOrig.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ Set expectedReadOnlyObjects = new HashSet();
+
+ Session s = openSession();
+ assertFalse( s.isDefaultReadOnly() );
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ s.save( cOrig );
+ checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ s.setDefaultReadOnly( true );
+ assertTrue( s.isDefaultReadOnly() );
+ checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ assertFalse( s.isDefaultReadOnly() );
+ DataPoint dp = ( DataPoint ) s.createQuery( "select c.lazyDataPoints from Container c join c.lazyDataPoints where c.id=" + cOrig.getId() )
+ .setReadOnly( true ).uniqueResult();
+ assertTrue( s.isReadOnly( dp ) );
+ t.commit();
+ s.close();
+ s = openSession();
+ t = s.beginTransaction();
+ s.createQuery("delete from DataPoint").executeUpdate();
+ s.createQuery("delete from Container").executeUpdate();
+ s.createQuery("delete from Info").executeUpdate();
+ s.createQuery("delete from Owner").executeUpdate();
+ t.commit();
+ s.close();
+ }
+
+ public void testDefaultReadOnlyWithModifiableFilterCollectionEntities() {
+ Container cOrig = createContainer();
+ Set expectedInitializedObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ cOrig, cOrig.getNoProxyInfo(), cOrig.getProxyInfo(), cOrig.getNonLazyInfo(),
+ cOrig.getNoProxyOwner(), cOrig.getProxyOwner(), cOrig.getNonLazyOwner(),
+ cOrig.getLazyDataPoints().iterator().next(),
+ cOrig.getNonLazyJoinDataPoints().iterator().next(),
+ cOrig.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ Set expectedReadOnlyObjects = new HashSet();
+
+ Session s = openSession();
+ assertFalse( s.isDefaultReadOnly() );
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ s.save( cOrig );
+ checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ s.setDefaultReadOnly( true );
+ assertTrue( s.isDefaultReadOnly() );
+ checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.setDefaultReadOnly( true );
+ assertTrue( s.isDefaultReadOnly() );
+ Container c = ( Container ) s.get( Container.class, cOrig.getId() );
+ assertNotSame( cOrig, c );
+ expectedInitializedObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ c, c.getNonLazyInfo(),
+ c.getNoProxyOwner(), c.getProxyOwner(), c.getNonLazyOwner(),
+ c.getNonLazyJoinDataPoints().iterator().next(),
+ c.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ expectedReadOnlyObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ c, c.getNoProxyInfo(), c.getProxyInfo(), c.getNonLazyInfo(),
+ c.getNoProxyOwner(), c.getProxyOwner(), c.getNonLazyOwner(),
+ //c.getLazyDataPoints(),
+ c.getNonLazyJoinDataPoints().iterator().next(),
+ c.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ List list = ( List ) s.createFilter( c.getLazyDataPoints(), "" )
+ .setMaxResults(1)
+ .setReadOnly( false )
+ .list();
+ assertEquals( 1, list.size() );
+ assertFalse( s.isReadOnly( list.get( 0 ) ) );
+ list = ( List ) s.createFilter( c.getNonLazyJoinDataPoints(), "" )
+ .setMaxResults(1)
+ .setReadOnly( false )
+ .list();
+ assertEquals( 1, list.size() );
+ assertTrue( s.isReadOnly( list.get( 0 ) ) );
+ list = ( List ) s.createFilter( c.getNonLazySelectDataPoints(), "" )
+ .setMaxResults(1)
+ .setReadOnly( false )
+ .list();
+ assertEquals( 1, list.size() );
+ assertTrue( s.isReadOnly( list.get( 0 ) ) );
+ t.commit();
+ s.close();
+ s = openSession();
+ t = s.beginTransaction();
+ s.createQuery("delete from DataPoint").executeUpdate();
+ s.createQuery("delete from Container").executeUpdate();
+ s.createQuery("delete from Info").executeUpdate();
+ s.createQuery("delete from Owner").executeUpdate();
+ t.commit();
+ s.close();
+ }
+
+ public void testDefaultModifiableWithReadOnlyFilterCollectionEntities() {
+ Container cOrig = createContainer();
+ Set expectedInitializedObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ cOrig, cOrig.getNoProxyInfo(), cOrig.getProxyInfo(), cOrig.getNonLazyInfo(),
+ cOrig.getNoProxyOwner(), cOrig.getProxyOwner(), cOrig.getNonLazyOwner(),
+ cOrig.getLazyDataPoints().iterator().next(),
+ cOrig.getNonLazyJoinDataPoints().iterator().next(),
+ cOrig.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ Set expectedReadOnlyObjects = new HashSet();
+
+ Session s = openSession();
+ assertFalse( s.isDefaultReadOnly() );
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ s.save( cOrig );
+ checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ s.setDefaultReadOnly( true );
+ assertTrue( s.isDefaultReadOnly() );
+ checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ assertFalse( s.isDefaultReadOnly() );
+ Container c = ( Container ) s.get( Container.class, cOrig.getId() );
+ assertNotSame( cOrig, c );
+ expectedInitializedObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ c, c.getNonLazyInfo(),
+ c.getNoProxyOwner(), c.getProxyOwner(), c.getNonLazyOwner(),
+ c.getNonLazyJoinDataPoints().iterator().next(),
+ c.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ expectedReadOnlyObjects = new HashSet();
+ List list = ( List ) s.createFilter( c.getLazyDataPoints(), "" )
+ .setMaxResults(1)
+ .setReadOnly( true )
+ .list();
+ assertEquals( 1, list.size() );
+ assertTrue( s.isReadOnly( list.get( 0 ) ) );
+ list = ( List ) s.createFilter( c.getNonLazyJoinDataPoints(), "" )
+ .setMaxResults(1)
+ .setReadOnly( true )
+ .list();
+ assertEquals( 1, list.size() );
+ assertFalse( s.isReadOnly( list.get( 0 ) ) );
+ list = ( List ) s.createFilter( c.getNonLazySelectDataPoints(), "" )
+ .setMaxResults(1)
+ .setReadOnly( true )
+ .list();
+ assertEquals( 1, list.size() );
+ assertFalse( s.isReadOnly( list.get( 0 ) ) );
+ t.commit();
+ s.close();
+ s = openSession();
+ t = s.beginTransaction();
+ s.createQuery("delete from DataPoint").executeUpdate();
+ s.createQuery("delete from Container").executeUpdate();
+ s.createQuery("delete from Info").executeUpdate();
+ s.createQuery("delete from Owner").executeUpdate();
+ t.commit();
+ s.close();
+ }
+
+ public void testDefaultReadOnlyWithFilterCollectionEntities() {
+ Container cOrig = createContainer();
+ Set expectedInitializedObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ cOrig, cOrig.getNoProxyInfo(), cOrig.getProxyInfo(), cOrig.getNonLazyInfo(),
+ cOrig.getNoProxyOwner(), cOrig.getProxyOwner(), cOrig.getNonLazyOwner(),
+ cOrig.getLazyDataPoints().iterator().next(),
+ cOrig.getNonLazyJoinDataPoints().iterator().next(),
+ cOrig.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ Set expectedReadOnlyObjects = new HashSet();
+
+ Session s = openSession();
+ assertFalse( s.isDefaultReadOnly() );
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ s.save( cOrig );
+ checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ s.setDefaultReadOnly( true );
+ assertTrue( s.isDefaultReadOnly() );
+ checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.setDefaultReadOnly( true );
+ assertTrue( s.isDefaultReadOnly() );
+ Container c = ( Container ) s.get( Container.class, cOrig.getId() );
+ assertNotSame( cOrig, c );
+ expectedInitializedObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ c, c.getNonLazyInfo(),
+ c.getNoProxyOwner(), c.getProxyOwner(), c.getNonLazyOwner(),
+ c.getNonLazyJoinDataPoints().iterator().next(),
+ c.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ expectedReadOnlyObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ c, c.getNoProxyInfo(), c.getProxyInfo(), c.getNonLazyInfo(),
+ c.getNoProxyOwner(), c.getProxyOwner(), c.getNonLazyOwner(),
+ //c.getLazyDataPoints(),
+ c.getNonLazyJoinDataPoints().iterator().next(),
+ c.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ List list = ( List ) s.createFilter( c.getLazyDataPoints(), "" )
+ .setMaxResults(1)
+ .list();
+ assertEquals( 1, list.size() );
+ assertTrue( s.isReadOnly( list.get( 0 ) ) );
+ list = ( List ) s.createFilter( c.getNonLazyJoinDataPoints(), "" )
+ .setMaxResults(1)
+ .list();
+ assertEquals( 1, list.size() );
+ assertTrue( s.isReadOnly( list.get( 0 ) ) );
+ list = ( List ) s.createFilter( c.getNonLazySelectDataPoints(), "" )
+ .setMaxResults(1)
+ .list();
+ assertEquals( 1, list.size() );
+ assertTrue( s.isReadOnly( list.get( 0 ) ) );
+ t.commit();
+ s.close();
+ s = openSession();
+ t = s.beginTransaction();
+ s.createQuery("delete from DataPoint").executeUpdate();
+ s.createQuery("delete from Container").executeUpdate();
+ s.createQuery("delete from Info").executeUpdate();
+ s.createQuery("delete from Owner").executeUpdate();
+ t.commit();
+ s.close();
+ }
+
+ public void testDefaultModifiableWithFilterCollectionEntities() {
+ Container cOrig = createContainer();
+ Set expectedInitializedObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ cOrig, cOrig.getNoProxyInfo(), cOrig.getProxyInfo(), cOrig.getNonLazyInfo(),
+ cOrig.getNoProxyOwner(), cOrig.getProxyOwner(), cOrig.getNonLazyOwner(),
+ cOrig.getLazyDataPoints().iterator().next(),
+ cOrig.getNonLazyJoinDataPoints().iterator().next(),
+ cOrig.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ Set expectedReadOnlyObjects = new HashSet();
+
+ Session s = openSession();
+ assertFalse( s.isDefaultReadOnly() );
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ s.save( cOrig );
+ checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ s.setDefaultReadOnly( true );
+ assertTrue( s.isDefaultReadOnly() );
+ checkContainer( cOrig, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ assertFalse( s.isDefaultReadOnly() );
+ Container c = ( Container ) s.get( Container.class, cOrig.getId() );
+ assertNotSame( cOrig, c );
+ expectedInitializedObjects =
+ new HashSet(
+ Arrays.asList( new Object[ ] {
+ c, c.getNonLazyInfo(),
+ c.getNoProxyOwner(), c.getProxyOwner(), c.getNonLazyOwner(),
+ c.getNonLazyJoinDataPoints().iterator().next(),
+ c.getNonLazySelectDataPoints().iterator().next()
+ }
+ )
+ );
+ expectedReadOnlyObjects = new HashSet();
+ List list = ( List ) s.createFilter( c.getLazyDataPoints(), "" )
+ .setMaxResults(1)
+ .list();
+ assertEquals( 1, list.size() );
+ assertFalse( s.isReadOnly( list.get( 0 ) ) );
+ list = ( List ) s.createFilter( c.getNonLazyJoinDataPoints(), "" )
+ .setMaxResults(1)
+ .list();
+ assertEquals( 1, list.size() );
+ assertFalse( s.isReadOnly( list.get( 0 ) ) );
+ list = ( List ) s.createFilter( c.getNonLazySelectDataPoints(), "" )
+ .setMaxResults(1)
+ .list();
+ assertEquals( 1, list.size() );
+ assertFalse( s.isReadOnly( list.get( 0 ) ) );
+ t.commit();
+ s.close();
+ s = openSession();
+ t = s.beginTransaction();
+ s.createQuery("delete from DataPoint").executeUpdate();
+ s.createQuery("delete from Container").executeUpdate();
+ s.createQuery("delete from Info").executeUpdate();
+ s.createQuery("delete from Owner").executeUpdate();
+ t.commit();
+ s.close();
+ }
+
+/*
+ public void testQueryReadOnlyModeExplicitLeftOuterJoinNonLazy() {
+
+ Container cOrig = createContainer();
+ Session s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ s.save( cOrig );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ t = s.beginTransaction();
+ List list = s.createQuery( "from Container c left outer join c.nonLazyInfo where c.id = :id" )
+ .setLong( "id", cOrig.getId() )
+ .setReadOnly( true )
+ .list();
+ assertEquals( 1, list.size() );
+ Container c = ( Container ) list.get( 0 );
+ check( c, true, s );
+ check( c.getNoProxyInfo(), false, s );
+ check( c.getProxyInfo(), false, s );
+ check( c.getNonLazyInfo(), true, s );
+
+ //check( c.getNoProxyOwner(), true, s );
+ //check( c.getProxyOwner(), true, s );
+ //check( c.getNonLazyOwner(), true, s );
+ check( c.getLazyDataPoints(), false, s );
+ //check( c.getNonLazyJoinDataPoints(), true, s );
+ //check( c.getNonLazySelectDataPoints(), true, s );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.createQuery("delete from DataPoint").executeUpdate();
+ s.createQuery("delete from Container").executeUpdate();
+ s.createQuery("delete from Info").executeUpdate();
+ s.createQuery("delete from Owner").executeUpdate();
+ t.commit();
+ s.close();
+
+ }
+
+ public void testQueryReadOnlyModeExplicitLeftJoinFetchNonLazy() {
+
+ Container cOrig = createContainer();
+ Session s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ s.save( cOrig );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ t = s.beginTransaction();
+ List list = s.createQuery( "from Container c left join fetch c.nonLazyInfo where c.id = :id" )
+ .setLong( "id", cOrig.getId() )
+ .setReadOnly( true )
+ .list();
+ assertEquals( 1, list.size() );
+ Container c = ( Container ) list.get( 0 );
+ check( c, true, s );
+ check( c.getNoProxyInfo(), false, s );
+ check( c.getProxyInfo(), false, s );
+ check( c.getNonLazyInfo(), true, s );
+
+ // note that Container the following many-to-one properties use a property-ref
+ // so they are initialized, regardless of how the lazy attribute is mapped:
+ // noProxyOwner, proxyOwner, nonLazyOwner
+ //check( c.getNoProxyOwner(), true, s );
+ //check( c.getProxyOwner(), true, s );
+ //check( c.getNonLazyOwner(), true, s );
+ check( c.getLazyDataPoints(), false, s );
+ //check( c.getNonLazyJoinDataPoints(), true, s );
+ //check( c.getNonLazySelectDataPoints(), true, s );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.createQuery("delete from DataPoint").executeUpdate();
+ s.createQuery("delete from Container").executeUpdate();
+ s.createQuery("delete from Info").executeUpdate();
+ s.createQuery("delete from Owner").executeUpdate();
+ t.commit();
+ s.close();
+
+ }
+
+ public void testEntityReadOnlyMode() {
+
+ Container cOrig = createContainer();
+ Session s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ s.save( cOrig );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ t = s.beginTransaction();
+ Container c = ( Container ) s.get( Container.class, cOrig.getId() );
+ assertNotNull( c );
+ s.setReadOnly( c, true );
+ check( c, true, s );
+ check( c.getNoProxyInfo(), false, s );
+ check( c.getProxyInfo(), false, s );
+ check( c.getNonLazyInfo(), true, s );
+
+ // note that Container the following many-to-one properties use a property-ref
+ // so they are initialized, regardless of how the lazy attribute is mapped:
+ // noProxyOwner, proxyOwner, nonLazyOwner
+ check( c.getNoProxyOwner(), true, s );
+ check( c.getProxyOwner(), true, s );
+ check( c.getNonLazyOwner(), true, s );
+ check( c.getLazyDataPoints(), false, s );
+ check( c.getNonLazyJoinDataPoints(), true, s );
+ check( c.getNonLazySelectDataPoints(), true, s );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.createQuery("delete from DataPoint").executeUpdate();
+ s.createQuery("delete from Container").executeUpdate();
+ s.createQuery("delete from Info").executeUpdate();
+ s.createQuery("delete from Owner").executeUpdate();
+ t.commit();
+ s.close();
+
+ }
+*/
+
+ private Container createContainer() {
+ Container c = new Container( "container" );
+ c.setNoProxyInfo( new Info( "no-proxy info" ) );
+ c.setProxyInfo( new Info( "proxy info" ) );
+ c.setNonLazyInfo( new Info( "non-lazy info" ) );
+ c.setNoProxyOwner( new Owner( "no-proxy owner" ) );
+ c.setProxyOwner( new Owner( "proxy owner" ) );
+ c.setNonLazyOwner( new Owner( "non-lazy owner" ) );
+ c.getLazyDataPoints().add( new DataPoint( new BigDecimal( 1 ), new BigDecimal( 1 ), "lazy data point" ) );
+ c.getNonLazyJoinDataPoints().add( new DataPoint( new BigDecimal( 2 ), new BigDecimal( 2 ), "non-lazy join data point" ) );
+ c.getNonLazySelectDataPoints().add( new DataPoint( new BigDecimal( 3 ), new BigDecimal( 3 ), "non-lazy select data point" ) );
+ return c;
+ }
+
+ private void checkContainer(Container c, Set expectedInitializedObjects, Set expectedReadOnlyObjects, Session s) {
+ checkObject( c, expectedInitializedObjects, expectedReadOnlyObjects, s );
+ if ( ! expectedInitializedObjects.contains( c ) ) {
+ return;
+ }
+ checkObject( c.getNoProxyInfo(), expectedInitializedObjects, expectedReadOnlyObjects, s);
+ checkObject( c.getProxyInfo(), expectedInitializedObjects, expectedReadOnlyObjects, s);
+ checkObject( c.getNonLazyInfo(), expectedInitializedObjects, expectedReadOnlyObjects, s );
+ checkObject( c.getNoProxyOwner(), expectedInitializedObjects, expectedReadOnlyObjects, s );
+ checkObject( c.getProxyOwner(), expectedInitializedObjects, expectedReadOnlyObjects, s );
+ checkObject( c.getNonLazyOwner(), expectedInitializedObjects, expectedReadOnlyObjects, s );
+ if ( Hibernate.isInitialized( c.getLazyDataPoints() ) ) {
+ for ( Iterator it=c.getLazyDataPoints().iterator(); it.hasNext(); ) {
+ checkObject( it.next(), expectedInitializedObjects, expectedReadOnlyObjects, s );
+ }
+ }
+ for ( Iterator it=c.getNonLazyJoinDataPoints().iterator(); it.hasNext(); ) {
+ checkObject( it.next(), expectedInitializedObjects, expectedReadOnlyObjects, s );
+ }
+ for ( Iterator it=c.getNonLazySelectDataPoints().iterator(); it.hasNext(); ) {
+ checkObject( it.next(), expectedInitializedObjects, expectedReadOnlyObjects, s );
+ }
+ }
+
+ private void checkObject(Object entityOrProxy, Set expectedInitializedObjects, Set expectedReadOnlyObjects, Session s) {
+ boolean isExpectedToBeInitialized = expectedInitializedObjects.contains( entityOrProxy );
+ boolean isExpectedToBeReadOnly = expectedReadOnlyObjects.contains( entityOrProxy );
+ SessionImplementor si = ( SessionImplementor ) s;
+ assertEquals( isExpectedToBeInitialized, Hibernate.isInitialized( entityOrProxy ) );
+ assertEquals( isExpectedToBeReadOnly, s.isReadOnly( entityOrProxy ) );
+ if ( Hibernate.isInitialized( entityOrProxy ) ) {
+ Object entity = ( entityOrProxy instanceof HibernateProxy ?
+ ( ( HibernateProxy ) entityOrProxy ).getHibernateLazyInitializer().getImplementation( si ) :
+ entityOrProxy
+ );
+ assertNotNull( entity );
+ assertEquals( isExpectedToBeReadOnly, s.isReadOnly( entity ));
+ }
+ }
+
+}
\ No newline at end of file
Added: core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlySessionTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlySessionTest.java (rev 0)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlySessionTest.java 2010-01-27 06:36:55 UTC (rev 18641)
@@ -0,0 +1,456 @@
+//$Id: ReadOnlyTest.java 10977 2006-12-12 23:28:04Z steve.ebersole(a)jboss.com $
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ *
+ */
+package org.hibernate.test.readonly;
+
+import java.math.BigDecimal;
+import java.util.List;
+
+import junit.framework.Test;
+
+import org.hibernate.CacheMode;
+import org.hibernate.Hibernate;
+import org.hibernate.ScrollMode;
+import org.hibernate.ScrollableResults;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.cfg.Environment;
+import org.hibernate.junit.functional.FunctionalTestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+
+/**
+ *
+ * @author Gail Badner
+ */
+public class ReadOnlySessionTest extends FunctionalTestCase {
+
+ public ReadOnlySessionTest(String str) {
+ super(str);
+ }
+
+ public String[] getMappings() {
+ return new String[] { "readonly/DataPoint.hbm.xml", "readonly/TextHolder.hbm.xml" };
+ }
+
+ public void configure(Configuration cfg) {
+ cfg.setProperty(Environment.STATEMENT_BATCH_SIZE, "20");
+ }
+
+ public String getCacheConcurrencyStrategy() {
+ return null;
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( ReadOnlySessionTest.class );
+ }
+
+ public void testReadOnlyOnProxies() {
+ Session s = openSession();
+ s.setCacheMode( CacheMode.IGNORE );
+ s.beginTransaction();
+ DataPoint dp = new DataPoint();
+ dp.setX( new BigDecimal( 0.1d ).setScale(19, BigDecimal.ROUND_DOWN) );
+ dp.setY( new BigDecimal( Math.cos( dp.getX().doubleValue() ) ).setScale(19, BigDecimal.ROUND_DOWN) );
+ dp.setDescription( "original" );
+ s.save( dp );
+ long dpId = dp.getId();
+ s.getTransaction().commit();
+ s.close();
+
+ s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ s.beginTransaction();
+ s.setDefaultReadOnly( true );
+ assertTrue( s.isDefaultReadOnly() );
+ dp = ( DataPoint ) s.load( DataPoint.class, new Long( dpId ) );
+ s.setDefaultReadOnly( false );
+ assertFalse( "was initialized", Hibernate.isInitialized( dp ) );
+ assertTrue( s.isReadOnly( dp ) );
+ assertFalse( "was initialized during isReadOnly", Hibernate.isInitialized( dp ) );
+ dp.setDescription( "changed" );
+ assertTrue( "was not initialized during mod", Hibernate.isInitialized( dp ) );
+ assertEquals( "desc not changed in memory", "changed", dp.getDescription() );
+ s.flush();
+ s.getTransaction().commit();
+ s.close();
+
+ s = openSession();
+ s.beginTransaction();
+ List list = s.createQuery( "from DataPoint where description = 'changed'" ).list();
+ assertEquals( "change written to database", 0, list.size() );
+ s.createQuery("delete from DataPoint").executeUpdate();
+ s.getTransaction().commit();
+ s.close();
+ }
+
+ public void testReadOnlyMode() {
+
+ Session s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ for ( int i=0; i<100; i++ ) {
+ DataPoint dp = new DataPoint();
+ dp.setX( new BigDecimal(i * 0.1d).setScale(19, BigDecimal.ROUND_DOWN) );
+ dp.setY( new BigDecimal( Math.cos( dp.getX().doubleValue() ) ).setScale(19, BigDecimal.ROUND_DOWN) );
+ s.save(dp);
+ }
+ t.commit();
+ s.close();
+
+ s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ t = s.beginTransaction();
+ s.setDefaultReadOnly( true );
+ int i = 0;
+ ScrollableResults sr = s.createQuery("from DataPoint dp order by dp.x asc")
+ .scroll(ScrollMode.FORWARD_ONLY);
+ while ( sr.next() ) {
+ DataPoint dp = (DataPoint) sr.get(0);
+ if (++i==50) {
+ s.setReadOnly(dp, false);
+ }
+ dp.setDescription("done!");
+ }
+ t.commit();
+ s.clear();
+ t = s.beginTransaction();
+ List single = s.createQuery("from DataPoint where description='done!'").list();
+ assertEquals( single.size(), 1 );
+ s.createQuery("delete from DataPoint").executeUpdate();
+ t.commit();
+ s.close();
+ }
+
+ public void testReadOnlyQueryScrollChangeToModifiableBeforeIterate() {
+
+ Session s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ for ( int i=0; i<100; i++ ) {
+ DataPoint dp = new DataPoint();
+ dp.setX( new BigDecimal(i * 0.1d).setScale(19, BigDecimal.ROUND_DOWN) );
+ dp.setY( new BigDecimal( Math.cos( dp.getX().doubleValue() ) ).setScale(19, BigDecimal.ROUND_DOWN) );
+ s.save(dp);
+ }
+ t.commit();
+ s.close();
+
+ s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ t = s.beginTransaction();
+ s.setDefaultReadOnly( true );
+ int i = 0;
+ ScrollableResults sr = s.createQuery("from DataPoint dp order by dp.x asc")
+ .scroll(ScrollMode.FORWARD_ONLY);
+ s.setDefaultReadOnly( false );
+ while ( sr.next() ) {
+ DataPoint dp = (DataPoint) sr.get(0);
+ if (++i==50) {
+ s.setReadOnly(dp, false);
+ }
+ dp.setDescription("done!");
+ }
+ t.commit();
+ s.clear();
+ t = s.beginTransaction();
+ List single = s.createQuery("from DataPoint where description='done!'").list();
+ assertEquals( 1, single.size() );
+ s.createQuery("delete from DataPoint").executeUpdate();
+ t.commit();
+ s.close();
+ }
+
+ public void testReadOnlyRefreshFailureExpected() {
+
+ Session s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ DataPoint dp = new DataPoint();
+ dp.setDescription( "original" );
+ dp.setX( new BigDecimal(0.1d).setScale(19, BigDecimal.ROUND_DOWN) );
+ dp.setY( new BigDecimal( Math.cos( dp.getX().doubleValue() ) ).setScale(19, BigDecimal.ROUND_DOWN) );
+ s.save(dp);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ s.setDefaultReadOnly( true );
+ t = s.beginTransaction();
+ dp = ( DataPoint ) s.get( DataPoint.class, dp.getId() );
+ assertEquals( "original", dp.getDescription() );
+ dp.setDescription( "changed" );
+ assertEquals( "changed", dp.getDescription() );
+ s.setDefaultReadOnly( false );
+ s.refresh( dp );
+ assertEquals( "original", dp.getDescription() );
+ dp.setDescription( "changed" );
+ assertEquals( "changed", dp.getDescription() );
+ t.commit();
+
+ s.clear();
+ t = s.beginTransaction();
+ dp = ( DataPoint ) s.get( DataPoint.class, dp.getId() );
+ assertEquals( "original", dp.getDescription() );
+ s.delete( dp );
+ t.commit();
+ s.close();
+
+ }
+
+ public void testReadOnlyDelete() {
+
+ Session s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ DataPoint dp = new DataPoint();
+ dp.setX( new BigDecimal(0.1d).setScale(19, BigDecimal.ROUND_DOWN) );
+ dp.setY( new BigDecimal( Math.cos( dp.getX().doubleValue() ) ).setScale(19, BigDecimal.ROUND_DOWN) );
+ s.save(dp);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ s.setDefaultReadOnly( true );
+ s.setCacheMode(CacheMode.IGNORE);
+ t = s.beginTransaction();
+ dp = ( DataPoint ) s.get( DataPoint.class, dp.getId() );
+ s.setDefaultReadOnly( false );
+ assertTrue( s.isReadOnly( dp ) );
+ s.delete( dp );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ List list = s.createQuery("from DataPoint where id=" + dp.getId() ).list();
+ assertTrue( list.isEmpty() );
+ t.commit();
+ s.close();
+
+ }
+
+ public void testReadOnlyGetModifyAndDelete() {
+
+ Session s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ DataPoint dp = new DataPoint();
+ dp.setX( new BigDecimal(0.1d).setScale(19, BigDecimal.ROUND_DOWN) );
+ dp.setY( new BigDecimal( Math.cos( dp.getX().doubleValue() ) ).setScale(19, BigDecimal.ROUND_DOWN) );
+ s.save(dp);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ s.setDefaultReadOnly( true );
+ s.setCacheMode(CacheMode.IGNORE);
+ t = s.beginTransaction();
+ dp = ( DataPoint ) s.get( DataPoint.class, dp.getId() );
+ s.setDefaultReadOnly( true );
+ dp.setDescription( "a DataPoint" );
+ s.delete( dp );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ List list = s.createQuery("from DataPoint where id=" + dp.getId() ).list();
+ assertTrue( list.isEmpty() );
+ t.commit();
+ s.close();
+
+ }
+
+ public void testReadOnlyModeWithExistingModifiableEntity() {
+
+ Session s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ DataPoint dp = null;
+ for ( int i=0; i<100; i++ ) {
+ dp = new DataPoint();
+ dp.setX( new BigDecimal(i * 0.1d).setScale(19, BigDecimal.ROUND_DOWN) );
+ dp.setY( new BigDecimal( Math.cos( dp.getX().doubleValue() ) ).setScale(19, BigDecimal.ROUND_DOWN) );
+ s.save(dp);
+ }
+ t.commit();
+ s.close();
+
+ s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ t = s.beginTransaction();
+ DataPoint dpLast = ( DataPoint ) s.get( DataPoint.class, dp.getId() );
+ assertFalse( s.isReadOnly( dpLast ) );
+ s.setDefaultReadOnly( true );
+ int i = 0;
+ ScrollableResults sr = s.createQuery("from DataPoint dp order by dp.x asc")
+ .scroll(ScrollMode.FORWARD_ONLY);
+ s.setDefaultReadOnly( false );
+ int nExpectedChanges = 0;
+ while ( sr.next() ) {
+ dp = (DataPoint) sr.get(0);
+ if ( dp.getId() == dpLast.getId() ) {
+ //dpLast existed in the session before executing the read-only query
+ assertFalse( s.isReadOnly( dp ) );
+ }
+ else {
+ assertTrue( s.isReadOnly( dp ) );
+ }
+ if (++i==50) {
+ s.setReadOnly(dp, false);
+ nExpectedChanges = ( dp == dpLast ? 1 : 2 );
+ }
+ dp.setDescription("done!");
+ }
+ t.commit();
+ s.clear();
+ t = s.beginTransaction();
+ List list = s.createQuery("from DataPoint where description='done!'").list();
+ assertEquals( nExpectedChanges, list.size() );
+ s.createQuery("delete from DataPoint").executeUpdate();
+ t.commit();
+ s.close();
+ }
+
+ public void testModifiableModeWithExistingReadOnlyEntity() {
+
+ Session s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ DataPoint dp = null;
+ for ( int i=0; i<100; i++ ) {
+ dp = new DataPoint();
+ dp.setX( new BigDecimal(i * 0.1d).setScale(19, BigDecimal.ROUND_DOWN) );
+ dp.setY( new BigDecimal( Math.cos( dp.getX().doubleValue() ) ).setScale(19, BigDecimal.ROUND_DOWN) );
+ s.save(dp);
+ }
+ t.commit();
+ s.close();
+
+ s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ t = s.beginTransaction();
+ s.setDefaultReadOnly( true );
+ DataPoint dpLast = ( DataPoint ) s.get( DataPoint.class, dp.getId() );
+ assertTrue( s.isReadOnly( dpLast ) );
+ int i = 0;
+ ScrollableResults sr = s.createQuery("from DataPoint dp order by dp.x asc")
+ .setReadOnly(false)
+ .scroll(ScrollMode.FORWARD_ONLY);
+ int nExpectedChanges = 0;
+ while ( sr.next() ) {
+ dp = (DataPoint) sr.get(0);
+ if ( dp.getId() == dpLast.getId() ) {
+ //dpLast existed in the session before executing the read-only query
+ assertTrue( s.isReadOnly( dp ) );
+ }
+ else {
+ assertFalse( s.isReadOnly( dp ) );
+ }
+ if (++i==50) {
+ s.setReadOnly(dp, true);
+ nExpectedChanges = ( dp == dpLast ? 99 : 98 );
+ }
+ dp.setDescription("done!");
+ }
+ t.commit();
+ s.clear();
+ t = s.beginTransaction();
+ List list = s.createQuery("from DataPoint where description='done!'").list();
+ assertEquals( nExpectedChanges, list.size() );
+ s.createQuery("delete from DataPoint").executeUpdate();
+ t.commit();
+ s.close();
+ }
+
+ public void testReadOnlyOnTextType() {
+ final String origText = "some huge text string";
+ final String newText = "some even bigger text string";
+
+ Session s = openSession();
+ s.beginTransaction();
+ s.setCacheMode( CacheMode.IGNORE );
+ TextHolder holder = new TextHolder( origText );
+ s.save( holder );
+ Long id = holder.getId();
+ s.getTransaction().commit();
+ s.close();
+
+ s = openSession();
+ s.beginTransaction();
+ s.setDefaultReadOnly( true );
+ s.setCacheMode( CacheMode.IGNORE );
+ holder = ( TextHolder ) s.get( TextHolder.class, id );
+ s.setDefaultReadOnly( false );
+ holder.setTheText( newText );
+ s.flush();
+ s.getTransaction().commit();
+ s.close();
+
+ s = openSession();
+ s.beginTransaction();
+ holder = ( TextHolder ) s.get( TextHolder.class, id );
+ assertEquals( "change written to database", origText, holder.getTheText() );
+ s.delete( holder );
+ s.getTransaction().commit();
+ s.close();
+ }
+
+ public void testMergeWithReadOnlyEntity() {
+
+ Session s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ DataPoint dp = new DataPoint();
+ dp.setX( new BigDecimal(0.1d).setScale(19, BigDecimal.ROUND_DOWN) );
+ dp.setY( new BigDecimal( Math.cos( dp.getX().doubleValue() ) ).setScale(19, BigDecimal.ROUND_DOWN) );
+ s.save(dp);
+ t.commit();
+ s.close();
+
+ dp.setDescription( "description" );
+
+ s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ t = s.beginTransaction();
+ s.setDefaultReadOnly( true );
+ DataPoint dpManaged = ( DataPoint ) s.get( DataPoint.class, new Long( dp.getId() ) );
+ DataPoint dpMerged = ( DataPoint ) s.merge( dp );
+ assertSame( dpManaged, dpMerged );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ dpManaged = ( DataPoint ) s.get( DataPoint.class, new Long( dp.getId() ) );
+ assertNull( dpManaged.getDescription() );
+ s.delete( dpManaged );
+ t.commit();
+ s.close();
+
+ }
+}
\ No newline at end of file
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlyTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlyTest.java 2010-01-26 21:49:51 UTC (rev 18640)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlyTest.java 2010-01-27 06:36:55 UTC (rev 18641)
@@ -26,6 +26,7 @@
package org.hibernate.test.readonly;
import java.math.BigDecimal;
+import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
@@ -44,6 +45,7 @@
/**
*
* @author Gavin King
+ * @author Gail Badner
*/
public class ReadOnlyTest extends FunctionalTestCase {
@@ -142,6 +144,31 @@
}
+ public void testReadOnlyModeAutoFlushOnQuery() {
+
+ Session s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ DataPoint dpFirst = null;
+ for ( int i=0; i<100; i++ ) {
+ DataPoint dp = new DataPoint();
+ dp.setX( new BigDecimal(i * 0.1d).setScale(19, BigDecimal.ROUND_DOWN) );
+ dp.setY( new BigDecimal( Math.cos( dp.getX().doubleValue() ) ).setScale(19, BigDecimal.ROUND_DOWN) );
+ s.save(dp);
+ }
+ ScrollableResults sr = s.createQuery("from DataPoint dp order by dp.x asc")
+ .setReadOnly(true)
+ .scroll(ScrollMode.FORWARD_ONLY);
+ while ( sr.next() ) {
+ DataPoint dp = (DataPoint) sr.get(0);
+ assertFalse( s.isReadOnly( dp ) );
+ s.delete( dp );
+ }
+ t.commit();
+ s.close();
+
+ }
+
public void testReadOnlyRefreshFailureExpected() {
Session s = openSession();
@@ -209,6 +236,37 @@
}
+ public void testReadOnlyGetModifyAndDelete() {
+
+ Session s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ DataPoint dp = new DataPoint();
+ dp.setX( new BigDecimal(0.1d).setScale(19, BigDecimal.ROUND_DOWN) );
+ dp.setY( new BigDecimal( Math.cos( dp.getX().doubleValue() ) ).setScale(19, BigDecimal.ROUND_DOWN) );
+ s.save(dp);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ t = s.beginTransaction();
+ dp = ( DataPoint ) s.get( DataPoint.class, dp.getId() );
+ s.setReadOnly( dp, true );
+ dp.setDescription( "a DataPoint" );
+ s.delete( dp );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ List list = s.createQuery("from DataPoint where description='done!'").list();
+ assertTrue( list.isEmpty() );
+ t.commit();
+ s.close();
+
+ }
+
public void testReadOnlyModeWithExistingModifiableEntity() {
Session s = openSession();
15 years, 1 month
Hibernate SVN: r18640 - in core/trunk: core/src/main/java/org/hibernate/id and 2 other directories.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2010-01-26 16:49:51 -0500 (Tue, 26 Jan 2010)
New Revision: 18640
Modified:
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/idclassgeneratedvalue/IdClassGeneratedValueTest.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/idclassgeneratedvalue/SimplePK.java
core/trunk/core/src/main/java/org/hibernate/id/CompositeNestedGeneratedValueGenerator.java
core/trunk/core/src/main/java/org/hibernate/mapping/Component.java
core/trunk/core/src/main/java/org/hibernate/tuple/entity/AbstractEntityTuplizer.java
Log:
HHH-4552 - Support generated value within composite keys
Modified: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/idclassgeneratedvalue/IdClassGeneratedValueTest.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/idclassgeneratedvalue/IdClassGeneratedValueTest.java 2010-01-26 21:42:19 UTC (rev 18639)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/idclassgeneratedvalue/IdClassGeneratedValueTest.java 2010-01-26 21:49:51 UTC (rev 18640)
@@ -60,7 +60,6 @@
s.close();
}
- @FailureExpected(message = "Not yet implemented", jiraKey = "HHH-4552")
@SuppressWarnings({ "unchecked" })
public void testSingleGeneratedValue() {
Session s = openSession();
@@ -77,7 +76,7 @@
s.beginTransaction();
List<Simple2> simpleList = s.createQuery( "select s from Simple2 s" ).list();
assertEquals( simpleList.size(), 2 );
- s1 = ( Simple2 ) s.load( Simple2.class, new SimplePK( s1Id1, 2L ) );
+ s1 = ( Simple2 ) s.load( Simple2.class, new SimplePK( s1Id1, 200L ) );
assertEquals( s1.getQuantity(), 10 );
s.clear();
s.createQuery( "delete Simple2" ).executeUpdate();
@@ -85,7 +84,6 @@
s.close();
}
- @FailureExpected(message = "Not yet implemented", jiraKey = "HHH-4552")
@SuppressWarnings({ "unchecked" })
public void testMultipleGeneratedValue() {
Session s = openSession();
@@ -103,7 +101,7 @@
s.beginTransaction();
List<Multiple> simpleList = s.createQuery( "select m from Multiple m" ).list();
assertEquals( simpleList.size(), 2 );
- m1 = ( Multiple ) s.load( Multiple.class, new MultiplePK( m1Id1, m1Id2, 2L ) );
+ m1 = ( Multiple ) s.load( Multiple.class, new MultiplePK( m1Id1, m1Id2, 1000L ) );
assertEquals( m1.getQuantity(), 10 );
s.clear();
s.createQuery( "delete Multiple" ).executeUpdate();
Modified: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/idclassgeneratedvalue/SimplePK.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/idclassgeneratedvalue/SimplePK.java 2010-01-26 21:42:19 UTC (rev 18639)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/idclassgeneratedvalue/SimplePK.java 2010-01-26 21:49:51 UTC (rev 18640)
@@ -33,28 +33,17 @@
public class SimplePK implements Serializable {
private final Long id1;
private final Long id2;
- // AnnotationBinder (incorrectly) requires this to be transient; see HHH-4819 and HHH-4820
- private final transient int cachedHashCode;
private SimplePK() {
- // required by Hibernate, though never used; see HHH-4818
id1 = null;
id2 = null;
- cachedHashCode = super.hashCode();
}
public SimplePK(Long id1, Long id2) {
this.id1 = id1;
this.id2 = id2;
- this.cachedHashCode = calculateHashCode();
}
- private int calculateHashCode() {
- int result = id1.hashCode();
- result = 31 * result + id2.hashCode();
- return result;
- }
-
public Long getId1() {
return id1;
}
@@ -80,6 +69,8 @@
@Override
public int hashCode() {
- return cachedHashCode;
+ int result = id1.hashCode();
+ result = 31 * result + id2.hashCode();
+ return result;
}
}
Modified: core/trunk/core/src/main/java/org/hibernate/id/CompositeNestedGeneratedValueGenerator.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/id/CompositeNestedGeneratedValueGenerator.java 2010-01-26 21:42:19 UTC (rev 18639)
+++ core/trunk/core/src/main/java/org/hibernate/id/CompositeNestedGeneratedValueGenerator.java 2010-01-26 21:49:51 UTC (rev 18640)
@@ -62,12 +62,35 @@
* @author Steve Ebersole
*/
public class CompositeNestedGeneratedValueGenerator implements IdentifierGenerator, Serializable {
+ /**
+ * Contract for declaring how to locate the context for sub-value injection.
+ */
public static interface GenerationContextLocator {
+ /**
+ * Given the incoming object, determine the context for injecting back its generated
+ * id sub-values.
+ *
+ * @param session The current session
+ * @param incomingObject The entity for which we are generating id
+ *
+ * @return The injection context
+ */
public Serializable locateGenerationContext(SessionImplementor session, Object incomingObject);
}
+ /**
+ * Contract for performing the actual sub-value generation, usually injecting it into the
+ * determined {@link GenerationContextLocator#locateGenerationContext context}
+ */
public static interface GenerationPlan {
- public void execute(SessionImplementor session, Object incomingObject, Object objectId);
+ /**
+ * Execute the value generation.
+ *
+ * @param session The current session
+ * @param incomingObject The entity for which we are generating id
+ * @param injectionContext The context into which the generated value can be injected
+ */
+ public void execute(SessionImplementor session, Object incomingObject, Object injectionContext);
}
private final GenerationContextLocator generationContextLocator;
Modified: core/trunk/core/src/main/java/org/hibernate/mapping/Component.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/mapping/Component.java 2010-01-26 21:42:19 UTC (rev 18639)
+++ core/trunk/core/src/main/java/org/hibernate/mapping/Component.java 2010-01-26 21:49:51 UTC (rev 18640)
@@ -37,6 +37,7 @@
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.dialect.Dialect;
+import org.hibernate.engine.EntityEntry;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.id.CompositeNestedGeneratedValueGenerator;
import org.hibernate.id.IdentifierGenerator;
@@ -348,17 +349,17 @@
// IMPL NOTE : See the javadoc discussion on CompositeNestedGeneratedValueGenerator wrt the
// various scenarios for which we need to account here
- if ( isEmbedded() ) {
- // we have the "straight up" embedded (again the hibernate term) component identifier
- attributeDeclarer = entityClass;
+ if ( rootClass.getIdentifierMapper() != null ) {
+ // we have the @IdClass / <composite-id mapped="true"/> case
+ attributeDeclarer = resolveComponentClass();
}
else if ( rootClass.getIdentifierProperty() != null ) {
// we have the "@EmbeddedId" / <composite-id name="idName"/> case
attributeDeclarer = resolveComponentClass();
}
else {
- // we have the @IdClass / <composite-id mapped="true"/> case
- attributeDeclarer = resolveComponentClass();
+ // we have the "straight up" embedded (again the hibernate term) component identifier
+ attributeDeclarer = entityClass;
}
locator = new StandardGenerationContextLocator( rootClass.getEntityName() );
@@ -383,13 +384,11 @@
defaultSchema,
rootClass
);
- final Setter injector = property.getPropertyAccessor( attributeDeclarer )
- .getSetter( attributeDeclarer, property.getName() );
generator.addGeneratedValuePlan(
new ValueGenerationPlan(
property.getName(),
valueGenerator,
- injector
+ injector( property, attributeDeclarer )
)
);
}
@@ -397,6 +396,11 @@
return generator;
}
+ private Setter injector(Property property, Class attributeDeclarer) {
+ return property.getPropertyAccessor( attributeDeclarer )
+ .getSetter( attributeDeclarer, property.getName() );
+ }
+
private Class resolveComponentClass() {
try {
return getComponentClass();
@@ -434,9 +438,12 @@
this.injector = injector;
}
- public void execute(SessionImplementor session, Object incomingObject, Object idObject) {
+ /**
+ * {@inheritDoc}
+ */
+ public void execute(SessionImplementor session, Object incomingObject, Object injectionContext) {
final Object generatedValue = subGenerator.generate( session, incomingObject );
- injector.set( idObject, generatedValue, session.getFactory() );
+ injector.set( injectionContext, generatedValue, session.getFactory() );
}
}
Modified: core/trunk/core/src/main/java/org/hibernate/tuple/entity/AbstractEntityTuplizer.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/tuple/entity/AbstractEntityTuplizer.java 2010-01-26 21:42:19 UTC (rev 18639)
+++ core/trunk/core/src/main/java/org/hibernate/tuple/entity/AbstractEntityTuplizer.java 2010-01-26 21:49:51 UTC (rev 18640)
@@ -226,6 +226,11 @@
else if ( idSetter != null ) {
idSetter.set( entity, id, getFactory() );
}
+ else if ( identifierMapperType != null ) {
+ ComponentType extractor = (ComponentType) entityMetamodel.getIdentifierProperty().getType();
+ ComponentType copier = (ComponentType) identifierMapperType;
+ copier.setPropertyValues( entity, extractor.getPropertyValues( id, getEntityMode() ), getEntityMode() );
+ }
}
public void resetIdentifier(Object entity, Serializable currentId, Object currentVersion) {
15 years, 1 month
Hibernate SVN: r18639 - in jpamodelgen/trunk/src: test/java/org/hibernate/jpamodelgen/test/elementcollection and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2010-01-26 16:42:19 -0500 (Tue, 26 Jan 2010)
New Revision: 18639
Modified:
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationMetaCollection.java
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationMetaEntity.java
jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/elementcollection/House.java
Log:
METAGEN-18 - Support @ElementCollection.targetClass + its XMl equivalent
Modified: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationMetaCollection.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationMetaCollection.java 2010-01-26 20:11:51 UTC (rev 18638)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationMetaCollection.java 2010-01-26 21:42:19 UTC (rev 18639)
@@ -17,30 +17,25 @@
*/
package org.hibernate.jpamodelgen.annotation;
-import org.hibernate.jpamodelgen.MetaCollection;
-
import javax.lang.model.element.Element;
+import org.hibernate.jpamodelgen.MetaCollection;
+
/**
- *
* @author Max Andersen
* @author Hardy Ferentschik
* @author Emmanuel Bernard
*/
public class AnnotationMetaCollection extends AnnotationMetaAttribute implements MetaCollection {
+ private String collectionType;
- private String collectionType;
-
-
public AnnotationMetaCollection(AnnotationMetaEntity parent, Element element, String collectionType, String elementType) {
- super(parent, element, elementType);
- this.collectionType = collectionType;
+ super( parent, element, elementType );
+ this.collectionType = collectionType;
}
@Override
- public String getMetaType() {
+ public String getMetaType() {
return collectionType;
}
-
-
}
Modified: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationMetaEntity.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationMetaEntity.java 2010-01-26 20:11:51 UTC (rev 18638)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationMetaEntity.java 2010-01-26 21:42:19 UTC (rev 18639)
@@ -22,10 +22,8 @@
import java.util.List;
import java.util.Map;
import javax.lang.model.element.AnnotationMirror;
-import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
-import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.Name;
import javax.lang.model.element.PackageElement;
@@ -34,6 +32,7 @@
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.ExecutableType;
import javax.lang.model.type.PrimitiveType;
+import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementFilter;
import javax.lang.model.util.SimpleTypeVisitor6;
@@ -312,8 +311,11 @@
class TypeVisitor extends SimpleTypeVisitor6<AnnotationMetaAttribute, Element> {
AnnotationMetaEntity parent;
- //if null, process all members as implicit
- //if not null, only process members marked as @Access(explicitAccessType)
+
+ /*
+ * If {@code explicitAccessType == null}, process all members as implicit. If {@code explicitAccessType != null}
+ * only process members marked as {@code @Access(explicitAccessType)}.
+ */
private AccessType explicitAccessType;
TypeVisitor(AnnotationMetaEntity parent, AccessType explicitAccessType) {
@@ -366,20 +368,19 @@
}
@Override
- public AnnotationMetaAttribute visitDeclared(DeclaredType t, Element element) {
+ public AnnotationMetaAttribute visitDeclared(DeclaredType declaredType, Element element) {
//FIXME consider XML
if ( isPersistent( element ) ) {
TypeElement returnedElement = ( TypeElement ) context.getProcessingEnvironment()
.getTypeUtils()
- .asElement( t );
- String fqElementName = returnedElement.getQualifiedName()
- .toString(); // WARNING: .toString() is necessary here since Name equals does not compare to String
+ .asElement( declaredType );
+ // WARNING: .toString() is necessary here since Name equals does not compare to String
+ String fqElementName = returnedElement.getQualifiedName().toString();
String collection = COLLECTIONS.get( fqElementName );
String targetEntity = getTargetEntity( element.getAnnotationMirrors() );
if ( collection != null ) {
if ( TypeUtils.containsAnnotation( element, ElementCollection.class ) ) {
- //FIXME I don't understand why this code is different between Elementcollection and a regular collection but it needs to take targetClass into account
- TypeMirror collectionElementType = getCollectionElementType( t, fqElementName );
+ TypeMirror collectionElementType = getCollectionElementType( declaredType, fqElementName );
final TypeElement collectionElement = ( TypeElement ) context.getProcessingEnvironment()
.getTypeUtils()
.asElement( collectionElementType );
@@ -391,12 +392,16 @@
if ( collection.equals( "javax.persistence.metamodel.MapAttribute" ) ) {
return new AnnotationMetaMap(
//FIXME support targetEntity for map's key @MapKeyClass
- parent, element, collection, getKeyType( t ), getElementType( t, targetEntity )
+ parent,
+ element,
+ collection,
+ getKeyType( declaredType ),
+ getElementType( declaredType, targetEntity )
);
}
else {
return new AnnotationMetaCollection(
- parent, element, collection, getElementType( t, targetEntity )
+ parent, element, collection, getElementType( declaredType, targetEntity )
);
}
}
@@ -446,39 +451,40 @@
}
/**
+ * @param annotations list of annotation mirrors.
+ *
* @return target entity class name as string or {@code null} if no targetEntity is here or if equals to void
*/
-
private String getTargetEntity(List<? extends AnnotationMirror> annotations) {
+ String fullyQualifiedTargetEntityName = null;
for ( AnnotationMirror mirror : annotations ) {
- if ( TypeUtils.isAnnotationMirrorOfType( mirror, ElementCollection.class )
- || TypeUtils.isAnnotationMirrorOfType( mirror, OneToMany.class )
+ if ( TypeUtils.isAnnotationMirrorOfType( mirror, ElementCollection.class ) ) {
+ fullyQualifiedTargetEntityName = getFullyQualifiedClassNameOfTargetEntity( mirror, "targetClass" );
+ }
+ else if ( TypeUtils.isAnnotationMirrorOfType( mirror, OneToMany.class )
|| TypeUtils.isAnnotationMirrorOfType( mirror, ManyToMany.class )
|| TypeUtils.isAnnotationMirrorOfType( mirror, ManyToOne.class )
|| TypeUtils.isAnnotationMirrorOfType( mirror, OneToOne.class ) ) {
- final String targetEntity = getTargetEntity( mirror );
- if ( targetEntity != null ) {
- return targetEntity;
- }
+ fullyQualifiedTargetEntityName = getFullyQualifiedClassNameOfTargetEntity( mirror, "targetEntity" );
}
}
- return null;
+ return fullyQualifiedTargetEntityName;
}
- private String getTargetEntity(AnnotationMirror mirror) {
- String targetEntity = null;
- final Map<? extends ExecutableElement, ? extends AnnotationValue> attributes = mirror.getElementValues();
- for ( Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : attributes.entrySet() ) {
- final String simpleName = entry.getKey().getSimpleName().toString();
- if ( "targetEntity".equals( simpleName ) ) {
- targetEntity = entry.getValue().toString();
- break;
+ private String getFullyQualifiedClassNameOfTargetEntity(AnnotationMirror mirror, String parameterName) {
+ assert mirror != null;
+ assert parameterName != null;
+
+ String targetEntityName = null;
+ Object parameterValue = TypeUtils.getAnnotationValue( mirror, parameterName );
+ if ( parameterValue != null ) {
+ TypeMirror parameterType = ( TypeMirror ) parameterValue;
+ if ( !parameterType.getKind().equals( TypeKind.VOID ) ) {
+ targetEntityName = parameterType.toString();
}
}
- targetEntity = ( "void.class".equals( targetEntity ) ) ? null : targetEntity;
- return targetEntity != null && targetEntity.endsWith( ".class" ) ?
- targetEntity.substring( 0, targetEntity.length() - 6 ) : null;
+ return targetEntityName;
}
public String generateImports() {
Modified: jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/elementcollection/House.java
===================================================================
--- jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/elementcollection/House.java 2010-01-26 20:11:51 UTC (rev 18638)
+++ jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/elementcollection/House.java 2010-01-26 21:42:19 UTC (rev 18639)
@@ -1,4 +1,4 @@
-// $Id:$
+// $Id$
/*
* JBoss, Home of Professional Open Source
* Copyright 2009, Red Hat, Inc. and/or its affiliates, and individual contributors
@@ -29,7 +29,7 @@
public class House {
private Map<String, Room> roomsByName;
- @ElementCollection
+ @ElementCollection(targetClass = Room.class)
@MapKeyColumn(name = "room_name")
public Map<String, Room> getRoomsByName() {
return roomsByName;
15 years, 1 month
Hibernate SVN: r18638 - in core/trunk: annotations/src/test/java/org/hibernate/test/annotations/idclass/xml and 9 other directories.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2010-01-26 15:11:51 -0500 (Tue, 26 Jan 2010)
New Revision: 18638
Added:
core/trunk/testing/src/main/java/org/hibernate/junit/FailureExpected.java
core/trunk/testing/src/main/java/org/hibernate/junit/RequiresDialect.java
core/trunk/testing/src/main/java/org/hibernate/junit/SkipForDialect.java
Removed:
core/trunk/testing/src/main/java/org/hibernate/test/annotations/FailureExpected.java
core/trunk/testing/src/main/java/org/hibernate/test/annotations/RequiresDialect.java
core/trunk/testing/src/main/java/org/hibernate/test/annotations/SkipForDialect.java
Modified:
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/cid/CompositeIdTest.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/idclass/xml/IdClassXmlTest.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/idclassgeneratedvalue/IdClassGeneratedValueTest.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/indexcoll/IndexedCollectionTest.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/lob/ImageTest.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/lob/TextTest.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/manytoonewithformula/ManyToOneWithFormulaTest.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/onetomany/OneToManyTest.java
core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/callbacks/CallbacksTest.java
core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/lob/BlobTest.java
core/trunk/testing/src/main/java/org/hibernate/test/annotations/HibernateTestCase.java
Log:
HHH-4822 - Add @FailureExpected annotation to annotations and entitymananger modules to allow the skipping of tests
Modified: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/cid/CompositeIdTest.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/cid/CompositeIdTest.java 2010-01-26 19:44:57 UTC (rev 18637)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/cid/CompositeIdTest.java 2010-01-26 20:11:51 UTC (rev 18638)
@@ -9,11 +9,10 @@
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.Criteria;
-import org.hibernate.dialect.HSQLDialect;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.Restrictions;
+import org.hibernate.junit.SkipForDialect;
import org.hibernate.test.annotations.TestCase;
-import org.hibernate.test.annotations.SkipForDialect;
/**
* test some composite id functionalities
Modified: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/idclass/xml/IdClassXmlTest.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/idclass/xml/IdClassXmlTest.java 2010-01-26 19:44:57 UTC (rev 18637)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/idclass/xml/IdClassXmlTest.java 2010-01-26 20:11:51 UTC (rev 18638)
@@ -22,20 +22,17 @@
*/
package org.hibernate.test.annotations.idclass.xml;
-import org.hibernate.Query;
-import org.hibernate.Session;
-import org.hibernate.Transaction;
-import org.hibernate.test.annotations.FailureExpected;
+import org.hibernate.junit.FailureExpected;
import org.hibernate.test.annotations.TestCase;
/**
- * HHH-4282
+ * A test for HHH-4282
*
* @author Hardy Ferentschik
*/
+@FailureExpected( jiraKey = "HHH-4282" )
public class IdClassXmlTest extends TestCase {
- @FailureExpected
public void testEntityMappningPropertiesAreNotIgnored() {
throw new RuntimeException();
// Session s = openSession();
Modified: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/idclassgeneratedvalue/IdClassGeneratedValueTest.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/idclassgeneratedvalue/IdClassGeneratedValueTest.java 2010-01-26 19:44:57 UTC (rev 18637)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/idclassgeneratedvalue/IdClassGeneratedValueTest.java 2010-01-26 20:11:51 UTC (rev 18638)
@@ -27,7 +27,7 @@
import java.util.List;
import org.hibernate.Session;
-import org.hibernate.test.annotations.FailureExpected;
+import org.hibernate.junit.FailureExpected;
import org.hibernate.test.annotations.TestCase;
/**
@@ -60,7 +60,7 @@
s.close();
}
- @FailureExpected(message = "Not yet implemented", issueNumber = "HHH-4552")
+ @FailureExpected(message = "Not yet implemented", jiraKey = "HHH-4552")
@SuppressWarnings({ "unchecked" })
public void testSingleGeneratedValue() {
Session s = openSession();
@@ -85,7 +85,7 @@
s.close();
}
- @FailureExpected(message = "Not yet implemented", issueNumber = "HHH-4552")
+ @FailureExpected(message = "Not yet implemented", jiraKey = "HHH-4552")
@SuppressWarnings({ "unchecked" })
public void testMultipleGeneratedValue() {
Session s = openSession();
Modified: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/indexcoll/IndexedCollectionTest.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/indexcoll/IndexedCollectionTest.java 2010-01-26 19:44:57 UTC (rev 18637)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/indexcoll/IndexedCollectionTest.java 2010-01-26 20:11:51 UTC (rev 18638)
@@ -12,9 +12,9 @@
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.dialect.HSQLDialect;
+import org.hibernate.junit.RequiresDialect;
import org.hibernate.mapping.Collection;
import org.hibernate.mapping.Column;
-import org.hibernate.test.annotations.RequiresDialect;
import org.hibernate.test.annotations.TestCase;
/**
Modified: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/lob/ImageTest.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/lob/ImageTest.java 2010-01-26 19:44:57 UTC (rev 18637)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/lob/ImageTest.java 2010-01-26 20:11:51 UTC (rev 18638)
@@ -32,7 +32,7 @@
import org.hibernate.dialect.Sybase11Dialect;
import org.hibernate.dialect.SybaseASE15Dialect;
import org.hibernate.dialect.SybaseDialect;
-import org.hibernate.test.annotations.RequiresDialect;
+import org.hibernate.junit.RequiresDialect;
import org.hibernate.test.annotations.TestCase;
import org.hibernate.util.ArrayHelper;
Modified: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/lob/TextTest.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/lob/TextTest.java 2010-01-26 19:44:57 UTC (rev 18637)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/lob/TextTest.java 2010-01-26 20:11:51 UTC (rev 18638)
@@ -32,7 +32,7 @@
import org.hibernate.dialect.Sybase11Dialect;
import org.hibernate.dialect.SybaseASE15Dialect;
import org.hibernate.dialect.SybaseDialect;
-import org.hibernate.test.annotations.RequiresDialect;
+import org.hibernate.junit.RequiresDialect;
import org.hibernate.test.annotations.TestCase;
import org.hibernate.util.ArrayHelper;
Modified: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/manytoonewithformula/ManyToOneWithFormulaTest.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/manytoonewithformula/ManyToOneWithFormulaTest.java 2010-01-26 19:44:57 UTC (rev 18637)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/manytoonewithformula/ManyToOneWithFormulaTest.java 2010-01-26 20:11:51 UTC (rev 18638)
@@ -29,7 +29,7 @@
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.dialect.HSQLDialect;
-import org.hibernate.test.annotations.SkipForDialect;
+import org.hibernate.junit.SkipForDialect;
import org.hibernate.test.annotations.TestCase;
/**
Modified: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/onetomany/OneToManyTest.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/onetomany/OneToManyTest.java 2010-01-26 19:44:57 UTC (rev 18637)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/onetomany/OneToManyTest.java 2010-01-26 20:11:51 UTC (rev 18638)
@@ -12,11 +12,9 @@
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
-import org.hibernate.dialect.HSQLDialect;
import org.hibernate.test.annotations.Customer;
import org.hibernate.test.annotations.Discount;
import org.hibernate.test.annotations.Passport;
-import org.hibernate.test.annotations.RequiresDialect;
import org.hibernate.test.annotations.TestCase;
import org.hibernate.test.annotations.Ticket;
import org.hibernate.test.annotations.TicketComparator;
Modified: core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/callbacks/CallbacksTest.java
===================================================================
--- core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/callbacks/CallbacksTest.java 2010-01-26 19:44:57 UTC (rev 18637)
+++ core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/callbacks/CallbacksTest.java 2010-01-26 20:11:51 UTC (rev 18638)
@@ -10,7 +10,7 @@
import org.hibernate.ejb.test.Cat;
import org.hibernate.ejb.test.Kitten;
import org.hibernate.ejb.test.TestCase;
-import org.hibernate.test.annotations.FailureExpected;
+import org.hibernate.junit.FailureExpected;
/**
* @author Emmanuel Bernard
@@ -168,7 +168,7 @@
em.close();
}
- @FailureExpected(message = "collection change does not trigger an event", issueNumber = "EJB-288")
+ @FailureExpected(message = "collection change does not trigger an event", jiraKey = "EJB-288")
public void testPostUpdateCollection() throws Exception {
// create a cat
EntityManager em = getOrCreateEntityManager();
Modified: core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/lob/BlobTest.java
===================================================================
--- core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/lob/BlobTest.java 2010-01-26 19:44:57 UTC (rev 18637)
+++ core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/lob/BlobTest.java 2010-01-26 20:11:51 UTC (rev 18638)
@@ -12,7 +12,6 @@
import org.hibernate.Hibernate;
import org.hibernate.dialect.Dialect;
import org.hibernate.ejb.test.TestCase;
-import org.hibernate.test.annotations.FailureExpected;
/**
* @author Emmanuel Bernard
Copied: core/trunk/testing/src/main/java/org/hibernate/junit/FailureExpected.java (from rev 18636, core/trunk/testing/src/main/java/org/hibernate/test/annotations/FailureExpected.java)
===================================================================
--- core/trunk/testing/src/main/java/org/hibernate/junit/FailureExpected.java (rev 0)
+++ core/trunk/testing/src/main/java/org/hibernate/junit/FailureExpected.java 2010-01-26 20:11:51 UTC (rev 18638)
@@ -0,0 +1,51 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2010, Red Hat Inc. or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.junit;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Annotations used to mark a test as an expected failure.
+ *
+ * @author Hardy Ferentschik
+ * @author Steve Ebersole
+ */
+(a)Retention(RetentionPolicy.RUNTIME)
+@Target({ ElementType.METHOD, ElementType.TYPE })
+public @interface FailureExpected {
+ /**
+ * The key of a JIRA issue which covers this expected failure.
+ * @return The jira issue key
+ */
+ String jiraKey();
+
+ /**
+ * A message explaining the reason for the expected failure. Optional.
+ * @return The reason
+ */
+ String message() default "";
+}
\ No newline at end of file
Property changes on: core/trunk/testing/src/main/java/org/hibernate/junit/FailureExpected.java
___________________________________________________________________
Name: svn:keywords
+ Id
Name: svn:eol-style
+ native
Copied: core/trunk/testing/src/main/java/org/hibernate/junit/RequiresDialect.java (from rev 18636, core/trunk/testing/src/main/java/org/hibernate/test/annotations/RequiresDialect.java)
===================================================================
--- core/trunk/testing/src/main/java/org/hibernate/junit/RequiresDialect.java (rev 0)
+++ core/trunk/testing/src/main/java/org/hibernate/junit/RequiresDialect.java 2010-01-26 20:11:51 UTC (rev 18638)
@@ -0,0 +1,54 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2010, Red Hat Inc. or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.junit;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+import org.hibernate.dialect.Dialect;
+
+/**
+ * Annotation used to indicate that a test should be run only when run against the
+ * indicated dialects.
+ *
+ * @author Hardy Ferentschik
+ */
+(a)Target({ElementType.METHOD, ElementType.TYPE})
+(a)Retention(RetentionPolicy.RUNTIME)
+public @interface RequiresDialect {
+ /**
+ * The dialects against which to run the test
+ * @return The dialects
+ */
+ Class<? extends Dialect>[] value();
+
+ /**
+ * Used to indicate if the dialects should be matched strictly (classes equal) or
+ * non-strictly (instanceof).
+ * @return Should strict matching be used?
+ */
+ boolean strictMatching() default false;
+}
Property changes on: core/trunk/testing/src/main/java/org/hibernate/junit/RequiresDialect.java
___________________________________________________________________
Name: svn:keywords
+ Id
Name: svn:eol-style
+ native
Copied: core/trunk/testing/src/main/java/org/hibernate/junit/SkipForDialect.java (from rev 18636, core/trunk/testing/src/main/java/org/hibernate/test/annotations/SkipForDialect.java)
===================================================================
--- core/trunk/testing/src/main/java/org/hibernate/junit/SkipForDialect.java (rev 0)
+++ core/trunk/testing/src/main/java/org/hibernate/junit/SkipForDialect.java 2010-01-26 20:11:51 UTC (rev 18638)
@@ -0,0 +1,68 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2010, Red Hat Inc. or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.junit;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+import org.hibernate.dialect.Dialect;
+
+/**
+ * Annotation used to indicate that a test should be skipped when run against the
+ * indicated dialects.
+ *
+ * @author Hardy Ferentschik
+ * @author Steve Ebersole
+ */
+(a)Retention(RetentionPolicy.RUNTIME)
+@Target({ ElementType.METHOD, ElementType.TYPE })
+public @interface SkipForDialect {
+ /**
+ * The dialects against which to skip the test
+ * @return The dialects
+ */
+ Class<? extends Dialect>[] value();
+
+ /**
+ * Used to indicate if the dialects should be matched strictly (classes equal) or
+ * non-strictly (instanceof).
+ * @return Should strict matching be used?
+ */
+ boolean strictMatching() default false;
+
+ /**
+ * Comment describing the reason for the skip.
+ * @return The comment
+ */
+ String comment() default "";
+
+ /**
+ * The key of a JIRA issue which covers the reason for this skip. Eventually we should make this
+ * a requirement.
+ * @return The jira issue key
+ */
+ String jiraKey() default "";
+}
\ No newline at end of file
Property changes on: core/trunk/testing/src/main/java/org/hibernate/junit/SkipForDialect.java
___________________________________________________________________
Name: svn:keywords
+ Id
Name: svn:eol-style
+ native
Deleted: core/trunk/testing/src/main/java/org/hibernate/test/annotations/FailureExpected.java
===================================================================
--- core/trunk/testing/src/main/java/org/hibernate/test/annotations/FailureExpected.java 2010-01-26 19:44:57 UTC (rev 18637)
+++ core/trunk/testing/src/main/java/org/hibernate/test/annotations/FailureExpected.java 2010-01-26 20:11:51 UTC (rev 18638)
@@ -1,42 +0,0 @@
-// $Id$
-/*
- * Hibernate, Relational Persistence for Idiomatic Java
- *
- * Copyright (c) 2010, Red Hat Inc. or third-party contributors as
- * indicated by the @author tags or express copyright attribution
- * statements applied by the authors. All third-party contributions are
- * distributed under license by Red Hat Inc.
- *
- * This copyrighted material is made available to anyone wishing to use, modify,
- * copy, or redistribute it subject to the terms and conditions of the GNU
- * Lesser General Public License, as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
- * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
- * for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this distribution; if not, write to:
- * Free Software Foundation, Inc.
- * 51 Franklin Street, Fifth Floor
- * Boston, MA 02110-1301 USA
- */
-package org.hibernate.test.annotations;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * Annotations used to mark a expected test failure.
- *
- * @author Hardy Ferentschik
- */
-@Target({ ElementType.METHOD, ElementType.TYPE })
-(a)Retention(RetentionPolicy.RUNTIME)
-public @interface FailureExpected {
- String message() default "";
- String issueNumber() default "";
-}
\ No newline at end of file
Modified: core/trunk/testing/src/main/java/org/hibernate/test/annotations/HibernateTestCase.java
===================================================================
--- core/trunk/testing/src/main/java/org/hibernate/test/annotations/HibernateTestCase.java 2010-01-26 19:44:57 UTC (rev 18637)
+++ core/trunk/testing/src/main/java/org/hibernate/test/annotations/HibernateTestCase.java 2010-01-26 20:11:51 UTC (rev 18638)
@@ -1,4 +1,3 @@
-// $Id:$
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
@@ -24,6 +23,7 @@
*/
package org.hibernate.test.annotations;
+import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
@@ -40,6 +40,9 @@
import org.hibernate.cfg.Configuration;
import org.hibernate.dialect.Dialect;
import org.hibernate.jdbc.Work;
+import org.hibernate.junit.FailureExpected;
+import org.hibernate.junit.RequiresDialect;
+import org.hibernate.junit.SkipForDialect;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.util.StringHelper;
@@ -58,11 +61,6 @@
/**
- * The test method.
- */
- private Method runMethod = null;
-
- /**
* Flag indicating whether the test should be run or skipped.
*/
private boolean runTest = true;
@@ -87,80 +85,164 @@
}
@Override
- protected void setUp() throws Exception {
- runMethod = findTestMethod();
- setRunTestFlag( runMethod );
- if ( runTest ) {
- if ( cfg == null || lastTestClass != getClass() ) {
- buildConfiguration();
- lastTestClass = getClass();
+ public void runBare() throws Throwable {
+ Method runMethod = findTestMethod();
+
+ final Skip skip = determineSkipByDialect( Dialect.getDialect(), runMethod );
+ if ( skip != null ) {
+ reportSkip( skip );
+ return;
+ }
+
+ setUp();
+ try {
+ runTest();
+ }
+ finally {
+ tearDown();
+ }
+ }
+
+ @Override
+ protected void runTest() throws Throwable {
+ Method runMethod = findTestMethod();
+ FailureExpected failureExpected = locateAnnotation( FailureExpected.class, runMethod );
+ try {
+ super.runTest();
+ if ( failureExpected != null ) {
+ throw new FailureExpectedTestPassedException();
}
+ }
+ catch ( FailureExpectedTestPassedException t ) {
+ closeResources();
+ throw t;
+ }
+ catch ( Throwable t ) {
+ if ( t instanceof InvocationTargetException ) {
+ t = ( ( InvocationTargetException ) t ).getTargetException();
+ }
+ if ( t instanceof IllegalAccessException ) {
+ t.fillInStackTrace();
+ }
+ closeResources();
+ if ( failureExpected != null) {
+ StringBuilder builder = new StringBuilder();
+ if ( StringHelper.isNotEmpty( failureExpected.message() ) ) {
+ builder.append( failureExpected.message() );
+ }
+ else {
+ builder.append( "ignoring @FailureExpected test" );
+ }
+ builder.append( " (" )
+ .append( failureExpected.jiraKey() )
+ .append( ")" );
+ reportSkip( "Failed with: " + t.toString(), builder.toString() );
+ }
else {
- runSchemaGeneration();
+ throw t;
}
}
}
@Override
+ protected void setUp() throws Exception {
+ if ( cfg == null || lastTestClass != getClass() ) {
+ buildConfiguration();
+ lastTestClass = getClass();
+ }
+ else {
+ runSchemaGeneration();
+ }
+ }
+
+ @Override
protected void tearDown() throws Exception {
runSchemaDrop();
handleUnclosedResources();
}
- protected void runTest() throws Throwable {
- if ( runTest ) {
- runTestMethod( runMethod );
+ protected static class Skip {
+ private final String reason;
+ private final String testDescription;
+
+ public Skip(String reason, String testDescription) {
+ this.reason = reason;
+ this.testDescription = testDescription;
}
}
- private void setRunTestFlag(Method runMethod) {
- updateRequiredDialectList( runMethod );
- updateSkipForDialectList( runMethod );
+ protected final Skip determineSkipByDialect(Dialect dialect, Method runMethod) {
+ // skips have precedence, so check them first
+ SkipForDialect skipForDialectAnn = locateAnnotation( SkipForDialect.class, runMethod );
+ if ( skipForDialectAnn != null ) {
+ for ( Class<? extends Dialect> dialectClass : skipForDialectAnn.value() ) {
+ if ( skipForDialectAnn.strictMatching() ) {
+ if ( dialectClass.equals( dialect.getClass() ) ) {
+ return buildSkip( dialect, skipForDialectAnn.comment(), skipForDialectAnn.jiraKey() );
+ }
+ }
+ else {
+ if ( dialectClass.isInstance( dialect ) ) {
+ return buildSkip( dialect, skipForDialectAnn.comment(), skipForDialectAnn.jiraKey() );
+ }
+ }
+ }
+ }
- if ( runForCurrentDialect() ) {
- runTest = true;
+ // then check against the requires
+ RequiresDialect requiresDialectAnn = locateAnnotation( RequiresDialect.class, runMethod );
+ if ( requiresDialectAnn != null ) {
+ for ( Class<? extends Dialect> dialectClass : requiresDialectAnn.value() ) {
+ if ( requiresDialectAnn.strictMatching() ) {
+ if ( dialectClass.equals( dialect.getClass() ) ) {
+ return buildSkip( dialect, null, null );
+ }
+ }
+ else {
+ if ( dialectClass.isInstance( dialect ) ) {
+ return buildSkip( dialect, null, null );
+ }
+ }
+ }
}
- else {
- log.warn(
- "Skipping test {}, because test does not apply for dialect {}", runMethod.getName(), Dialect
- .getDialect().getClass()
- );
- runTest = false;
- }
+
+ return null;
}
- private void updateRequiredDialectList(Method runMethod) {
- requiredDialectList.clear();
-
- RequiresDialect requiresDialectMethodAnn = runMethod.getAnnotation( RequiresDialect.class );
- if ( requiresDialectMethodAnn != null ) {
- Class<? extends Dialect>[] requiredDialects = requiresDialectMethodAnn.value();
- requiredDialectList.addAll( Arrays.asList( requiredDialects ) );
+ protected <T extends Annotation> T locateAnnotation(Class<T> annotationClass, Method runMethod) {
+ T annotation = runMethod.getAnnotation( annotationClass );
+ if ( annotation == null ) {
+ annotation = getClass().getAnnotation( annotationClass );
}
-
- RequiresDialect requiresDialectClassAnn = getClass().getAnnotation( RequiresDialect.class );
- if ( requiresDialectClassAnn != null ) {
- Class<? extends Dialect>[] requiredDialects = requiresDialectClassAnn.value();
- requiredDialectList.addAll( Arrays.asList( requiredDialects ) );
+ if ( annotation == null ) {
+ annotation = runMethod.getDeclaringClass().getAnnotation( annotationClass );
}
+ return annotation;
}
- private void updateSkipForDialectList(Method runMethod) {
- skipForDialectList.clear();
+ protected Skip buildSkip(Dialect dialect, String comment, String jiraKey) {
+ StringBuilder buffer = new StringBuilder();
+ buffer.append( "skipping database-specific test [" );
+ buffer.append( fullTestName() );
+ buffer.append( "] for dialect [" );
+ buffer.append( dialect.getClass().getName() );
+ buffer.append( ']' );
- SkipForDialect skipForDialectMethodAnn = runMethod.getAnnotation( SkipForDialect.class );
- if ( skipForDialectMethodAnn != null ) {
- Class<? extends Dialect>[] skipDialects = skipForDialectMethodAnn.value();
- skipForDialectList.addAll( Arrays.asList( skipDialects ) );
+ if ( StringHelper.isNotEmpty( comment ) ) {
+ buffer.append( "; " ).append( comment );
}
- SkipForDialect skipForDialectClassAnn = getClass().getAnnotation( SkipForDialect.class );
- if ( skipForDialectClassAnn != null ) {
- Class<? extends Dialect>[] skipDialects = skipForDialectClassAnn.value();
- skipForDialectList.addAll( Arrays.asList( skipDialects ) );
+ if ( StringHelper.isNotEmpty( jiraKey ) ) {
+ buffer.append( " (" ).append( jiraKey ).append( ')' );
}
+
+ return new Skip( buffer.toString(), null );
}
+ public String fullTestName() {
+ return this.getClass().getName() + "#" + this.getName();
+ }
+
protected boolean runForCurrentDialect() {
boolean runTestForCurrentDialect = true;
@@ -185,48 +267,6 @@
return runTestForCurrentDialect;
}
- private void runTestMethod(Method runMethod) throws Throwable {
- boolean failureExpected = runMethod.getAnnotation( FailureExpected.class ) != null;
- try {
- runMethod.invoke( this, new Class[0] );
- if ( failureExpected ) {
- throw new FailureExpectedTestPassedException();
- }
- }
- catch ( FailureExpectedTestPassedException t ) {
- closeResources();
- throw t;
- }
- catch ( Throwable t ) {
- if ( t instanceof InvocationTargetException ) {
- t = ( ( InvocationTargetException ) t ).getTargetException();
- }
- if ( t instanceof IllegalAccessException ) {
- t.fillInStackTrace();
- }
- closeResources();
- if ( failureExpected ) {
- FailureExpected ann = runMethod.getAnnotation( FailureExpected.class );
- StringBuilder builder = new StringBuilder();
- if ( StringHelper.isNotEmpty( ann.message() ) ) {
- builder.append( ann.message() );
- }
- else {
- builder.append( "ignoring test methods annoated with @FailureExpected" );
- }
- if ( StringHelper.isNotEmpty( ann.issueNumber() ) ) {
- builder.append( " (" );
- builder.append( ann.issueNumber() );
- builder.append( ")" );
- }
- reportSkip( builder.toString(), "Failed with: " + t.toString() );
- }
- else {
- throw t;
- }
- }
- }
-
private Method findTestMethod() {
String fName = getName();
assertNotNull( fName );
@@ -288,12 +328,14 @@
export.drop( true, true );
}
+ private void reportSkip(Skip skip) {
+ reportSkip( skip.reason, skip.testDescription );
+ }
+
protected void reportSkip(String reason, String testDescription) {
StringBuilder builder = new StringBuilder();
builder.append( "*** skipping test [" );
- builder.append( runMethod.getDeclaringClass().getName() );
- builder.append( "." );
- builder.append( runMethod.getName() );
+ builder.append( fullTestName() );
builder.append( "] - " );
builder.append( testDescription );
builder.append( " : " );
Deleted: core/trunk/testing/src/main/java/org/hibernate/test/annotations/RequiresDialect.java
===================================================================
--- core/trunk/testing/src/main/java/org/hibernate/test/annotations/RequiresDialect.java 2010-01-26 19:44:57 UTC (rev 18637)
+++ core/trunk/testing/src/main/java/org/hibernate/test/annotations/RequiresDialect.java 2010-01-26 20:11:51 UTC (rev 18638)
@@ -1,43 +0,0 @@
-// $Id$
-/*
- * Hibernate, Relational Persistence for Idiomatic Java
- *
- * Copyright (c) 2010, Red Hat Inc. or third-party contributors as
- * indicated by the @author tags or express copyright attribution
- * statements applied by the authors. All third-party contributions are
- * distributed under license by Red Hat Inc.
- *
- * This copyrighted material is made available to anyone wishing to use, modify,
- * copy, or redistribute it subject to the terms and conditions of the GNU
- * Lesser General Public License, as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
- * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
- * for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this distribution; if not, write to:
- * Free Software Foundation, Inc.
- * 51 Franklin Street, Fifth Floor
- * Boston, MA 02110-1301 USA
- */
-package org.hibernate.test.annotations;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-import org.hibernate.dialect.Dialect;
-
-/**
- * Annotations used to mark a test to be specific to a given dialect.
- *
- * @author Hardy Ferentschik
- */
-(a)Target({ElementType.METHOD, ElementType.TYPE})
-(a)Retention(RetentionPolicy.RUNTIME)
-public @interface RequiresDialect {
- Class<? extends Dialect>[] value();
-}
Deleted: core/trunk/testing/src/main/java/org/hibernate/test/annotations/SkipForDialect.java
===================================================================
--- core/trunk/testing/src/main/java/org/hibernate/test/annotations/SkipForDialect.java 2010-01-26 19:44:57 UTC (rev 18637)
+++ core/trunk/testing/src/main/java/org/hibernate/test/annotations/SkipForDialect.java 2010-01-26 20:11:51 UTC (rev 18638)
@@ -1,45 +0,0 @@
-// $Id$
-/*
- * Hibernate, Relational Persistence for Idiomatic Java
- *
- * Copyright (c) 2010, Red Hat Inc. or third-party contributors as
- * indicated by the @author tags or express copyright attribution
- * statements applied by the authors. All third-party contributions are
- * distributed under license by Red Hat Inc.
- *
- * This copyrighted material is made available to anyone wishing to use, modify,
- * copy, or redistribute it subject to the terms and conditions of the GNU
- * Lesser General Public License, as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
- * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
- * for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this distribution; if not, write to:
- * Free Software Foundation, Inc.
- * 51 Franklin Street, Fifth Floor
- * Boston, MA 02110-1301 USA
- */
-package org.hibernate.test.annotations;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-import org.hibernate.dialect.Dialect;
-
-/**
- * Annotations used to mark a test to be specific to a given dialect.
- *
- * @author Hardy Ferentschik
- */
-@Target({ ElementType.METHOD, ElementType.TYPE })
-(a)Retention(RetentionPolicy.RUNTIME)
-public @interface SkipForDialect {
- Class<? extends Dialect>[] value();
-
- String comment();
-}
\ No newline at end of file
15 years, 1 month
Hibernate SVN: r18637 - core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/lob.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2010-01-26 14:44:57 -0500 (Tue, 26 Jan 2010)
New Revision: 18637
Modified:
core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/lob/BlobTest.java
Log:
HHH-4822 reverted a test which was accidently marked with @FailureExpected
Modified: core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/lob/BlobTest.java
===================================================================
--- core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/lob/BlobTest.java 2010-01-26 18:36:59 UTC (rev 18636)
+++ core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/lob/BlobTest.java 2010-01-26 19:44:57 UTC (rev 18637)
@@ -19,30 +19,28 @@
*/
public class BlobTest extends TestCase {
- @FailureExpected
public void testBlobSerialization() throws Exception {
- throw new RuntimeException( );
-// EntityManager em = getOrCreateEntityManager();
-// em.getTransaction().begin();
-// Map<String,String> image = new HashMap<String, String>();
-// image.put( "meta", "metadata" );
-// image.put( "data", "imagedata" );
-// ImageReader reader = new ImageReader();
-// ByteArrayOutputStream baos = new ByteArrayOutputStream();
-// ObjectOutputStream oos = new ObjectOutputStream( baos );
-// oos.writeObject( image );
-// reader.setImage( (Blob) Hibernate.createBlob( baos.toByteArray() ) );
-// em.persist( reader );
-// em.getTransaction().commit();
-// em.close(); //useless but y'a know
-// em = getOrCreateEntityManager();
-// em.getTransaction().begin();
-// reader = em.find( ImageReader.class, reader.getId() );
-// ObjectInputStream ois = new ObjectInputStream( reader.getImage().getBinaryStream() );
-// image = (HashMap<String, String>) ois.readObject();
-// assertTrue( image.containsKey( "meta" ) );
-// em.getTransaction().commit();
-// em.close();
+ EntityManager em = getOrCreateEntityManager();
+ em.getTransaction().begin();
+ Map<String,String> image = new HashMap<String, String>();
+ image.put( "meta", "metadata" );
+ image.put( "data", "imagedata" );
+ ImageReader reader = new ImageReader();
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ ObjectOutputStream oos = new ObjectOutputStream( baos );
+ oos.writeObject( image );
+ reader.setImage( (Blob) Hibernate.createBlob( baos.toByteArray() ) );
+ em.persist( reader );
+ em.getTransaction().commit();
+ em.close(); //useless but y'a know
+ em = getOrCreateEntityManager();
+ em.getTransaction().begin();
+ reader = em.find( ImageReader.class, reader.getId() );
+ ObjectInputStream ois = new ObjectInputStream( reader.getImage().getBinaryStream() );
+ image = (HashMap<String, String>) ois.readObject();
+ assertTrue( image.containsKey( "meta" ) );
+ em.getTransaction().commit();
+ em.close();
}
@Override
15 years, 1 month
Hibernate SVN: r18636 - in core/trunk: entitymanager/src/main/java/org/hibernate/ejb and 1 other directories.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2010-01-26 13:36:59 -0500 (Tue, 26 Jan 2010)
New Revision: 18636
Added:
core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/ejb3configuration/ConfigurationObjectSettingTest.java
core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/ejb3configuration/PersistenceUnitInfoAdapter.java
Modified:
core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationBinder.java
core/trunk/entitymanager/src/main/java/org/hibernate/ejb/AvailableSettings.java
core/trunk/entitymanager/src/main/java/org/hibernate/ejb/Ejb3Configuration.java
core/trunk/entitymanager/src/main/java/org/hibernate/ejb/HibernatePersistence.java
Log:
HHH-4678 - Apply PersistenceUnitInfo#getSharedCacheMode and #getValidationMode
Modified: core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationBinder.java
===================================================================
--- core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationBinder.java 2010-01-26 18:06:40 UTC (rev 18635)
+++ core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationBinder.java 2010-01-26 18:36:59 UTC (rev 18636)
@@ -769,12 +769,7 @@
}
Cacheable cacheableAnn = clazzToProcess.getAnnotation( Cacheable.class );
- SharedCacheMode mode = (SharedCacheMode) mappings.getConfigurationProperties().get(
- "javax.persistence.sharedCache.mode"
- );
- if ( mode == null ) {
- mode = SharedCacheMode.UNSPECIFIED;
- }
+ SharedCacheMode mode = determineSharedCacheMode( mappings );
switch ( mode ) {
case ALL: {
cacheAnn = buildCacheMock( clazzToProcess.getName(), mappings );
@@ -800,6 +795,33 @@
return cacheAnn;
}
+ private static SharedCacheMode determineSharedCacheMode(ExtendedMappings mappings) {
+ SharedCacheMode mode;
+ final Object value = mappings.getConfigurationProperties().get( "javax.persistence.sharedCache.mode" );
+ if ( value == null ) {
+ log.debug( "no value specified for 'javax.persistence.sharedCache.mode'; using UNSPECIFIED" );
+ mode = SharedCacheMode.UNSPECIFIED;
+ }
+ else {
+ if ( SharedCacheMode.class.isInstance( value ) ) {
+ mode = ( SharedCacheMode ) value;
+ }
+ else {
+ try {
+ mode = SharedCacheMode.valueOf( value.toString() );
+ }
+ catch ( Exception e ) {
+ log.debug(
+ "Unable to resolve given mode name [" + value.toString()
+ + "]; using UNSPECIFIED : " + e.toString()
+ );
+ mode = SharedCacheMode.UNSPECIFIED;
+ }
+ }
+ }
+ return mode;
+ }
+
private static Cache buildCacheMock(String region, ExtendedMappings mappings) {
return new LocalCacheAnnotationImpl( region, determineCacheConcurrencyStrategy( mappings ) );
}
Modified: core/trunk/entitymanager/src/main/java/org/hibernate/ejb/AvailableSettings.java
===================================================================
--- core/trunk/entitymanager/src/main/java/org/hibernate/ejb/AvailableSettings.java 2010-01-26 18:06:40 UTC (rev 18635)
+++ core/trunk/entitymanager/src/main/java/org/hibernate/ejb/AvailableSettings.java 2010-01-26 18:36:59 UTC (rev 18636)
@@ -147,6 +147,11 @@
public static final String VALIDATION_MODE = "javax.persistence.validation.mode";
/**
+ * Used to pass along any discovered validator factory.
+ */
+ public static final String VALIDATION_FACTORY = "javax.persistence.validation.factory";
+
+ /**
* Used to request (hint) a pessimistic lock scope.
* <p/>
* See JPA 2 sections 8.2.1.9 and 3.4.4.3
Modified: core/trunk/entitymanager/src/main/java/org/hibernate/ejb/Ejb3Configuration.java
===================================================================
--- core/trunk/entitymanager/src/main/java/org/hibernate/ejb/Ejb3Configuration.java 2010-01-26 18:06:40 UTC (rev 18635)
+++ core/trunk/entitymanager/src/main/java/org/hibernate/ejb/Ejb3Configuration.java 2010-01-26 18:36:59 UTC (rev 18636)
@@ -54,6 +54,7 @@
import javax.persistence.EntityNotFoundException;
import javax.persistence.MappedSuperclass;
import javax.persistence.PersistenceException;
+import javax.persistence.SharedCacheMode;
import javax.persistence.spi.PersistenceUnitInfo;
import javax.persistence.spi.PersistenceUnitTransactionType;
import javax.sql.DataSource;
@@ -161,6 +162,7 @@
* If used, be sure to <b>not override</b> the hibernate.connection.provider_class
* property
*/
+ @SuppressWarnings({ "JavaDoc", "unchecked" })
public void setDataSource(DataSource ds) {
if ( ds != null ) {
Map cpInjection = new HashMap();
@@ -173,10 +175,23 @@
/**
* create a factory from a parsed persistence.xml
* Especially the scanning of classes and additional jars is done already at this point.
+ * <p/>
+ * NOTE: public only for unit testing purposes; not a public API!
+ *
+ * @param metadata The information parsed from the persistence.xml
+ * @param overridesIn Any explicitly passed config settings
+ *
+ * @return this
*/
- private Ejb3Configuration configure(PersistenceMetadata metadata, Map overrides) {
+ @SuppressWarnings({ "unchecked" })
+ public Ejb3Configuration configure(PersistenceMetadata metadata, Map overridesIn) {
log.debug( "Creating Factory: {}", metadata.getName() );
+ Map overrides = new HashMap();
+ if ( overridesIn != null ) {
+ overrides.putAll( overridesIn );
+ }
+
Map workingVars = new HashMap();
workingVars.put( AvailableSettings.PERSISTENCE_UNIT_NAME, metadata.getName() );
this.persistenceUnitName = metadata.getName();
@@ -218,20 +233,46 @@
if ( metadata.getHbmfiles().size() > 0 ) {
workingVars.put( AvailableSettings.HBXML_FILES, metadata.getHbmfiles() );
}
- if ( metadata.getValidationMode() != null) {
- workingVars.put( AvailableSettings.VALIDATION_MODE, metadata.getValidationMode() );
- }
- if ( metadata.getSharedCacheMode() != null) {
- workingVars.put( AvailableSettings.SHARED_CACHE_MODE, metadata.getSharedCacheMode() );
- }
+
Properties props = new Properties();
props.putAll( metadata.getProps() );
- if ( overrides != null ) {
- for ( Map.Entry entry : (Set<Map.Entry>) overrides.entrySet() ) {
- Object value = entry.getValue();
- props.put( entry.getKey(), value == null ? "" : value ); //alter null, not allowed in properties
+
+ // validation factory
+ final Object validationFactory = overrides.get( AvailableSettings.VALIDATION_FACTORY );
+ if ( validationFactory != null ) {
+ props.put( AvailableSettings.VALIDATION_FACTORY, validationFactory );
+ }
+ overrides.remove( AvailableSettings.VALIDATION_FACTORY );
+
+ // validation-mode (overrides has precedence)
+ {
+ final Object integrationValue = overrides.get( AvailableSettings.VALIDATION_MODE );
+ if ( integrationValue != null ) {
+ props.put( AvailableSettings.VALIDATION_MODE, integrationValue.toString() );
}
+ else if ( metadata.getValidationMode() != null ) {
+ props.put( AvailableSettings.VALIDATION_MODE, metadata.getValidationMode() );
+ }
+ overrides.remove( AvailableSettings.VALIDATION_MODE );
}
+
+ // shared-cache-mode (overrides has precedence)
+ {
+ final Object integrationValue = overrides.get( AvailableSettings.SHARED_CACHE_MODE );
+ if ( integrationValue != null ) {
+ props.put( AvailableSettings.SHARED_CACHE_MODE, integrationValue.toString() );
+ }
+ else if ( metadata.getSharedCacheMode() != null ) {
+ props.put( AvailableSettings.SHARED_CACHE_MODE, metadata.getSharedCacheMode() );
+ }
+ overrides.remove( AvailableSettings.SHARED_CACHE_MODE );
+ }
+
+ for ( Map.Entry entry : (Set<Map.Entry>) overrides.entrySet() ) {
+ Object value = entry.getValue();
+ props.put( entry.getKey(), value == null ? "" : value ); //alter null, not allowed in properties
+ }
+
configure( props, workingVars );
return this;
}
@@ -246,8 +287,12 @@
*
* @param persistenceUnitName persistence unit name
* @param integration properties passed to the persistence provider
+ *
* @return configured Ejb3Configuration or null if no persistence unit match
+ *
+ * @see HibernatePersistence#createEntityManagerFactory(String, java.util.Map)
*/
+ @SuppressWarnings({ "unchecked" })
public Ejb3Configuration configure(String persistenceUnitName, Map integration) {
try {
log.debug( "Look up for persistence unit: {}", persistenceUnitName );
@@ -416,9 +461,18 @@
}
/**
- * Process configuration from a PersistenceUnitInfo object
- * Typically called by the container
+ * Process configuration from a PersistenceUnitInfo object; typically called by the container
+ * via {@link javax.persistence.spi.PersistenceProvider#createContainerEntityManagerFactory}.
+ * In Hibernate EM, this correlates to {@link HibernatePersistence#createContainerEntityManagerFactory}
+ *
+ * @param info The persistence unit info passed in by the container (usually from processing a persistence.xml).
+ * @param integration The map of integration properties from the container to configure the provider.
+ *
+ * @return The configured EJB3Configurartion object
+ *
+ * @see HibernatePersistence#createContainerEntityManagerFactory
*/
+ @SuppressWarnings({ "unchecked" })
public Ejb3Configuration configure(PersistenceUnitInfo info, Map integration) {
if ( log.isDebugEnabled() ) {
log.debug( "Processing {}", LogHelper.logPersistenceUnitInfo( info ) );
@@ -427,19 +481,26 @@
log.info( "Processing PersistenceUnitInfo [\n\tname: {}\n\t...]", info.getPersistenceUnitName() );
}
+ // Spec says the passed map may be null, so handle that to make further processing easier...
integration = integration != null ? Collections.unmodifiableMap( integration ) : CollectionHelper.EMPTY_MAP;
+
+ // See if we (Hibernate) are the persistence provider
String provider = (String) integration.get( AvailableSettings.PROVIDER );
- if ( provider == null ) provider = info.getPersistenceProviderClassName();
+ if ( provider == null ) {
+ provider = info.getPersistenceProviderClassName();
+ }
if ( provider != null && ! provider.trim().startsWith( IMPLEMENTATION_NAME ) ) {
log.info( "Required a different provider: {}", provider );
return null;
}
+
+ // set the classloader, passed in by the container in info, to set as the TCCL so that
+ // Hibernate uses it to properly resolve class references.
if ( info.getClassLoader() == null ) {
throw new IllegalStateException(
"[PersistenceUnit: " + info.getPersistenceUnitName() == null ? "" : info.getPersistenceUnitName()
+ "] " + "PersistenceUnitInfo.getClassLoader() id null" );
}
- //set the classloader
Thread thread = Thread.currentThread();
ClassLoader contextClassLoader = thread.getContextClassLoader();
boolean sameClassLoader = info.getClassLoader().equals( contextClassLoader );
@@ -451,6 +512,10 @@
overridenClassLoader = null;
}
+ // Best I can tell, 'workingVars' is some form of additional configuration contract.
+ // But it does not correlate 1-1 to EMF/SF settings. It really is like a set of de-typed
+ // additional configuration info. I think it makes better sense to define this as an actual
+ // contract if that was in fact the intent; the code here is pretty confusing.
try {
Map workingVars = new HashMap();
workingVars.put( AvailableSettings.PERSISTENCE_UNIT_NAME, info.getPersistenceUnitName() );
@@ -460,7 +525,9 @@
List<NamedInputStream> hbmFiles = new ArrayList<NamedInputStream>();
List<String> packages = new ArrayList<String>();
List<String> xmlFiles = new ArrayList<String>( 50 );
- if ( info.getMappingFileNames() != null ) xmlFiles.addAll( info.getMappingFileNames() );
+ if ( info.getMappingFileNames() != null ) {
+ xmlFiles.addAll( info.getMappingFileNames() );
+ }
//Should always be true if the container is not dump
boolean searchForORMFiles = ! xmlFiles.contains( META_INF_ORM_XML );
@@ -481,9 +548,7 @@
setDetectedArtifactsOnScanningContext( context, info.getProperties(), null, info.excludeUnlistedClasses() );
scanForClasses( context, packages, entities, hbmFiles );
- Properties properties = info.getProperties() != null ?
- info.getProperties() :
- new Properties();
+ Properties properties = info.getProperties() != null ? info.getProperties() : new Properties();
ConfigurationHelper.overrideProperties( properties, integration );
//FIXME entities is used to enhance classes and to collect annotated entities this should not be mixed
@@ -500,18 +565,34 @@
workingVars.put( AvailableSettings.XML_FILE_NAMES, xmlFiles );
if ( hbmFiles.size() > 0 ) workingVars.put( AvailableSettings.HBXML_FILES, hbmFiles );
- //validation-mode
- final Object validationMode = info.getValidationMode();
- if ( validationMode != null) {
- workingVars.put( AvailableSettings.VALIDATION_MODE, validationMode );
+ // validation factory
+ final Object validationFactory = integration.get( AvailableSettings.VALIDATION_FACTORY );
+ if ( validationFactory != null ) {
+ properties.put( AvailableSettings.VALIDATION_FACTORY, validationFactory );
}
- //shared-cache-mode
- final Object sharedCacheMode = info.getSharedCacheMode();
- if ( sharedCacheMode != null) {
- workingVars.put( AvailableSettings.SHARED_CACHE_MODE, sharedCacheMode );
+ // validation-mode (integration has precedence)
+ {
+ final Object integrationValue = integration.get( AvailableSettings.VALIDATION_MODE );
+ if ( integrationValue != null ) {
+ properties.put( AvailableSettings.VALIDATION_MODE, integrationValue.toString() );
+ }
+ else if ( info.getValidationMode() != null ) {
+ properties.put( AvailableSettings.VALIDATION_MODE, info.getValidationMode().name() );
+ }
}
+ // shared-cache-mode (integration has precedence)
+ {
+ final Object integrationValue = integration.get( AvailableSettings.SHARED_CACHE_MODE );
+ if ( integrationValue != null ) {
+ properties.put( AvailableSettings.SHARED_CACHE_MODE, integrationValue.toString() );
+ }
+ else if ( info.getSharedCacheMode() != null ) {
+ properties.put( AvailableSettings.SHARED_CACHE_MODE, info.getSharedCacheMode().name() );
+ }
+ }
+
//datasources
Boolean isJTA = null;
boolean overridenDatasource = false;
@@ -837,12 +918,20 @@
}
/**
- * create a factory from a canonical workingVars map and the overriden properties
+ * Configures this configuration object from 2 distinctly different sources.
*
+ * @param properties These are the properties that came from the user, either via
+ * a persistence.xml or explicitly passed in to one of our
+ * {@link javax.persistence.spi.PersistenceProvider}/{@link HibernatePersistence} contracts.
+ * @param workingVars Is collection of settings which need to be handled similarly
+ * between the 2 main bootstrap methods, but where the values are determine very differently
+ * by each bootstrap method. todo eventually make this a contract (class/interface)
+ *
+ * @return The configured configuration
+ *
+ * @see HibernatePersistence
*/
- private Ejb3Configuration configure(
- Properties properties, Map workingVars
- ) {
+ private Ejb3Configuration configure(Properties properties, Map workingVars) {
//TODO check for people calling more than once this method (except buildEMF)
if (isConfigurationProcessed) return this;
isConfigurationProcessed = true;
Modified: core/trunk/entitymanager/src/main/java/org/hibernate/ejb/HibernatePersistence.java
===================================================================
--- core/trunk/entitymanager/src/main/java/org/hibernate/ejb/HibernatePersistence.java 2010-01-26 18:06:40 UTC (rev 18635)
+++ core/trunk/entitymanager/src/main/java/org/hibernate/ejb/HibernatePersistence.java 2010-01-26 18:36:59 UTC (rev 18636)
@@ -26,6 +26,7 @@
import java.util.Map;
import javax.persistence.EntityManagerFactory;
import javax.persistence.spi.LoadState;
+import javax.persistence.spi.PersistenceProvider;
import javax.persistence.spi.PersistenceUnitInfo;
import javax.persistence.spi.ProviderUtil;
@@ -36,34 +37,50 @@
*
* @author Gavin King
*/
-public class HibernatePersistence implements javax.persistence.spi.PersistenceProvider {
+public class HibernatePersistence extends AvailableSettings implements PersistenceProvider {
- //The following properties are for Internal use only
/**
- * link to the alternative Hibernate configuration file
- * Internal use only
+ * Get an entity manager factory by its entity manager name, using the specified
+ * properties (they override any found in the peristence.xml file).
+ * <p/>
+ * This is the form used in JSE environments.
+ *
+ * @param persistenceUnitName entity manager name
+ * @param properties The explicit property values
+ *
+ * @return initialized EntityManagerFactory
*/
+ public EntityManagerFactory createEntityManagerFactory(String persistenceUnitName, Map properties) {
+ Ejb3Configuration cfg = new Ejb3Configuration();
+ Ejb3Configuration configured = cfg.configure( persistenceUnitName, properties );
+ return configured != null ? configured.buildEntityManagerFactory() : null;
+ }
-
/**
- * Get an entity manager factory by its entity manager name and given the
- * appropriate extra properties. Those proeprties override the one get through
- * the peristence.xml file.
+ * Create an entity manager factory from the given persistence unit info, using the specified
+ * properties (they override any on the PUI).
+ * <p/>
+ * This is the form used by the container in a JEE environment.
*
- * @param persistenceUnitName entity manager name
- * @param overridenProperties properties passed to the persistence provider
+ * @param info The persistence unit information
+ * @param properties The explicit property values
+ *
* @return initialized EntityManagerFactory
*/
- public EntityManagerFactory createEntityManagerFactory(String persistenceUnitName, Map overridenProperties) {
+ public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map properties) {
Ejb3Configuration cfg = new Ejb3Configuration();
- Ejb3Configuration configured = cfg.configure( persistenceUnitName, overridenProperties );
+ Ejb3Configuration configured = cfg.configure( info, properties );
return configured != null ? configured.buildEntityManagerFactory() : null;
}
- public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map map) {
+ /**
+ * create a factory from a canonical version
+ * @deprecated
+ */
+ public EntityManagerFactory createEntityManagerFactory(Map properties) {
+ // This is used directly by JBoss so don't remove until further notice. bill(a)jboss.org
Ejb3Configuration cfg = new Ejb3Configuration();
- Ejb3Configuration configured = cfg.configure( info, map );
- return configured != null ? configured.buildEntityManagerFactory() : null;
+ return cfg.createEntityManagerFactory( properties );
}
private final ProviderUtil providerUtil = new ProviderUtil() {
@@ -80,18 +97,11 @@
}
};
+ /**
+ * {@inheritDoc}
+ */
public ProviderUtil getProviderUtil() {
return providerUtil;
}
- /**
- * create a factory from a canonical version
- * @deprecated
- */
- public EntityManagerFactory createEntityManagerFactory(Map properties) {
- // This is used directly by JBoss so don't remove until further notice. bill(a)jboss.org
- Ejb3Configuration cfg = new Ejb3Configuration();
- return cfg.createEntityManagerFactory( properties );
- }
-
}
\ No newline at end of file
Added: core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/ejb3configuration/ConfigurationObjectSettingTest.java
===================================================================
--- core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/ejb3configuration/ConfigurationObjectSettingTest.java (rev 0)
+++ core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/ejb3configuration/ConfigurationObjectSettingTest.java 2010-01-26 18:36:59 UTC (rev 18636)
@@ -0,0 +1,249 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2010, Red Hat Inc. or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.ejb.test.ejb3configuration;
+
+import java.util.Collections;
+import java.util.Map;
+import javax.persistence.SharedCacheMode;
+import javax.persistence.ValidationMode;
+
+import org.hibernate.HibernateException;
+import org.hibernate.ejb.AvailableSettings;
+import org.hibernate.ejb.Ejb3Configuration;
+import org.hibernate.ejb.packaging.PersistenceMetadata;
+
+/**
+ * Test passing along various config settings that take objects other than strings as values.
+ *
+ * @author Steve Ebersole
+ */
+public class ConfigurationObjectSettingTest extends junit.framework.TestCase {
+ public void testContainerBootstrapSharedCacheMode() {
+ // first, via the integration vars
+ PersistenceUnitInfoAdapter empty = new PersistenceUnitInfoAdapter();
+ {
+ // as object
+ Ejb3Configuration cfg = new Ejb3Configuration();
+ Ejb3Configuration configured = cfg.configure(
+ empty,
+ Collections.singletonMap( AvailableSettings.SHARED_CACHE_MODE, SharedCacheMode.DISABLE_SELECTIVE )
+ );
+ assertEquals( SharedCacheMode.DISABLE_SELECTIVE.name(), configured.getProperties().get( AvailableSettings.SHARED_CACHE_MODE ) );
+ }
+ {
+ // as string
+ Ejb3Configuration cfg = new Ejb3Configuration();
+ Ejb3Configuration configured = cfg.configure(
+ empty,
+ Collections.singletonMap( AvailableSettings.SHARED_CACHE_MODE, SharedCacheMode.DISABLE_SELECTIVE.name() )
+ );
+ assertEquals( SharedCacheMode.DISABLE_SELECTIVE.name(), configured.getProperties().get( AvailableSettings.SHARED_CACHE_MODE ) );
+ }
+
+ // next, via the PUI
+ PersistenceUnitInfoAdapter adapter = new PersistenceUnitInfoAdapter() {
+ @Override
+ public SharedCacheMode getSharedCacheMode() {
+ return SharedCacheMode.ENABLE_SELECTIVE;
+ }
+ };
+ {
+ Ejb3Configuration cfg = new Ejb3Configuration();
+ Ejb3Configuration configured = cfg.configure( adapter, null );
+ assertEquals( SharedCacheMode.ENABLE_SELECTIVE.name(), configured.getProperties().get( AvailableSettings.SHARED_CACHE_MODE ) );
+ }
+
+ // via both, integration vars should take precedence
+ {
+ Ejb3Configuration cfg = new Ejb3Configuration();
+ Ejb3Configuration configured = cfg.configure(
+ adapter,
+ Collections.singletonMap( AvailableSettings.SHARED_CACHE_MODE, SharedCacheMode.DISABLE_SELECTIVE )
+ );
+ assertEquals( SharedCacheMode.DISABLE_SELECTIVE.name(), configured.getProperties().get( AvailableSettings.SHARED_CACHE_MODE ) );
+ }
+ }
+
+ public void testContainerBootstrapValidationMode() {
+ // first, via the integration vars
+ PersistenceUnitInfoAdapter empty = new PersistenceUnitInfoAdapter();
+ {
+ // as object
+ Ejb3Configuration cfg = new Ejb3Configuration();
+ Ejb3Configuration configured = cfg.configure(
+ empty,
+ Collections.singletonMap( AvailableSettings.VALIDATION_MODE, ValidationMode.CALLBACK )
+ );
+ assertEquals( ValidationMode.CALLBACK.name(), configured.getProperties().get( AvailableSettings.VALIDATION_MODE ) );
+ }
+ {
+ // as string
+ Ejb3Configuration cfg = new Ejb3Configuration();
+ Ejb3Configuration configured = cfg.configure(
+ empty,
+ Collections.singletonMap( AvailableSettings.VALIDATION_MODE, ValidationMode.CALLBACK.name() )
+ );
+ assertEquals( ValidationMode.CALLBACK.name(), configured.getProperties().get( AvailableSettings.VALIDATION_MODE ) );
+ }
+
+ // next, via the PUI
+ PersistenceUnitInfoAdapter adapter = new PersistenceUnitInfoAdapter() {
+ @Override
+ public ValidationMode getValidationMode() {
+ return ValidationMode.CALLBACK;
+ }
+ };
+ {
+ Ejb3Configuration cfg = new Ejb3Configuration();
+ Ejb3Configuration configured = cfg.configure( adapter, null );
+ assertEquals( ValidationMode.CALLBACK.name(), configured.getProperties().get( AvailableSettings.VALIDATION_MODE ) );
+ }
+
+ // via both, integration vars should take precedence
+ {
+ Ejb3Configuration cfg = new Ejb3Configuration();
+ Ejb3Configuration configured = cfg.configure(
+ adapter,
+ Collections.singletonMap( AvailableSettings.VALIDATION_MODE, ValidationMode.NONE )
+ );
+ assertEquals( ValidationMode.NONE.name(), configured.getProperties().get( AvailableSettings.VALIDATION_MODE ) );
+ }
+ }
+
+ public void testContainerBootstrapValidationFactory() {
+ final Object token = new Object();
+ PersistenceUnitInfoAdapter adapter = new PersistenceUnitInfoAdapter();
+ Ejb3Configuration cfg = new Ejb3Configuration();
+ try {
+ cfg.configure(
+ adapter,
+ Collections.singletonMap( AvailableSettings.VALIDATION_FACTORY, token )
+ );
+ fail( "Was expecting error as token did not implement ValidatorFactory" );
+ }
+ catch ( HibernateException e ) {
+ // probably the condition we want but unfortunately the exception is not specific
+ // and the pertinent info is in a cause
+ }
+ }
+
+ public void testStandaloneBootstrapSharedCacheMode() {
+ // first, via the integration vars
+ PersistenceMetadata metadata = new PersistenceMetadata();
+ {
+ // as object
+ Ejb3Configuration cfg = new Ejb3Configuration();
+ Ejb3Configuration configured = cfg.configure(
+ metadata,
+ Collections.singletonMap( AvailableSettings.SHARED_CACHE_MODE, SharedCacheMode.DISABLE_SELECTIVE )
+ );
+ assertEquals( SharedCacheMode.DISABLE_SELECTIVE.name(), configured.getProperties().get( AvailableSettings.SHARED_CACHE_MODE ) );
+ }
+ {
+ // as string
+ Ejb3Configuration cfg = new Ejb3Configuration();
+ Ejb3Configuration configured = cfg.configure(
+ metadata,
+ Collections.singletonMap( AvailableSettings.SHARED_CACHE_MODE, SharedCacheMode.DISABLE_SELECTIVE.name() )
+ );
+ assertEquals( SharedCacheMode.DISABLE_SELECTIVE.name(), configured.getProperties().get( AvailableSettings.SHARED_CACHE_MODE ) );
+ }
+
+ // next, via the PM
+ metadata.setSharedCacheMode( SharedCacheMode.ENABLE_SELECTIVE.name() );
+ {
+ Ejb3Configuration cfg = new Ejb3Configuration();
+ Ejb3Configuration configured = cfg.configure( metadata, null );
+ assertEquals( SharedCacheMode.ENABLE_SELECTIVE.name(), configured.getProperties().get( AvailableSettings.SHARED_CACHE_MODE ) );
+ }
+
+ // via both, integration vars should take precedence
+ {
+ Ejb3Configuration cfg = new Ejb3Configuration();
+ Ejb3Configuration configured = cfg.configure(
+ metadata,
+ Collections.singletonMap( AvailableSettings.SHARED_CACHE_MODE, SharedCacheMode.DISABLE_SELECTIVE )
+ );
+ assertEquals( SharedCacheMode.DISABLE_SELECTIVE.name(), configured.getProperties().get( AvailableSettings.SHARED_CACHE_MODE ) );
+ }
+ }
+
+ public void testStandaloneBootstrapValidationMode() {
+ // first, via the integration vars
+ PersistenceMetadata metadata = new PersistenceMetadata();
+ {
+ // as object
+ Ejb3Configuration cfg = new Ejb3Configuration();
+ Ejb3Configuration configured = cfg.configure(
+ metadata,
+ Collections.singletonMap( AvailableSettings.VALIDATION_MODE, ValidationMode.CALLBACK )
+ );
+ assertEquals( ValidationMode.CALLBACK.name(), configured.getProperties().get( AvailableSettings.VALIDATION_MODE ) );
+ }
+ {
+ // as string
+ Ejb3Configuration cfg = new Ejb3Configuration();
+ Ejb3Configuration configured = cfg.configure(
+ metadata,
+ Collections.singletonMap( AvailableSettings.VALIDATION_MODE, ValidationMode.CALLBACK.name() )
+ );
+ assertEquals( ValidationMode.CALLBACK.name(), configured.getProperties().get( AvailableSettings.VALIDATION_MODE ) );
+ }
+
+ // next, via the PUI
+ metadata.setValidationMode( ValidationMode.AUTO.name() );
+ {
+ Ejb3Configuration cfg = new Ejb3Configuration();
+ Ejb3Configuration configured = cfg.configure( metadata, null );
+ assertEquals( ValidationMode.AUTO.name(), configured.getProperties().get( AvailableSettings.VALIDATION_MODE ) );
+ }
+
+ // via both, integration vars should take precedence
+ {
+ Ejb3Configuration cfg = new Ejb3Configuration();
+ Ejb3Configuration configured = cfg.configure(
+ metadata,
+ Collections.singletonMap( AvailableSettings.VALIDATION_MODE, ValidationMode.NONE )
+ );
+ assertEquals( ValidationMode.NONE.name(), configured.getProperties().get( AvailableSettings.VALIDATION_MODE ) );
+ }
+ }
+
+ public void testStandaloneBootstrapValidationFactory() {
+ final Object token = new Object();
+ PersistenceMetadata metadata = new PersistenceMetadata();
+ Ejb3Configuration cfg = new Ejb3Configuration();
+ try {
+ cfg.configure(
+ metadata,
+ Collections.singletonMap( AvailableSettings.VALIDATION_FACTORY, token )
+ );
+ fail( "Was expecting error as token did not implement ValidatorFactory" );
+ }
+ catch ( HibernateException e ) {
+ // probably the condition we want but unfortunately the exception is not specific
+ // and the pertinent info is in a cause
+ }
+ }
+}
Added: core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/ejb3configuration/PersistenceUnitInfoAdapter.java
===================================================================
--- core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/ejb3configuration/PersistenceUnitInfoAdapter.java (rev 0)
+++ core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/ejb3configuration/PersistenceUnitInfoAdapter.java 2010-01-26 18:36:59 UTC (rev 18636)
@@ -0,0 +1,116 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2010, Red Hat Inc. or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.ejb.test.ejb3configuration;
+
+import java.net.URL;
+import java.util.Collections;
+import java.util.List;
+import java.util.Properties;
+import javax.persistence.SharedCacheMode;
+import javax.persistence.ValidationMode;
+import javax.persistence.spi.ClassTransformer;
+import javax.persistence.spi.PersistenceUnitInfo;
+import javax.persistence.spi.PersistenceUnitTransactionType;
+import javax.sql.DataSource;
+
+import org.hibernate.ejb.HibernatePersistence;
+
+/**
+ * TODO : javadoc
+ *
+ * @author Steve Ebersole
+ */
+public class PersistenceUnitInfoAdapter implements PersistenceUnitInfo {
+ private Properties properties;
+
+ public String getPersistenceUnitName() {
+ return "persistenceUnitAdapter";
+ }
+
+ public String getPersistenceProviderClassName() {
+ return HibernatePersistence.class.getName();
+ }
+
+ public PersistenceUnitTransactionType getTransactionType() {
+ return null;
+ }
+
+ public DataSource getJtaDataSource() {
+ return null;
+ }
+
+ public DataSource getNonJtaDataSource() {
+ return null;
+ }
+
+ public List<String> getMappingFileNames() {
+ return Collections.emptyList();
+ }
+
+ public List<URL> getJarFileUrls() {
+ return Collections.emptyList();
+ }
+
+ public URL getPersistenceUnitRootUrl() {
+ return null;
+ }
+
+ public List<String> getManagedClassNames() {
+ return Collections.emptyList();
+ }
+
+ public boolean excludeUnlistedClasses() {
+ return false;
+ }
+
+ public SharedCacheMode getSharedCacheMode() {
+ return null;
+ }
+
+ public ValidationMode getValidationMode() {
+ return null;
+ }
+
+ public Properties getProperties() {
+ if ( properties == null ) {
+ properties = new Properties();
+ }
+ return properties;
+ }
+
+ public String getPersistenceXMLSchemaVersion() {
+ return null;
+ }
+
+ public ClassLoader getClassLoader() {
+ return Thread.currentThread().getContextClassLoader();
+ }
+
+ public void addTransformer(ClassTransformer transformer) {
+ }
+
+ public ClassLoader getNewTempClassLoader() {
+ return Thread.currentThread().getContextClassLoader();
+ }
+}
15 years, 1 month
Hibernate SVN: r18635 - jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2010-01-26 13:06:40 -0500 (Tue, 26 Jan 2010)
New Revision: 18635
Modified:
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/ClassWriter.java
Log:
METAGEN-14
Modified: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/ClassWriter.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/ClassWriter.java 2010-01-26 17:48:54 UTC (rev 18634)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/ClassWriter.java 2010-01-26 18:06:40 UTC (rev 18635)
@@ -39,7 +39,6 @@
public static void writeFile(MetaEntity entity, Context context) {
try {
String metaModelPackage = entity.getPackageName();
-
StringBuffer body = generateBody( entity, context );
FileObject fo = context.getProcessingEnvironment().getFiler().createSourceFile(
@@ -49,11 +48,8 @@
PrintWriter pw = new PrintWriter( os );
pw.println( "package " + metaModelPackage + ";" );
-
pw.println();
-
pw.println( entity.generateImports() );
-
pw.println( body );
pw.flush();
@@ -62,7 +58,7 @@
}
catch ( FilerException filerEx ) {
context.logMessage(
- Diagnostic.Kind.WARNING, "Problem with Processing Environment Filer: " + filerEx.getMessage()
+ Diagnostic.Kind.ERROR, "Problem with Filer: " + filerEx.getMessage()
);
}
catch ( IOException ioEx ) {
@@ -77,6 +73,7 @@
* Generate everything after import statements.
*
* @param entity The meta entity for which to write the body
+ * @param context The processing context
*
* @return body content
*/
@@ -111,7 +108,6 @@
final TypeMirror superClass = entity.getTypeElement().getSuperclass();
//superclass of Object is of NoType which returns some other kind
- String superclassDeclaration = "";
if ( superClass.getKind() == TypeKind.DECLARED ) {
//F..king Ch...t Have those people used their horrible APIs even once?
final Element superClassElement = ( ( DeclaredType ) superClass ).asElement();
15 years, 1 month