Hibernate SVN: r15298 - in entitymanager/trunk/src/test/org/hibernate/ejb/test: emops and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2008-10-08 22:50:26 -0400 (Wed, 08 Oct 2008)
New Revision: 15298
Modified:
entitymanager/trunk/src/test/org/hibernate/ejb/test/TestCase.java
entitymanager/trunk/src/test/org/hibernate/ejb/test/emops/FlushModeTest.java
Log:
Fix test case rework error when passign argument on em creation
Modified: entitymanager/trunk/src/test/org/hibernate/ejb/test/TestCase.java
===================================================================
--- entitymanager/trunk/src/test/org/hibernate/ejb/test/TestCase.java 2008-10-09 01:33:00 UTC (rev 15297)
+++ entitymanager/trunk/src/test/org/hibernate/ejb/test/TestCase.java 2008-10-09 02:50:26 UTC (rev 15298)
@@ -57,9 +57,12 @@
return em;
}
- protected EntityManager getEntityManager(Map properties) {
- if (em == null || !em.isOpen())
- em = factory.createEntityManager(properties);
+ /** always reopen a new EM and clse the existing one */
+ protected EntityManager createEntityManager(Map properties) {
+ if (em != null && em.isOpen() ) {
+ em.close();
+ }
+ em = factory.createEntityManager(properties);
return em;
}
Modified: entitymanager/trunk/src/test/org/hibernate/ejb/test/emops/FlushModeTest.java
===================================================================
--- entitymanager/trunk/src/test/org/hibernate/ejb/test/emops/FlushModeTest.java 2008-10-09 01:33:00 UTC (rev 15297)
+++ entitymanager/trunk/src/test/org/hibernate/ejb/test/emops/FlushModeTest.java 2008-10-09 02:50:26 UTC (rev 15298)
@@ -15,7 +15,7 @@
public void testCreateEMFlushMode() throws Exception {
Map properties = new HashMap();
properties.put( "org.hibernate.flushMode", "manual" );
- EntityManager em = getEntityManager( properties );
+ EntityManager em = createEntityManager( properties );
em.getTransaction().begin();
Dress dress = new Dress();
dress.name = "long dress";
16 years, 2 months
Hibernate SVN: r15297 - in annotations/branches/v3_2_1_GA_CP/src/java/org/hibernate/cfg: annotations and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: gbadner
Date: 2008-10-08 21:33:00 -0400 (Wed, 08 Oct 2008)
New Revision: 15297
Modified:
annotations/branches/v3_2_1_GA_CP/src/java/org/hibernate/cfg/Ejb3JoinColumn.java
annotations/branches/v3_2_1_GA_CP/src/java/org/hibernate/cfg/annotations/TableBinder.java
Log:
JBPAPP-1065 ANN-560 - Quoting clashes with defaults in NamingStrategy
Modified: annotations/branches/v3_2_1_GA_CP/src/java/org/hibernate/cfg/Ejb3JoinColumn.java
===================================================================
--- annotations/branches/v3_2_1_GA_CP/src/java/org/hibernate/cfg/Ejb3JoinColumn.java 2008-10-09 01:31:40 UTC (rev 15296)
+++ annotations/branches/v3_2_1_GA_CP/src/java/org/hibernate/cfg/Ejb3JoinColumn.java 2008-10-09 01:33:00 UTC (rev 15297)
@@ -10,13 +10,13 @@
import org.hibernate.AnnotationException;
import org.hibernate.MappingException;
+import org.hibernate.util.StringHelper;
import org.hibernate.mapping.Column;
import org.hibernate.mapping.Join;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.SimpleValue;
import org.hibernate.mapping.Table;
import org.hibernate.mapping.Value;
-import org.hibernate.util.StringHelper;
/**
* Wrap state of an EJB3 @JoinColumn annotation
@@ -272,27 +272,51 @@
);
boolean mappedBySide = mappedByTableName != null || mappedByPropertyName != null;
boolean ownerSide = getPropertyName() != null;
+
+ Boolean isRefColumnQuoted = StringHelper.isQuoted( logicalReferencedColumn );
+ String unquotedLogicalReferenceColumn = isRefColumnQuoted ?
+ StringHelper.unquote( logicalReferencedColumn ) :
+ logicalReferencedColumn;
+
if ( mappedBySide ) {
+ String unquotedMappedbyTable = StringHelper.unquote( mappedByTableName );
columnName = getMappings().getNamingStrategy().foreignKeyColumnName(
mappedByPropertyName,
- mappedByEntityName, mappedByTableName,
- logicalReferencedColumn
+ mappedByEntityName,
+ unquotedMappedbyTable,
+ unquotedLogicalReferenceColumn
);
- //columnName = ( defaultColumnHeader == null ? getPropertyName() : defaultColumnHeader ) + "_" + logicalReferencedColumn;
+ //one element was quoted so we quote
+ if ( isRefColumnQuoted || StringHelper.isQuoted( mappedByTableName ) ) {
+ columnName = StringHelper.quote( columnName );
+ }
}
else if ( ownerSide ) {
+ String logicalTableName = getMappings().getLogicalTableName( referencedEntity.getTable() );
+ String unquotedLogicalTableName = StringHelper.unquote( logicalTableName );
columnName = getMappings().getNamingStrategy().foreignKeyColumnName(
getPropertyName(),
- referencedEntity.getEntityName(), getMappings().getLogicalTableName( referencedEntity.getTable() ),
- logicalReferencedColumn
+ referencedEntity.getEntityName(),
+ unquotedLogicalTableName,
+ unquotedLogicalReferenceColumn
);
+ //one element was quoted so we quote
+ if ( isRefColumnQuoted || StringHelper.isQuoted( logicalTableName ) ) {
+ columnName = StringHelper.quote( columnName );
+ }
}
else {
//is an intra-entity hierarchy table join so copy the name by default
+ String logicalTableName = getMappings().getLogicalTableName( referencedEntity.getTable() );
+ String unquotedLogicalTableName = StringHelper.unquote( logicalTableName );
columnName = getMappings().getNamingStrategy().joinKeyColumnName(
- logicalReferencedColumn,
- getMappings().getLogicalTableName( referencedEntity.getTable() )
+ unquotedLogicalReferenceColumn,
+ unquotedLogicalTableName
);
+ //one element was quoted so we quote
+ if ( isRefColumnQuoted || StringHelper.isQuoted( logicalTableName ) ) {
+ columnName = StringHelper.quote( columnName );
+ }
}
//yuk side effect on an implicit column
setLogicalColumnName( columnName );
@@ -329,8 +353,13 @@
protected void addColumnBinding(SimpleValue value) {
if ( StringHelper.isEmpty( mappedBy ) ) {
+ String unquotedLogColName = StringHelper.unquote( getLogicalColumnName() );
+ String unquotedRefColumn = StringHelper.unquote( getReferencedColumn() );
String logicalColumnName = getMappings().getNamingStrategy()
- .logicalCollectionColumnName( getLogicalColumnName(), getPropertyName(), getReferencedColumn() );
+ .logicalCollectionColumnName( unquotedLogColName, getPropertyName(), unquotedRefColumn );
+ if ( StringHelper.isQuoted( getLogicalColumnName() ) || StringHelper.isQuoted( getLogicalColumnName() ) ) {
+ logicalColumnName = StringHelper.quote( logicalColumnName );
+ }
getMappings().addColumnBinding( logicalColumnName, getMappingColumn(), value.getTable() );
}
}
@@ -423,14 +452,6 @@
}
}
- public void setMappedByPropertyName(String mappedByPropertyName) {
- this.mappedByPropertyName = mappedByPropertyName;
- }
-
- public void setMappedByTableName(String mappedByTableName) {
- this.mappedByTableName = mappedByTableName;
- }
-
public static Ejb3JoinColumn[] buildJoinTableJoinColumns(
JoinColumn[] annJoins, Map<String, Join> secondaryTables,
PropertyHolder propertyHolder, String propertyName, String mappedBy, ExtendedMappings mappings
Modified: annotations/branches/v3_2_1_GA_CP/src/java/org/hibernate/cfg/annotations/TableBinder.java
===================================================================
--- annotations/branches/v3_2_1_GA_CP/src/java/org/hibernate/cfg/annotations/TableBinder.java 2008-10-09 01:31:40 UTC (rev 15296)
+++ annotations/branches/v3_2_1_GA_CP/src/java/org/hibernate/cfg/annotations/TableBinder.java 2008-10-09 01:33:00 UTC (rev 15297)
@@ -11,6 +11,7 @@
import org.hibernate.AnnotationException;
import org.hibernate.AssertionFailure;
import org.hibernate.annotations.Index;
+import org.hibernate.util.StringHelper;
import org.hibernate.cfg.BinderHelper;
import org.hibernate.cfg.Ejb3JoinColumn;
import org.hibernate.cfg.ExtendedMappings;
@@ -25,7 +26,6 @@
import org.hibernate.mapping.Table;
import org.hibernate.mapping.ToOne;
import org.hibernate.mapping.Value;
-import org.hibernate.util.StringHelper;
/**
* Table related operations
@@ -43,8 +43,8 @@
String constraints;
Table denormalizedSuperTable;
ExtendedMappings mappings;
- private Table ownerEntityTable;
- private Table associatedEntityTable;
+ private String ownerEntityTable;
+ private String associatedEntityTable;
private String propertyName;
private String ownerEntity;
private String associatedEntity;
@@ -88,22 +88,35 @@
// only bind association table currently
public Table bind() {
//logicalName only accurate for assoc table...
+ String unquotedOwnerTable = StringHelper.unquote( ownerEntityTable );
+ String unquotedAssocTable = StringHelper.unquote( associatedEntityTable );
+
String logicalName = mappings.getNamingStrategy()
.logicalCollectionTableName(
name,
- ownerEntityTable == null ? null : ownerEntityTable.getName(), //we remove potential quotes
- associatedEntityTable == null ? null : associatedEntityTable.getName(), //we remove potential quotes
+ unquotedOwnerTable,
+ unquotedAssocTable,
propertyName );
- String extendedName = name != null ?
- mappings.getNamingStrategy().tableName( name ) :
- mappings.getNamingStrategy()
- .collectionTableName(
- ownerEntity,
- ownerEntityTable == null ? null : ownerEntityTable.getName(), //we remove potential quotes
- associatedEntity,
- associatedEntityTable == null ? null : associatedEntityTable.getName(), //we remove potential quotes
- propertyName
- );
+ if ( StringHelper.isQuoted( ownerEntityTable ) || StringHelper.isQuoted( associatedEntityTable ) ) {
+ logicalName = StringHelper.quote( logicalName );
+ }
+ String extendedName;
+ if ( name != null ) {
+ extendedName = mappings.getNamingStrategy().tableName( name );
+ }
+ else {
+ extendedName = mappings.getNamingStrategy()
+ .collectionTableName(
+ ownerEntity,
+ unquotedOwnerTable,
+ associatedEntity,
+ unquotedAssocTable,
+ propertyName
+ );
+ if ( StringHelper.isQuoted( ownerEntityTable ) || StringHelper.isQuoted( associatedEntityTable ) ) {
+ extendedName = StringHelper.quote( extendedName );
+ }
+ }
return fillTable(
schema, catalog,
extendedName, logicalName, isAbstract, uniqueConstraints, constraints,
@@ -367,9 +380,9 @@
String propertyName
) {
this.ownerEntity = ownerEntity;
- this.ownerEntityTable = ownerEntityTable != null ? new Table(ownerEntityTable) : null;
+ this.ownerEntityTable = ownerEntityTable;
this.associatedEntity = associatedEntity;
- this.associatedEntityTable = associatedEntityTable != null ? new Table(associatedEntityTable) : null;
+ this.associatedEntityTable = associatedEntityTable;
this.propertyName = propertyName;
this.name = null;
}
16 years, 2 months
Hibernate SVN: r15296 - core/branches/Branch_3_2_4_SP1_CP/src/org/hibernate/util.
by hibernate-commits@lists.jboss.org
Author: gbadner
Date: 2008-10-08 21:31:40 -0400 (Wed, 08 Oct 2008)
New Revision: 15296
Modified:
core/branches/Branch_3_2_4_SP1_CP/src/org/hibernate/util/StringHelper.java
Log:
JBPAPP-1065 - Quoting clashes with defaults in NamingStrategy
Modified: core/branches/Branch_3_2_4_SP1_CP/src/org/hibernate/util/StringHelper.java
===================================================================
--- core/branches/Branch_3_2_4_SP1_CP/src/org/hibernate/util/StringHelper.java 2008-10-08 23:09:58 UTC (rev 15295)
+++ core/branches/Branch_3_2_4_SP1_CP/src/org/hibernate/util/StringHelper.java 2008-10-09 01:31:40 UTC (rev 15296)
@@ -390,4 +390,25 @@
return filter;
}
+ public static boolean isQuoted(String name) {
+ return name != null && name.length() != 0 && name.charAt( 0 ) == '`';
+ }
+
+ public static String quote(String name) {
+ if ( name == null || name.length() == 0 || isQuoted( name ) ) {
+ return name;
+ }
+ else {
+ return new StringBuffer( name.length() + 2 ).append('`').append( name ).append( '`' ).toString();
+ }
+ }
+
+ public static String unquote(String name) {
+ if ( isQuoted( name ) ) {
+ return name.substring( 1, name.length() - 1 );
+ }
+ else {
+ return name;
+ }
+ }
}
16 years, 2 months
Hibernate SVN: r15295 - in entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test: association and 10 other directories.
by hibernate-commits@lists.jboss.org
Author: jcosta(a)redhat.com
Date: 2008-10-08 19:09:58 -0400 (Wed, 08 Oct 2008)
New Revision: 15295
Modified:
entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/EntityManagerTest.java
entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/PackagedEntityManagerTest.java
entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/QueryTest.java
entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/TestCase.java
entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/ValidatorIntegrationTest.java
entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/association/AssociationTest.java
entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/callbacks/CallbackAndDirtyTest.java
entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/callbacks/CallbacksTest.java
entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/cascade/CascadeTest.java
entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/cascade/DeleteOrphanTest.java
entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/cascade/FetchTest.java
entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/emops/FlushModeTest.java
entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/emops/GetReferenceTest.java
entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/emops/MergeTest.java
entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/emops/RefreshTest.java
entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/emops/RemoveTest.java
entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/exception/ExceptionTest.java
entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/inheritance/InheritanceTest.java
entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/lob/BlobTest.java
entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/lock/LockTest.java
entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/ops/MergeNewTest.java
entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/transaction/FlushAndTransactionTest.java
entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/xml/XmlAttributeOverrideTest.java
entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/xml/XmlTest.java
Log:
EJB-394 - applied patch to get the entity manager from the parent class, which is now wrapping the tests in try/catch block
Modified: entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/EntityManagerTest.java
===================================================================
--- entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/EntityManagerTest.java 2008-10-08 23:02:47 UTC (rev 15294)
+++ entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/EntityManagerTest.java 2008-10-08 23:09:58 UTC (rev 15295)
@@ -49,7 +49,7 @@
//
// Item item = new Item( "Mouse", "Micro$oft mouse" );
//
-// EntityManager em = factory.createEntityManager();
+// EntityManager em = getOrCreateEntityManager();
// em.getTransaction().begin();
// em.persist( item );
// assertTrue( em.contains( item ) );
@@ -95,7 +95,7 @@
Item item = new Item( "Mouse", "Micro$oft mouse" );
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
em.persist( item );
assertTrue( em.contains( item ) );
@@ -148,7 +148,7 @@
stats.clear();
stats.setStatisticsEnabled( true );
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
em.persist( res );
@@ -161,7 +161,7 @@
assertEquals( 1, stats.getSecondLevelCachePutCount() );
assertEquals( 0, stats.getSecondLevelCacheHitCount() );
- em = factory.createEntityManager();
+ em = getOrCreateEntityManager();
em.getTransaction().begin();
Item second = em.find( Item.class, item.getName() );
assertEquals( 1, second.getDistributors().size() );
@@ -169,7 +169,7 @@
em.getTransaction().commit();
em.close();
- em = factory.createEntityManager();
+ em = getOrCreateEntityManager();
em.getTransaction().begin();
second = em.find( Item.class, item.getName() );
assertEquals( 1, second.getDistributors().size() );
@@ -184,7 +184,7 @@
}
public void testContains() throws Exception {
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Integer nonManagedObject = new Integer( 4 );
try {
@@ -198,7 +198,7 @@
finally {
em.close();
}
- em = factory.createEntityManager();
+ em = getOrCreateEntityManager();
em.getTransaction().begin();
Item item = new Item();
item.setDescr( "Mine" );
@@ -214,7 +214,7 @@
}
public void testClear() throws Exception {
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Wallet w = new Wallet();
w.setBrand( "Lacoste" );
@@ -229,7 +229,7 @@
}
public void testFlushMode() throws Exception {
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.setFlushMode( FlushModeType.COMMIT );
assertEquals( FlushModeType.COMMIT, em.getFlushMode() );
( (HibernateEntityManager) em ).getSession().setFlushMode( FlushMode.ALWAYS );
@@ -238,7 +238,7 @@
}
public void testPersistNoneGenerator() throws Exception {
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Wallet w = new Wallet();
w.setBrand( "Lacoste" );
@@ -255,7 +255,7 @@
}
public void testSerializableException() throws Exception {
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
try {
Query query = em.createQuery( "SELECT p FETCH JOIN p.distributors FROM Item p" );
@@ -297,7 +297,7 @@
}
public void testIsOpen() throws Exception {
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
assertTrue( em.isOpen() );
em.getTransaction().begin();
assertTrue( em.isOpen() );
@@ -308,7 +308,7 @@
//EJB-9
// public void testGet() throws Exception {
-// EntityManager em = factory.createEntityManager();
+// EntityManager em = getOrCreateEntityManager();
// em.getTransaction().begin();
// Item item = (Item) em.get(Item.class, "nonexistentone");
// try {
Modified: entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/PackagedEntityManagerTest.java
===================================================================
--- entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/PackagedEntityManagerTest.java 2008-10-08 23:02:47 UTC (rev 15294)
+++ entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/PackagedEntityManagerTest.java 2008-10-08 23:09:58 UTC (rev 15295)
@@ -241,7 +241,7 @@
//
// Item item = new Item( "Mouse", "Micro$oft mouse" );
//
-// EntityManager em = factory.createEntityManager();
+// EntityManager em = getOrCreateEntityManager();
// em.getTransaction().begin();
// em.persist( item );
// assertTrue( em.contains( item ) );
@@ -290,7 +290,7 @@
Item item = new Item( "Mouse", "Micro$oft mouse" );
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
em.persist( item );
assertTrue( em.contains( item ) );
@@ -343,7 +343,7 @@
stats.clear();
stats.setStatisticsEnabled( true );
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
em.persist( res );
@@ -356,7 +356,7 @@
assertEquals( 1, stats.getSecondLevelCachePutCount() );
assertEquals( 0, stats.getSecondLevelCacheHitCount() );
- em = factory.createEntityManager();
+ em = getOrCreateEntityManager();
em.getTransaction().begin();
Item second = em.find( Item.class, item.getName() );
assertEquals( 1, second.getDistributors().size() );
@@ -364,7 +364,7 @@
em.getTransaction().commit();
em.close();
- em = factory.createEntityManager();
+ em = getOrCreateEntityManager();
em.getTransaction().begin();
second = em.find( Item.class, item.getName() );
assertEquals( 1, second.getDistributors().size() );
@@ -381,7 +381,7 @@
}
public void testExternalJar() throws Exception {
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
Scooter s = new Scooter();
s.setModel( "Abadah" );
s.setSpeed( new Long( 85 ) );
@@ -389,7 +389,7 @@
em.persist( s );
em.getTransaction().commit();
em.close();
- em = factory.createEntityManager();
+ em = getOrCreateEntityManager();
em.getTransaction().begin();
s = em.find( Scooter.class, s.getModel() );
assertEquals( new Long( 85 ), s.getSpeed() );
Modified: entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/QueryTest.java
===================================================================
--- entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/QueryTest.java 2008-10-08 23:02:47 UTC (rev 15294)
+++ entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/QueryTest.java 2008-10-08 23:09:58 UTC (rev 15295)
@@ -17,7 +17,7 @@
public class QueryTest extends TestCase {
public void testPagedQuery() throws Exception {
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Item item = new Item( "Mouse", "Micro$oft mouse" );
em.persist( item );
@@ -36,7 +36,7 @@
}
public void testAggregationReturnType() throws Exception {
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Item item = new Item( "Mouse", "Micro$oft mouse" );
em.persist( item );
@@ -51,9 +51,9 @@
public void testParameterList() throws Exception {
final Item item = new Item( "Mouse", "Micro$oft mouse" );
- final Item item2 = new Item( "Computer", "D�ll computer" );
+ final Item item2 = new Item( "Computer", "D�ll computer" );
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
em.persist( item );
em.persist( item2 );
@@ -94,7 +94,7 @@
// auchan.setName("Auchan");
// item.addDistributor(auchan);
//
-// EntityManager em = factory.createEntityManager();
+// EntityManager em = getOrCreateEntityManager();
// em.getTransaction().begin();
// em.persist(fnac);
// em.persist(auchan);
@@ -120,9 +120,9 @@
public void testEscapeCharacter() throws Exception {
final Item item = new Item( "Mouse", "Micro_oft mouse" );
- final Item item2 = new Item( "Computer", "D�ll computer" );
+ final Item item2 = new Item( "Computer", "D�ll computer" );
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
em.persist( item );
em.persist( item2 );
@@ -145,7 +145,7 @@
Item item = new Item( "Mouse", "Micro$oft mouse" );
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
em.persist( item );
assertTrue( em.contains( item ) );
@@ -166,7 +166,7 @@
Item item = new Item( "Mouse", "Micro$oft mouse" );
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
em.persist( item );
assertTrue( em.contains( item ) );
@@ -185,7 +185,7 @@
}
public void testExplicitPositionalParameter() throws Exception {
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Wallet w = new Wallet();
w.setBrand( "Lacoste" );
@@ -210,7 +210,7 @@
}
public void testNativeQuestionMarkParameter() throws Exception {
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Wallet w = new Wallet();
w.setBrand( "Lacoste" );
@@ -232,7 +232,7 @@
Item item = new Item( "Mouse", "Micro$oft mouse" );
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
em.persist( item );
assertTrue( em.contains( item ) );
@@ -257,7 +257,7 @@
}
public void testDistinct() throws Exception {
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
em.createQuery( "delete Item" ).executeUpdate();
em.createQuery( "delete Distributor" ).executeUpdate();
@@ -285,7 +285,7 @@
}
public void testIsNull() throws Exception {
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Distributor d1 = new Distributor();
d1.setName( "Fnac" );
@@ -321,7 +321,7 @@
Item item = new Item( "Mouse", "Micro$oft mouse" );
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
em.persist( item );
assertTrue( em.contains( item ) );
Modified: entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/TestCase.java
===================================================================
--- entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/TestCase.java 2008-10-08 23:02:47 UTC (rev 15294)
+++ entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/TestCase.java 2008-10-08 23:09:58 UTC (rev 15295)
@@ -7,9 +7,13 @@
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
+
+import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
import org.hibernate.cfg.Environment;
import org.hibernate.ejb.HibernatePersistence;
@@ -19,6 +23,8 @@
*/
public abstract class TestCase extends junit.framework.TestCase {
protected EntityManagerFactory factory;
+ protected EntityManager em;
+ private static Log log = LogFactory.getLog( TestCase.class );
public TestCase() {
super();
@@ -35,7 +41,36 @@
public void tearDown() {
factory.close();
}
+
+ @Override
+ public void runTest() throws Throwable {
+ try {
+ em = getOrCreateEntityManager();
+ super.runTest();
+ } catch (Throwable t) {
+ if (em.getTransaction().isActive())
+ em.getTransaction().rollback();
+ throw t;
+ } finally {
+ if (em.isOpen()) {
+ em.close();
+ log.warn("The test case didn't closed the Entity Manager. Make sure you close it always!");
+ }
+ }
+ }
+
+ protected EntityManager getOrCreateEntityManager() {
+ if (em == null || !em.isOpen())
+ em = factory.createEntityManager();
+ return em;
+ }
+ protected EntityManager getOrCreateEntityManager(Map properties) {
+ if (em == null || !em.isOpen())
+ em = factory.createEntityManager(properties);
+ return em;
+ }
+
public abstract Class[] getAnnotatedClasses();
public String[] getEjb3DD() {
Modified: entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/ValidatorIntegrationTest.java
===================================================================
--- entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/ValidatorIntegrationTest.java 2008-10-08 23:02:47 UTC (rev 15294)
+++ entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/ValidatorIntegrationTest.java 2008-10-08 23:09:58 UTC (rev 15295)
@@ -12,7 +12,7 @@
public class ValidatorIntegrationTest extends TestCase {
public void testPropertyValidation() throws Exception {
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
Cat cat = new Cat();
cat.setAge( 33 );
cat.setDateOfBirth( new Date() );
Modified: entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/association/AssociationTest.java
===================================================================
--- entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/association/AssociationTest.java 2008-10-08 23:02:47 UTC (rev 15294)
+++ entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/association/AssociationTest.java 2008-10-08 23:09:58 UTC (rev 15295)
@@ -10,7 +10,7 @@
*/
public class AssociationTest extends TestCase {
public void testBidirOneToOne() throws Exception {
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
String id = "10";
Incident i = em.find( Incident.class, id );
@@ -30,7 +30,7 @@
}
public void testMergeAndBidirOneToOne() throws Exception {
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Oven oven = new Oven();
Kitchen kitchen = new Kitchen();
Modified: entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/callbacks/CallbackAndDirtyTest.java
===================================================================
--- entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/callbacks/CallbackAndDirtyTest.java 2008-10-08 23:02:47 UTC (rev 15294)
+++ entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/callbacks/CallbackAndDirtyTest.java 2008-10-08 23:09:58 UTC (rev 15295)
@@ -13,7 +13,7 @@
public class CallbackAndDirtyTest extends TestCase {
public void testDirtyButNotDirty() throws Exception {
- EntityManager manager = factory.createEntityManager();
+ EntityManager manager = getOrCreateEntityManager();
manager.getTransaction().begin();
Employee mark = new Employee();
mark.setName( "Mark" );
Modified: entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/callbacks/CallbacksTest.java
===================================================================
--- entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/callbacks/CallbacksTest.java 2008-10-08 23:02:47 UTC (rev 15294)
+++ entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/callbacks/CallbacksTest.java 2008-10-08 23:09:58 UTC (rev 15295)
@@ -14,7 +14,7 @@
public class CallbacksTest extends TestCase {
public void testCallbackMethod() throws Exception {
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
Cat c = new Cat();
c.setName( "Kitty" );
c.setDateOfBirth( new Date( 90, 11, 15 ) );
@@ -36,7 +36,7 @@
}
public void testEntityListener() throws Exception {
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
Cat c = new Cat();
c.setName( "Kitty" );
c.setLength( 12 );
@@ -63,7 +63,7 @@
public void testPostPersist() throws Exception {
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
Cat c = new Cat();
em.getTransaction().begin();
c.setLength( 23 );
@@ -80,7 +80,7 @@
//Not a test since the spec did not make the proper change on listeners
public void listenerAnnotation() throws Exception {
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
Translation tl = new Translation();
em.getTransaction().begin();
tl.setInto( "France" );
@@ -102,7 +102,7 @@
}
public void testPrePersistOnCascade() throws Exception {
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Television tv = new Television();
RemoteControl rc = new RemoteControl();
@@ -116,7 +116,7 @@
}
public void testCallBackListenersHierarchy() throws Exception {
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Television tv = new Television();
em.persist( tv );
@@ -131,7 +131,7 @@
}
public void testException() throws Exception {
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Rythm r = new Rythm();
try {
Modified: entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/cascade/CascadeTest.java
===================================================================
--- entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/cascade/CascadeTest.java 2008-10-08 23:02:47 UTC (rev 15294)
+++ entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/cascade/CascadeTest.java 2008-10-08 23:09:58 UTC (rev 15295)
@@ -14,7 +14,7 @@
public void testCascade() throws Exception {
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Teacher teacher = null;
@@ -33,7 +33,7 @@
em.getTransaction().commit();
System.out.println("***************************");
- em = factory.createEntityManager();
+ em = getOrCreateEntityManager();
em.getTransaction().begin();
Teacher foundTeacher = (Teacher) em.createQuery( "select t from Teacher as t" ).getSingleResult();
@@ -59,7 +59,7 @@
e1.setAuthor(e2);
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(e2);
@@ -67,7 +67,7 @@
tx.commit();
em.close();
- em = factory.createEntityManager();
+ em = getOrCreateEntityManager();
e1 = em.find(Song.class, e1.getId());
e2 = null;
Modified: entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/cascade/DeleteOrphanTest.java
===================================================================
--- entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/cascade/DeleteOrphanTest.java 2008-10-08 23:02:47 UTC (rev 15294)
+++ entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/cascade/DeleteOrphanTest.java 2008-10-08 23:09:58 UTC (rev 15295)
@@ -20,7 +20,7 @@
public void testDeleteOrphan() throws Exception {
EntityTransaction tx;
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
tx = em.getTransaction();
tx.begin();
Troop disney = new Troop();
@@ -33,7 +33,7 @@
tx.commit();
em.close();
- em = factory.createEntityManager();
+ em = getOrCreateEntityManager();
tx = em.getTransaction();
tx.begin();
Troop troop = em.find( Troop.class, disney.getId() );
@@ -45,14 +45,14 @@
troop.getSoldiers().remove( soldier );
troop = (Troop) unserialize( serialize( troop ) );
- em = factory.createEntityManager();
+ em = getOrCreateEntityManager();
tx = em.getTransaction();
tx.begin();
em.merge( troop );
tx.commit();
em.close();
- em = factory.createEntityManager();
+ em = getOrCreateEntityManager();
tx = em.getTransaction();
tx.begin();
soldier = em.find( Soldier.class, mickey.getId() );
Modified: entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/cascade/FetchTest.java
===================================================================
--- entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/cascade/FetchTest.java 2008-10-08 23:02:47 UTC (rev 15294)
+++ entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/cascade/FetchTest.java 2008-10-08 23:09:58 UTC (rev 15295)
@@ -17,7 +17,7 @@
public class FetchTest extends TestCase {
public void testCascadeAndFetchCollection() throws Exception {
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Troop disney = new Troop();
disney.setName( "Disney" );
@@ -28,7 +28,7 @@
em.getTransaction().commit();
em.close();
- em = factory.createEntityManager();
+ em = getOrCreateEntityManager();
em.getTransaction().begin();
Troop troop = em.find( Troop.class, disney.getId() );
assertFalse( Hibernate.isInitialized( troop.getSoldiers() ) );
@@ -36,7 +36,7 @@
assertFalse( Hibernate.isInitialized( troop.getSoldiers() ) );
em.close();
- em = factory.createEntityManager();
+ em = getOrCreateEntityManager();
em.getTransaction().begin();
troop = em.find( Troop.class, disney.getId() );
em.remove( troop );
@@ -46,7 +46,7 @@
}
public void testCascadeAndFetchEntity() throws Exception {
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Troop disney = new Troop();
disney.setName( "Disney" );
@@ -57,14 +57,14 @@
em.getTransaction().commit();
em.close();
- em = factory.createEntityManager();
+ em = getOrCreateEntityManager();
em.getTransaction().begin();
Soldier soldier = em.find( Soldier.class, mickey.getId() );
assertFalse( Hibernate.isInitialized( soldier.getTroop() ) );
em.getTransaction().commit();
assertFalse( Hibernate.isInitialized( soldier.getTroop() ) );
em.close();
- em = factory.createEntityManager();
+ em = getOrCreateEntityManager();
em.getTransaction().begin();
Troop troop = em.find( Troop.class, disney.getId() );
em.remove( troop );
@@ -76,7 +76,7 @@
public void testTwoLevelDeepPersist() throws Exception {
EntityTransaction tx;
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
tx = em.getTransaction();
tx.begin();
Conference jbwBarcelona = new Conference();
@@ -94,7 +94,7 @@
tx.commit();
em.close();
- em = factory.createEntityManager();
+ em = getOrCreateEntityManager();
tx = em.getTransaction();
tx.begin();
jbwBarcelona = em.find( Conference.class, jbwBarcelona.getId() );
@@ -112,7 +112,7 @@
public void testTwoLevelDeepPersistOnManyToOne() throws Exception {
EntityTransaction tx;
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
tx = em.getTransaction();
tx.begin();
Grandson gs = new Grandson();
@@ -121,7 +121,7 @@
em.persist( gs );
tx.commit();
em.close();
- em = factory.createEntityManager();
+ em = getOrCreateEntityManager();
tx = em.getTransaction();
tx.begin();
gs = em.find( Grandson.class, gs.getId() );
@@ -134,7 +134,7 @@
}
public void testPerfCascadeAndFetchEntity() throws Exception {
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
//init data
em.getTransaction().begin();
int loop = 50;
@@ -150,7 +150,7 @@
em.close();
//Warm up loop
- em = factory.createEntityManager();
+ em = getOrCreateEntityManager();
em.getTransaction().begin();
for ( int i = 0; i < loop ; i++ ) {
//Soldier soldier = em.find( Soldier.class, new Integer(i) );
@@ -167,7 +167,7 @@
//do not evict
for ( int j = 0; j < 10 ; j++ ) {
- em = factory.createEntityManager();
+ em = getOrCreateEntityManager();
em.getTransaction().begin();
for ( int i = 0; i < loop ; i++ ) {
Troop troop = em.find( Troop.class, new Integer( i ) );
@@ -182,7 +182,7 @@
em.close();
//evict
- em = factory.createEntityManager();
+ em = getOrCreateEntityManager();
em.getTransaction().begin();
for ( int i = 0; i < loop ; i++ ) {
//Soldier soldier = em.find( Soldier.class, new Integer(i) );
Modified: entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/emops/FlushModeTest.java
===================================================================
--- entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/emops/FlushModeTest.java 2008-10-08 23:02:47 UTC (rev 15294)
+++ entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/emops/FlushModeTest.java 2008-10-08 23:09:58 UTC (rev 15295)
@@ -15,7 +15,7 @@
public void testCreateEMFlushMode() throws Exception {
Map properties = new HashMap();
properties.put( "org.hibernate.flushMode", "manual" );
- EntityManager em = factory.createEntityManager( properties );
+ EntityManager em = getOrCreateEntityManager( properties );
em.getTransaction().begin();
Dress dress = new Dress();
dress.name = "long dress";
Modified: entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/emops/GetReferenceTest.java
===================================================================
--- entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/emops/GetReferenceTest.java 2008-10-08 23:02:47 UTC (rev 15294)
+++ entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/emops/GetReferenceTest.java 2008-10-08 23:09:58 UTC (rev 15295)
@@ -12,7 +12,7 @@
public class GetReferenceTest extends TestCase {
public void testWrongIdType() throws Exception {
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
try {
Competitor c = em.getReference( Competitor.class, new String("30") );
fail("Expected IllegalArgumentException");
Modified: entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/emops/MergeTest.java
===================================================================
--- entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/emops/MergeTest.java 2008-10-08 23:02:47 UTC (rev 15294)
+++ entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/emops/MergeTest.java 2008-10-08 23:09:58 UTC (rev 15295)
@@ -14,7 +14,7 @@
race.competitors.add( new Competitor() );
race.competitors.add( new Competitor() );
race.competitors.add( new Competitor() );
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
em.persist( race );
em.flush();
@@ -32,7 +32,7 @@
public void testRemoveAndMerge() {
Race race = new Race();
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
em.persist( race );
em.flush();
@@ -57,7 +57,7 @@
public void testConcurrentMerge() {
Race race = new Race();
race.name = "Derby";
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
em.persist( race );
em.flush();
@@ -66,7 +66,7 @@
race.name = "Magnicourt";
- em = factory.createEntityManager();
+ em = getOrCreateEntityManager();
em.getTransaction().begin();
Race race2 = em.find(Race.class, race.id );
race2.name = "Mans";
@@ -76,7 +76,7 @@
em.getTransaction().commit();
em.close();
- em = factory.createEntityManager();
+ em = getOrCreateEntityManager();
em.getTransaction().begin();
race2 = em.find(Race.class, race.id );
assertEquals( "Last commit win in merge", "Magnicourt", race2.name );
Modified: entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/emops/RefreshTest.java
===================================================================
--- entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/emops/RefreshTest.java 2008-10-08 23:02:47 UTC (rev 15294)
+++ entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/emops/RefreshTest.java 2008-10-08 23:09:58 UTC (rev 15295)
@@ -11,7 +11,7 @@
public class RefreshTest extends TestCase {
public void testRefreshNonManaged() throws Exception {
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Race race = new Race();
em.persist( race );
Modified: entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/emops/RemoveTest.java
===================================================================
--- entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/emops/RemoveTest.java 2008-10-08 23:02:47 UTC (rev 15294)
+++ entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/emops/RemoveTest.java 2008-10-08 23:09:58 UTC (rev 15295)
@@ -14,7 +14,7 @@
race.competitors.add( new Competitor() );
race.competitors.add( new Competitor() );
race.competitors.add( new Competitor() );
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
em.persist( race );
em.flush();
@@ -26,7 +26,7 @@
public void testRemoveAndFind() {
Race race = new Race();
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
em.persist( race );
em.remove( race );
Modified: entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/exception/ExceptionTest.java
===================================================================
--- entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/exception/ExceptionTest.java 2008-10-08 23:02:47 UTC (rev 15294)
+++ entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/exception/ExceptionTest.java 2008-10-08 23:09:58 UTC (rev 15295)
@@ -15,7 +15,7 @@
public class ExceptionTest extends TestCase {
public void testOptimisticLockingException() throws Exception {
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
EntityManager em2 = factory.createEntityManager();
em.getTransaction().begin();
Music music = new Music();
@@ -23,11 +23,17 @@
em.persist( music );
em.getTransaction().commit();
- em2.getTransaction().begin();
- Music music2 = em2.find( Music.class, music.getId() );
- music2.setName( "HouseMusic" );
- em2.getTransaction().commit();
- em2.close();
+ try {
+ em2.getTransaction().begin();
+ Music music2 = em2.find( Music.class, music.getId() );
+ music2.setName( "HouseMusic" );
+ em2.getTransaction().commit();
+ } catch (Exception e) {
+ em2.getTransaction().rollback();
+ throw e;
+ } finally {
+ em2.close();
+ }
em.getTransaction().begin();
music.setName( "Rock" );
@@ -50,7 +56,7 @@
}
public void testEntityNotFoundException() throws Exception {
- EntityManager em = factory.createEntityManager( );
+ EntityManager em = getOrCreateEntityManager( );
Music music = em.getReference( Music.class, new Integer(-1) );
try {
music.getName();
Modified: entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/inheritance/InheritanceTest.java
===================================================================
--- entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/inheritance/InheritanceTest.java 2008-10-08 23:02:47 UTC (rev 15294)
+++ entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/inheritance/InheritanceTest.java 2008-10-08 23:09:58 UTC (rev 15295)
@@ -11,7 +11,7 @@
public class InheritanceTest extends TestCase {
public void testFind() throws Exception {
- EntityManager firstSession = factory.createEntityManager( );
+ EntityManager firstSession = getOrCreateEntityManager( );
Strawberry u = new Strawberry();
u.setSize( 12l );
firstSession.getTransaction().begin();
Modified: entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/lob/BlobTest.java
===================================================================
--- entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/lob/BlobTest.java 2008-10-08 23:02:47 UTC (rev 15294)
+++ entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/lob/BlobTest.java 2008-10-08 23:09:58 UTC (rev 15295)
@@ -18,7 +18,7 @@
public class BlobTest extends TestCase {
public void testBlobSerialization() throws Exception {
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Map image = new HashMap();
image.put( "meta", "metadata" );
@@ -31,7 +31,7 @@
em.persist( reader );
em.getTransaction().commit();
em.close(); //useless but y'a know
- em = factory.createEntityManager();
+ em = getOrCreateEntityManager();
em.getTransaction().begin();
reader = em.find( ImageReader.class, reader.getId() );
ObjectInputStream ois = new ObjectInputStream( reader.getImage().getBinaryStream() );
Modified: entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/lock/LockTest.java
===================================================================
--- entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/lock/LockTest.java 2008-10-08 23:02:47 UTC (rev 15294)
+++ entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/lock/LockTest.java 2008-10-08 23:09:58 UTC (rev 15295)
@@ -14,7 +14,7 @@
public void testLockRead() throws Exception {
Lock lock = new Lock();
lock.setName( "name" );
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
em.persist( lock );
em.getTransaction().commit();
@@ -35,7 +35,7 @@
public void testLockWrite() throws Exception {
Lock lock = new Lock();
lock.setName( "second" );
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
em.persist( lock );
em.getTransaction().commit();
Modified: entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/ops/MergeNewTest.java
===================================================================
--- entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/ops/MergeNewTest.java 2008-10-08 23:02:47 UTC (rev 15294)
+++ entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/ops/MergeNewTest.java 2008-10-08 23:09:58 UTC (rev 15295)
@@ -14,7 +14,7 @@
Workload load = new Workload();
load.name = "Cleaning";
load.load = 10;
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
load = em.merge( load );
assertNotNull( load.id );
@@ -28,20 +28,20 @@
Workload load = new Workload();
load.name = "Cleaning";
load.load = 10;
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
load = em.merge( load );
em.flush();
em.getTransaction().commit();
em.close();
- em = factory.createEntityManager();
+ em = getOrCreateEntityManager();
em.getTransaction().begin();
load = em.find( Workload.class, load.id );
em.remove( load );
em.flush();
em.getTransaction().commit();
em.close();
- em = factory.createEntityManager();
+ em = getOrCreateEntityManager();
em.getTransaction().begin();
em.merge( load );
em.flush();
Modified: entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/transaction/FlushAndTransactionTest.java
===================================================================
--- entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/transaction/FlushAndTransactionTest.java 2008-10-08 23:02:47 UTC (rev 15294)
+++ entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/transaction/FlushAndTransactionTest.java 2008-10-08 23:09:58 UTC (rev 15295)
@@ -21,7 +21,7 @@
public void testAlwaysTransactionalOperations() throws Exception {
Book book = new Book();
book.name = "Le petit prince";
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
em.persist( book );
em.getTransaction().commit();
@@ -47,7 +47,7 @@
// public void testTransactionalOperationsWhenTransactional() throws Exception {
// Book book = new Book();
// book.name = "Le petit prince";
-// EntityManager em = factory.createEntityManager( PersistenceContextType.TRANSACTION );
+// EntityManager em = getOrCreateEntityManager( PersistenceContextType.TRANSACTION );
// try {
// em.persist( book );
// fail("flush has to be inside a Tx");
@@ -75,7 +75,7 @@
public void testTransactionalOperationsWhenExtended() throws Exception {
Book book = new Book();
book.name = "Le petit prince";
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
Statistics stats = ( (HibernateEntityManagerFactory) factory ).getSessionFactory().getStatistics();
stats.clear();
stats.setStatisticsEnabled( true );
@@ -118,7 +118,7 @@
public void testMergeWhenExtended() throws Exception {
Book book = new Book();
book.name = "Le petit prince";
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
Statistics stats = ( (HibernateEntityManagerFactory) factory ).getSessionFactory().getStatistics();
em.getTransaction().begin();
@@ -159,7 +159,7 @@
}
public void testCloseAndTransaction() throws Exception {
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Book book = new Book();
book.name = "Java for Dummies";
@@ -176,7 +176,7 @@
}
em.getTransaction().commit();
assertFalse( em.isOpen() );
- em = factory.createEntityManager();
+ em = getOrCreateEntityManager();
em.getTransaction().begin();
book = em.find( Book.class, book.id );
assertEquals( "C# for Dummies", book.name );
@@ -186,14 +186,14 @@
}
public void testTransactionCommitDoesNotFlush() throws Exception {
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Book book = new Book();
book.name = "Java for Dummies";
em.persist( book );
em.getTransaction().commit();
em.close();
- em = factory.createEntityManager();
+ em = getOrCreateEntityManager();
em.getTransaction().begin();
List result = em.createQuery("select book from Book book where book.name = :title").
setParameter( "title", book.name ).getResultList();
@@ -206,7 +206,7 @@
Book book = new Book();
book.name = "Stolen keys";
book.id = null; //new Integer( 50 );
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
try {
em.persist( book );
@@ -241,7 +241,7 @@
Book book = new Book();
book.name = "Stolen keys";
book.id = null; //new Integer( 50 );
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
em.persist( book );
em.flush();
@@ -268,7 +268,7 @@
public void testRollbackClearPC() throws Exception {
Book book = new Book();
book.name = "Stolen keys";
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
em.persist( book );
em.getTransaction().commit();
Modified: entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/xml/XmlAttributeOverrideTest.java
===================================================================
--- entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/xml/XmlAttributeOverrideTest.java 2008-10-08 23:02:47 UTC (rev 15294)
+++ entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/xml/XmlAttributeOverrideTest.java 2008-10-08 23:09:58 UTC (rev 15295)
@@ -11,7 +11,7 @@
public class XmlAttributeOverrideTest extends TestCase {
public void testAttributeOverriding() throws Exception {
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Employee e = new Employee();
Modified: entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/xml/XmlTest.java
===================================================================
--- entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/xml/XmlTest.java 2008-10-08 23:02:47 UTC (rev 15294)
+++ entitymanager/branches/v3_2_1_GA_CP/src/test/org/hibernate/ejb/test/xml/XmlTest.java 2008-10-08 23:09:58 UTC (rev 15295)
@@ -10,7 +10,7 @@
*/
public class XmlTest extends TestCase {
public void testXmlMappingCorrectness() throws Exception {
- EntityManager em = factory.createEntityManager();
+ EntityManager em = getOrCreateEntityManager();
em.close();
}
16 years, 2 months
Hibernate SVN: r15294 - in core/branches/Branch_3_2_4_SP1_CP: src/org/hibernate/hql/ast and 1 other directories.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2008-10-08 19:02:47 -0400 (Wed, 08 Oct 2008)
New Revision: 15294
Modified:
core/branches/Branch_3_2_4_SP1_CP/src/org/hibernate/dialect/DB2Dialect.java
core/branches/Branch_3_2_4_SP1_CP/src/org/hibernate/dialect/Dialect.java
core/branches/Branch_3_2_4_SP1_CP/src/org/hibernate/hql/ast/HqlSqlWalker.java
core/branches/Branch_3_2_4_SP1_CP/test/org/hibernate/test/hql/BulkManipulationTest.java
Log:
JBPAPP-949 : parameters in select clause
Modified: core/branches/Branch_3_2_4_SP1_CP/src/org/hibernate/dialect/DB2Dialect.java
===================================================================
--- core/branches/Branch_3_2_4_SP1_CP/src/org/hibernate/dialect/DB2Dialect.java 2008-10-08 22:59:59 UTC (rev 15293)
+++ core/branches/Branch_3_2_4_SP1_CP/src/org/hibernate/dialect/DB2Dialect.java 2008-10-08 23:02:47 UTC (rev 15294)
@@ -351,12 +351,28 @@
return false;
}
+ /**
+ * {@inheritDoc}
+ * <p/>
+ * DB2 is know to support parameters in the <tt>SELECT</tt> clause, but only in casted form
+ * (see {@link #requiresCastingOfParametersInSelectClause()}).
+ *
+ * @return True.
+ */
public boolean supportsParametersInInsertSelect() {
- // DB2 known to not support parameters within the select
- // clause of an SQL INSERT ... SELECT ... statement
- return false;
+ return true;
}
+ /**
+ * DB2 in fact does require that parameters appearing in the select clause be wrapped in cast() calls
+ * to tell the DB parser the type of the select value.
+ *
+ * @return True.
+ */
+ public boolean requiresCastingOfParametersInSelectClause() {
+ return true;
+ }
+
public boolean supportsResultSetPositionQueryMethodsOnForwardOnlyCursor() {
return false;
}
Modified: core/branches/Branch_3_2_4_SP1_CP/src/org/hibernate/dialect/Dialect.java
===================================================================
--- core/branches/Branch_3_2_4_SP1_CP/src/org/hibernate/dialect/Dialect.java 2008-10-08 22:59:59 UTC (rev 15293)
+++ core/branches/Branch_3_2_4_SP1_CP/src/org/hibernate/dialect/Dialect.java 2008-10-08 23:02:47 UTC (rev 15294)
@@ -1605,14 +1605,14 @@
}
/**
- * Does this dialect support casted parameters within the select clause of
- * INSERT ... SELECT ... cast( ? as <type> ) statements?
+ * Does this dialect require that parameters appearing in the <tt>SELECT</tt> clause be wrapped in <tt>cast()</tt>
+ * calls to tell the db parser the expected type.
*
- * @return True if this is supported; false otherwise.
+ * @return True if select clause parameter must be cast()ed
* @since 3.2
*/
- public boolean supportsCastedParametersInInsertSelect() {
- return true;
+ public boolean requiresCastingOfParametersInSelectClause() {
+ return false;
}
/**
Modified: core/branches/Branch_3_2_4_SP1_CP/src/org/hibernate/hql/ast/HqlSqlWalker.java
===================================================================
--- core/branches/Branch_3_2_4_SP1_CP/src/org/hibernate/hql/ast/HqlSqlWalker.java 2008-10-08 22:59:59 UTC (rev 15293)
+++ core/branches/Branch_3_2_4_SP1_CP/src/org/hibernate/hql/ast/HqlSqlWalker.java 2008-10-08 23:02:47 UTC (rev 15294)
@@ -651,38 +651,38 @@
AST versionValueNode = null;
if ( sessionFactoryHelper.getFactory().getDialect().supportsParametersInInsertSelect() ) {
- versionValueNode = getASTFactory().create( HqlSqlTokenTypes.PARAM, "?" );
- ParameterSpecification paramSpec = new VersionTypeSeedParameterSpecification( versionType );
- ( ( ParameterNode ) versionValueNode ).setHqlParameterSpecification( paramSpec );
- parameters.add( 0, paramSpec );
- }
- else if ( sessionFactoryHelper.getFactory().getDialect().supportsCastedParametersInInsertSelect() ) {
int sqlTypes[] = versionType.sqlTypes( sessionFactoryHelper.getFactory() );
if ( sqlTypes == null || sqlTypes.length == 0 ) {
- throw new AssertionFailure( versionType.getClass() + "sqlTypes() returns null or empty array" );
+ throw new IllegalStateException( versionType.getClass() + ".sqlTypes() returns null or empty array" );
}
if ( sqlTypes.length > 1 ) {
- throw new UnsupportedOperationException( versionType.getClass() +
- ".sqlTypes() returns > 1 element; only single-valued versions are allowed." );
+ throw new IllegalStateException(
+ versionType.getClass() +
+ ".sqlTypes() returns > 1 element; only single-valued versions are allowed."
+ );
}
- MethodNode versionMethodNode = ( MethodNode ) getASTFactory().create( HqlSqlTokenTypes.METHOD_CALL, "(" );
- AST methodIdentNode = getASTFactory().create( HqlSqlTokenTypes.IDENT, "cast" );
- versionMethodNode.initializeMethodNode(methodIdentNode, true );
- versionMethodNode.addChild( methodIdentNode );
- AST castExprListNode = getASTFactory().create( HqlSqlTokenTypes.EXPR_LIST, "exprList" );
- methodIdentNode.setNextSibling( castExprListNode );
- AST paramNode = getASTFactory().create( HqlSqlTokenTypes.PARAM, "?" );
+ versionValueNode = getASTFactory().create( HqlSqlTokenTypes.PARAM, "?" );
ParameterSpecification paramSpec = new VersionTypeSeedParameterSpecification( versionType );
- ( ( ParameterNode ) paramNode ).setHqlParameterSpecification( paramSpec );
- castExprListNode.addChild( paramNode );
- paramNode.setNextSibling(
- getASTFactory().create(
- HqlSqlTokenTypes.IDENT,
- sessionFactoryHelper.getFactory().getDialect().getTypeName( sqlTypes[0] ) )
- );
- processFunction( versionMethodNode, true );
- versionValueNode = versionMethodNode;
+ ( ( ParameterNode ) versionValueNode ).setHqlParameterSpecification( paramSpec );
parameters.add( 0, paramSpec );
+
+ if ( sessionFactoryHelper.getFactory().getDialect().requiresCastingOfParametersInSelectClause() ) {
+ // we need to wrtap the param in a cast()
+ MethodNode versionMethodNode = ( MethodNode ) getASTFactory().create( HqlSqlTokenTypes.METHOD_CALL, "(" );
+ AST methodIdentNode = getASTFactory().create( HqlSqlTokenTypes.IDENT, "cast" );
+ versionMethodNode.addChild( methodIdentNode );
+ versionMethodNode.initializeMethodNode(methodIdentNode, true );
+ AST castExprListNode = getASTFactory().create( HqlSqlTokenTypes.EXPR_LIST, "exprList" );
+ methodIdentNode.setNextSibling( castExprListNode );
+ castExprListNode.addChild( versionValueNode );
+ versionValueNode.setNextSibling(
+ getASTFactory().create(
+ HqlSqlTokenTypes.IDENT,
+ sessionFactoryHelper.getFactory().getDialect().getTypeName( sqlTypes[0] ) )
+ );
+ processFunction( versionMethodNode, true );
+ versionValueNode = versionMethodNode;
+ }
}
else {
if ( isIntegral( versionType ) ) {
Modified: core/branches/Branch_3_2_4_SP1_CP/test/org/hibernate/test/hql/BulkManipulationTest.java
===================================================================
--- core/branches/Branch_3_2_4_SP1_CP/test/org/hibernate/test/hql/BulkManipulationTest.java 2008-10-08 22:59:59 UTC (rev 15293)
+++ core/branches/Branch_3_2_4_SP1_CP/test/org/hibernate/test/hql/BulkManipulationTest.java 2008-10-08 23:02:47 UTC (rev 15294)
@@ -416,9 +416,8 @@
// dialects which do not allow a parameter in the select portion of an INSERT ... SELECT statement
// will also be problematic for this test because the timestamp here is vm-based as opposed to
// db-based.
- if ( !getDialect().supportsParametersInInsertSelect() &&
- !getDialect().supportsCastedParametersInInsertSelect() ) {
- reportSkip( "dialect does not support parameter in INSERT ... SELECT",
+ if ( ! getDialect().supportsParametersInInsertSelect() ) {
+ reportSkip( "dialect does not support parameter in INSERT ... SELECT",
"test bulk inserts with generated id and generated timestamp");
return;
}
16 years, 2 months
Hibernate SVN: r15293 - in core/branches/Branch_3_2: src/org/hibernate/hql/ast and 1 other directories.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2008-10-08 18:59:59 -0400 (Wed, 08 Oct 2008)
New Revision: 15293
Modified:
core/branches/Branch_3_2/src/org/hibernate/dialect/DB2Dialect.java
core/branches/Branch_3_2/src/org/hibernate/dialect/Dialect.java
core/branches/Branch_3_2/src/org/hibernate/hql/ast/HqlSqlWalker.java
core/branches/Branch_3_2/test/org/hibernate/test/hql/BulkManipulationTest.java
Log:
HHH-3519 : params in select clause
Modified: core/branches/Branch_3_2/src/org/hibernate/dialect/DB2Dialect.java
===================================================================
--- core/branches/Branch_3_2/src/org/hibernate/dialect/DB2Dialect.java 2008-10-08 20:03:23 UTC (rev 15292)
+++ core/branches/Branch_3_2/src/org/hibernate/dialect/DB2Dialect.java 2008-10-08 22:59:59 UTC (rev 15293)
@@ -351,12 +351,28 @@
return false;
}
+ /**
+ * {@inheritDoc}
+ * <p/>
+ * DB2 is know to support parameters in the <tt>SELECT</tt> clause, but only in casted form
+ * (see {@link #requiresCastingOfParametersInSelectClause()}).
+ *
+ * @return True.
+ */
public boolean supportsParametersInInsertSelect() {
- // DB2 known to not support parameters within the select
- // clause of an SQL INSERT ... SELECT ... statement
- return false;
+ return true;
}
+ /**
+ * DB2 in fact does require that parameters appearing in the select clause be wrapped in cast() calls
+ * to tell the DB parser the type of the select value.
+ *
+ * @return True.
+ */
+ public boolean requiresCastingOfParametersInSelectClause() {
+ return true;
+ }
+
public boolean supportsResultSetPositionQueryMethodsOnForwardOnlyCursor() {
return false;
}
Modified: core/branches/Branch_3_2/src/org/hibernate/dialect/Dialect.java
===================================================================
--- core/branches/Branch_3_2/src/org/hibernate/dialect/Dialect.java 2008-10-08 20:03:23 UTC (rev 15292)
+++ core/branches/Branch_3_2/src/org/hibernate/dialect/Dialect.java 2008-10-08 22:59:59 UTC (rev 15293)
@@ -1595,14 +1595,14 @@
}
/**
- * Does this dialect support casted parameters within the select clause of
- * INSERT ... SELECT ... cast( ? as <type> ) statements?
+ * Does this dialect require that parameters appearing in the <tt>SELECT</tt> clause be wrapped in <tt>cast()</tt>
+ * calls to tell the db parser the expected type.
*
- * @return True if this is supported; false otherwise.
+ * @return True if select clause parameter must be cast()ed
* @since 3.2
*/
- public boolean supportsCastedParametersInInsertSelect() {
- return true;
+ public boolean requiresCastingOfParametersInSelectClause() {
+ return false;
}
/**
Modified: core/branches/Branch_3_2/src/org/hibernate/hql/ast/HqlSqlWalker.java
===================================================================
--- core/branches/Branch_3_2/src/org/hibernate/hql/ast/HqlSqlWalker.java 2008-10-08 20:03:23 UTC (rev 15292)
+++ core/branches/Branch_3_2/src/org/hibernate/hql/ast/HqlSqlWalker.java 2008-10-08 22:59:59 UTC (rev 15293)
@@ -15,7 +15,6 @@
import org.apache.commons.logging.LogFactory;
import org.hibernate.QueryException;
import org.hibernate.HibernateException;
-import org.hibernate.AssertionFailure;
import org.hibernate.engine.JoinSequence;
import org.hibernate.engine.ParameterBinder;
import org.hibernate.engine.SessionFactoryImplementor;
@@ -662,39 +661,39 @@
AST versionValueNode = null;
if ( sessionFactoryHelper.getFactory().getDialect().supportsParametersInInsertSelect() ) {
- versionValueNode = getASTFactory().create( HqlSqlTokenTypes.PARAM, "?" );
- ParameterSpecification paramSpec = new VersionTypeSeedParameterSpecification( versionType );
- ( ( ParameterNode ) versionValueNode ).setHqlParameterSpecification( paramSpec );
- parameters.add( 0, paramSpec );
- }
- else if ( sessionFactoryHelper.getFactory().getDialect().supportsCastedParametersInInsertSelect() ) {
int sqlTypes[] = versionType.sqlTypes( sessionFactoryHelper.getFactory() );
if ( sqlTypes == null || sqlTypes.length == 0 ) {
- throw new AssertionFailure( versionType.getClass() + "sqlTypes() returns null or empty array" );
+ throw new IllegalStateException( versionType.getClass() + ".sqlTypes() returns null or empty array" );
}
if ( sqlTypes.length > 1 ) {
- throw new UnsupportedOperationException( versionType.getClass() +
- ".sqlTypes() returns > 1 element; only single-valued versions are allowed." );
+ throw new IllegalStateException(
+ versionType.getClass() +
+ ".sqlTypes() returns > 1 element; only single-valued versions are allowed."
+ );
}
- MethodNode versionMethodNode = ( MethodNode ) getASTFactory().create( HqlSqlTokenTypes.METHOD_CALL, "(" );
- AST methodIdentNode = getASTFactory().create( HqlSqlTokenTypes.IDENT, "cast" );
- versionMethodNode.initializeMethodNode(methodIdentNode, true );
- versionMethodNode.addChild( methodIdentNode );
- AST castExprListNode = getASTFactory().create( HqlSqlTokenTypes.EXPR_LIST, "exprList" );
- methodIdentNode.setNextSibling( castExprListNode );
- AST paramNode = getASTFactory().create( HqlSqlTokenTypes.PARAM, "?" );
+ versionValueNode = getASTFactory().create( HqlSqlTokenTypes.PARAM, "?" );
ParameterSpecification paramSpec = new VersionTypeSeedParameterSpecification( versionType );
- ( ( ParameterNode ) paramNode ).setHqlParameterSpecification( paramSpec );
- castExprListNode.addChild( paramNode );
- paramNode.setNextSibling(
- getASTFactory().create(
- HqlSqlTokenTypes.IDENT,
- sessionFactoryHelper.getFactory().getDialect().getTypeName( sqlTypes[0] ) )
- );
- processFunction( versionMethodNode, true );
- versionValueNode = versionMethodNode;
+ ( ( ParameterNode ) versionValueNode ).setHqlParameterSpecification( paramSpec );
parameters.add( 0, paramSpec );
+
+ if ( sessionFactoryHelper.getFactory().getDialect().requiresCastingOfParametersInSelectClause() ) {
+ // we need to wrtap the param in a cast()
+ MethodNode versionMethodNode = ( MethodNode ) getASTFactory().create( HqlSqlTokenTypes.METHOD_CALL, "(" );
+ AST methodIdentNode = getASTFactory().create( HqlSqlTokenTypes.IDENT, "cast" );
+ versionMethodNode.addChild( methodIdentNode );
+ versionMethodNode.initializeMethodNode(methodIdentNode, true );
+ AST castExprListNode = getASTFactory().create( HqlSqlTokenTypes.EXPR_LIST, "exprList" );
+ methodIdentNode.setNextSibling( castExprListNode );
+ castExprListNode.addChild( versionValueNode );
+ versionValueNode.setNextSibling(
+ getASTFactory().create(
+ HqlSqlTokenTypes.IDENT,
+ sessionFactoryHelper.getFactory().getDialect().getTypeName( sqlTypes[0] ) )
+ );
+ processFunction( versionMethodNode, true );
+ versionValueNode = versionMethodNode;
}
+ }
else {
if ( isIntegral( versionType ) ) {
try {
Modified: core/branches/Branch_3_2/test/org/hibernate/test/hql/BulkManipulationTest.java
===================================================================
--- core/branches/Branch_3_2/test/org/hibernate/test/hql/BulkManipulationTest.java 2008-10-08 20:03:23 UTC (rev 15292)
+++ core/branches/Branch_3_2/test/org/hibernate/test/hql/BulkManipulationTest.java 2008-10-08 22:59:59 UTC (rev 15293)
@@ -419,8 +419,7 @@
// dialects which do not allow a parameter in the select portion of an INSERT ... SELECT statement
// will also be problematic for this test because the timestamp here is vm-based as opposed to
// db-based.
- if ( !getDialect().supportsParametersInInsertSelect() &&
- !getDialect().supportsCastedParametersInInsertSelect() ) {
+ if ( ! getDialect().supportsParametersInInsertSelect() ) {
reportSkip( "dialect does not support parameter in INSERT ... SELECT",
"test bulk inserts with generated id and generated timestamp");
return;
16 years, 2 months
Hibernate SVN: r15292 - in search/trunk/src/java/org/hibernate/search: engine and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2008-10-08 16:03:23 -0400 (Wed, 08 Oct 2008)
New Revision: 15292
Added:
search/trunk/src/java/org/hibernate/search/bridge/LuceneOptions.java
search/trunk/src/java/org/hibernate/search/engine/LuceneOptionsImpl.java
Removed:
search/trunk/src/java/org/hibernate/search/bridge/LuceneOptions.java
Modified:
search/trunk/src/java/org/hibernate/search/engine/DocumentBuilder.java
Log:
HSEARCH-273 make LcueneOptions an interface and its implementation package visible
Deleted: search/trunk/src/java/org/hibernate/search/bridge/LuceneOptions.java
===================================================================
--- search/trunk/src/java/org/hibernate/search/bridge/LuceneOptions.java 2008-10-08 17:33:27 UTC (rev 15291)
+++ search/trunk/src/java/org/hibernate/search/bridge/LuceneOptions.java 2008-10-08 20:03:23 UTC (rev 15292)
@@ -1,49 +0,0 @@
-// $Id$
-package org.hibernate.search.bridge;
-
-import org.apache.lucene.document.Field.Index;
-import org.apache.lucene.document.Field.Store;
-import org.apache.lucene.document.Field.TermVector;
-
-/**
- * A wrapper class for Lucene parameters needed for indexing.
- *
- * @author Hardy Ferentschik
- */
-public class LuceneOptions {
- private final Store store;
- private final Index index;
- private final TermVector termVector;
- private final Float boost;
-
- public LuceneOptions(Store store, Index index, TermVector termVector, Float boost) {
- this.store = store;
- this.index = index;
- this.termVector = termVector;
- this.boost = boost;
- }
-
- public Store getStore() {
- return store;
- }
-
- public Index getIndex() {
- return index;
- }
-
- public TermVector getTermVector() {
- return termVector;
- }
-
- /**
- * @return the boost value. If <code>boost == null</code>, the default boost value
- * 1.0 is returned.
- */
- public Float getBoost() {
- if ( boost != null ) {
- return boost;
- } else {
- return 1.0f;
- }
- }
-}
\ No newline at end of file
Added: search/trunk/src/java/org/hibernate/search/bridge/LuceneOptions.java
===================================================================
--- search/trunk/src/java/org/hibernate/search/bridge/LuceneOptions.java (rev 0)
+++ search/trunk/src/java/org/hibernate/search/bridge/LuceneOptions.java 2008-10-08 20:03:23 UTC (rev 15292)
@@ -0,0 +1,22 @@
+package org.hibernate.search.bridge;
+
+import org.apache.lucene.document.Field;
+
+/**
+ * A wrapper class for Lucene parameters needed for indexing.
+ *
+ * @author Emmanuel Bernard
+ */
+public interface LuceneOptions {
+ Field.Store getStore();
+
+ Field.Index getIndex();
+
+ Field.TermVector getTermVector();
+
+ /**
+ * @return the boost value. If <code>boost == null</code>, the default boost value
+ * 1.0 is returned.
+ */
+ Float getBoost();
+}
Modified: search/trunk/src/java/org/hibernate/search/engine/DocumentBuilder.java
===================================================================
--- search/trunk/src/java/org/hibernate/search/engine/DocumentBuilder.java 2008-10-08 17:33:27 UTC (rev 15291)
+++ search/trunk/src/java/org/hibernate/search/engine/DocumentBuilder.java 2008-10-08 20:03:23 UTC (rev 15292)
@@ -49,6 +49,7 @@
import org.hibernate.search.bridge.LuceneOptions;
import org.hibernate.search.bridge.TwoWayFieldBridge;
import org.hibernate.search.bridge.TwoWayString2FieldBridgeAdaptor;
+import org.hibernate.search.engine.LuceneOptionsImpl;
import org.hibernate.search.impl.InitContext;
import org.hibernate.search.store.DirectoryProvider;
import org.hibernate.search.store.IndexShardingStrategy;
@@ -503,18 +504,39 @@
//TODO could we use T instead of EntityClass?
public void addWorkToQueue(Class entityClass, T entity, Serializable id, WorkType workType, List<LuceneWork> queue, SearchFactoryImplementor searchFactoryImplementor) {
//TODO with the caller loop we are in a n^2: optimize it using a HashMap for work recognition
+ List<LuceneWork> toDelete = new ArrayList<LuceneWork>();
+ boolean duplicateDelete = false;
for (LuceneWork luceneWork : queue) {
- //any work on the same entity should be ignored
+ //avoid unecessary duplicated work
if ( luceneWork.getEntityClass() == entityClass
) {
Serializable currentId = luceneWork.getId();
+ //currentId != null => either ADD or Delete work
if ( currentId != null && currentId.equals( id ) ) { //find a way to use Type.equals(x,y)
- return;
+ if (workType == WorkType.DELETE) { //TODO add PURGE?
+ //DELETE should have precedence over any update before (HSEARCH-257)
+ //if an Add work is here, remove it
+ //if an other delete is here remember but still search for Add
+ if (luceneWork instanceof AddLuceneWork) {
+ toDelete.add( luceneWork );
+ }
+ else if (luceneWork instanceof DeleteLuceneWork) {
+ duplicateDelete = true;
+ }
+ }
+ else {
+ //we can safely say we are out, the other work is an ADD
+ return;
+ }
}
//TODO do something to avoid multiple PURGE ALL and OPTIMIZE
}
+ }
+ for ( LuceneWork luceneWork : toDelete ) {
+ toDelete.remove( luceneWork );
+ }
+ if (duplicateDelete) return;
- }
boolean searchForContainers = false;
String idInString = idBridge.objectToString( id );
if ( workType == WorkType.ADD ) {
@@ -620,7 +642,7 @@
Field classField =
new Field( CLASS_FIELDNAME, instanceClass.getName(), Field.Store.YES, Field.Index.UN_TOKENIZED, Field.TermVector.NO );
doc.add( classField );
- LuceneOptions luceneOptions = new LuceneOptions( Field.Store.YES,
+ LuceneOptions luceneOptions = new LuceneOptionsImpl( Field.Store.YES,
Field.Index.UN_TOKENIZED, Field.TermVector.NO, idBoost );
idBridge.set( idKeywordName, id, doc, luceneOptions );
}
@@ -866,13 +888,13 @@
}
private LuceneOptions getClassLuceneOptions(int i) {
- LuceneOptions options = new LuceneOptions( classStores.get( i ),
+ LuceneOptions options = new LuceneOptionsImpl( classStores.get( i ),
classIndexes.get( i ), classTermVectors.get( i ), classBoosts.get( i ) );
return options;
}
private LuceneOptions getFieldLuceneOptions(int i, Float boost) {
- LuceneOptions options = new LuceneOptions( fieldStore.get( i ),
+ LuceneOptions options = new LuceneOptionsImpl( fieldStore.get( i ),
fieldIndex.get( i ), fieldTermVectors.get( i ), boost );
return options;
}
Copied: search/trunk/src/java/org/hibernate/search/engine/LuceneOptionsImpl.java (from rev 15291, search/trunk/src/java/org/hibernate/search/bridge/LuceneOptions.java)
===================================================================
--- search/trunk/src/java/org/hibernate/search/engine/LuceneOptionsImpl.java (rev 0)
+++ search/trunk/src/java/org/hibernate/search/engine/LuceneOptionsImpl.java 2008-10-08 20:03:23 UTC (rev 15292)
@@ -0,0 +1,52 @@
+// $Id$
+package org.hibernate.search.engine;
+
+import org.apache.lucene.document.Field.Index;
+import org.apache.lucene.document.Field.Store;
+import org.apache.lucene.document.Field.TermVector;
+
+import org.hibernate.search.bridge.LuceneOptions;
+
+/**
+ * A wrapper class for Lucene parameters needed for indexing.
+ * This is a package level class
+ *
+ * @author Hardy Ferentschik
+ */
+class LuceneOptionsImpl implements LuceneOptions {
+ private final Store store;
+ private final Index index;
+ private final TermVector termVector;
+ private final Float boost;
+
+ public LuceneOptionsImpl(Store store, Index index, TermVector termVector, Float boost) {
+ this.store = store;
+ this.index = index;
+ this.termVector = termVector;
+ this.boost = boost;
+ }
+
+ public Store getStore() {
+ return store;
+ }
+
+ public Index getIndex() {
+ return index;
+ }
+
+ public TermVector getTermVector() {
+ return termVector;
+ }
+
+ /**
+ * @return the boost value. If <code>boost == null</code>, the default boost value
+ * 1.0 is returned.
+ */
+ public Float getBoost() {
+ if ( boost != null ) {
+ return boost;
+ } else {
+ return 1.0f;
+ }
+ }
+}
\ No newline at end of file
Property changes on: search/trunk/src/java/org/hibernate/search/engine/LuceneOptionsImpl.java
___________________________________________________________________
Name: svn:keywords
+ Id
Name: svn:eol-style
+ native
16 years, 2 months
Hibernate SVN: r15291 - in core/trunk: core/src/main/java/org/hibernate/tuple/component and 3 other directories.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2008-10-08 13:33:27 -0400 (Wed, 08 Oct 2008)
New Revision: 15291
Added:
core/trunk/core/src/main/java/org/hibernate/tuple/component/ComponentTuplizerFactory.java
core/trunk/core/src/main/java/org/hibernate/tuple/entity/EntityTuplizerFactory.java
Modified:
core/trunk/core/src/main/java/org/hibernate/cfg/Configuration.java
core/trunk/core/src/main/java/org/hibernate/cfg/Settings.java
core/trunk/core/src/main/java/org/hibernate/tuple/component/ComponentEntityModeToTuplizerMapping.java
core/trunk/core/src/main/java/org/hibernate/tuple/entity/EntityEntityModeToTuplizerMapping.java
core/trunk/core/src/main/java/org/hibernate/tuple/entity/EntityTuplizer.java
core/trunk/core/src/main/java/org/hibernate/util/ReflectHelper.java
core/trunk/testsuite/src/test/java/org/hibernate/test/dynamicentity/tuplizer2/Customer.hbm.xml
core/trunk/testsuite/src/test/java/org/hibernate/test/dynamicentity/tuplizer2/ImprovedTuplizerDynamicEntityTest.java
Log:
HHH-3517 : default Tuplizer class setting
Modified: core/trunk/core/src/main/java/org/hibernate/cfg/Configuration.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/cfg/Configuration.java 2008-10-08 17:32:21 UTC (rev 15290)
+++ core/trunk/core/src/main/java/org/hibernate/cfg/Configuration.java 2008-10-08 17:33:27 UTC (rev 15291)
@@ -67,6 +67,8 @@
import org.hibernate.SessionFactory;
import org.hibernate.SessionFactoryObserver;
import org.hibernate.DuplicateMappingException;
+import org.hibernate.tuple.entity.EntityTuplizerFactory;
+import org.hibernate.tuple.component.ComponentTuplizerFactory;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.MySQLDialect;
import org.hibernate.dialect.function.SQLFunction;
@@ -182,6 +184,9 @@
protected Map sqlFunctions;
+ private EntityTuplizerFactory entityTuplizerFactory;
+// private ComponentTuplizerFactory componentTuplizerFactory; todo : HHH-3517 and HHH-1907
+
private Interceptor interceptor;
private Properties properties;
private EntityResolver entityResolver;
@@ -197,6 +202,15 @@
private transient Mapping mapping = buildMapping();
+ protected Configuration(SettingsFactory settingsFactory) {
+ this.settingsFactory = settingsFactory;
+ reset();
+ }
+
+ public Configuration() {
+ this( new SettingsFactory() );
+ }
+
protected void reset() {
classes = new HashMap();
imports = new HashMap();
@@ -228,17 +242,19 @@
eventListeners = new EventListeners();
sqlFunctions = new HashMap();
- }
- protected Configuration(SettingsFactory settingsFactory) {
- this.settingsFactory = settingsFactory;
- reset();
+ entityTuplizerFactory = new EntityTuplizerFactory();
+// componentTuplizerFactory = new ComponentTuplizerFactory();
}
- public Configuration() {
- this( new SettingsFactory() );
+ public EntityTuplizerFactory getEntityTuplizerFactory() {
+ return entityTuplizerFactory;
}
+// public ComponentTuplizerFactory getComponentTuplizerFactory() {
+// return componentTuplizerFactory;
+// }
+
/**
* Iterate the entity mappings
*
@@ -2092,13 +2108,20 @@
public Settings buildSettings() throws HibernateException {
Properties clone = ( Properties ) properties.clone();
PropertiesHelper.resolvePlaceHolders( clone );
- return settingsFactory.buildSettings( clone );
+ return buildSettingsInternal( clone );
}
public Settings buildSettings(Properties props) throws HibernateException {
- return settingsFactory.buildSettings( props );
+ return buildSettingsInternal( props );
}
+ private Settings buildSettingsInternal(Properties props) {
+ final Settings settings = settingsFactory.buildSettings( props );
+ settings.setEntityTuplizerFactory( this.getEntityTuplizerFactory() );
+// settings.setComponentTuplizerFactory( this.getComponentTuplizerFactory() );
+ return settings;
+ }
+
public Map getNamedSQLQueries() {
return namedSqlQueries;
}
Modified: core/trunk/core/src/main/java/org/hibernate/cfg/Settings.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/cfg/Settings.java 2008-10-08 17:32:21 UTC (rev 15290)
+++ core/trunk/core/src/main/java/org/hibernate/cfg/Settings.java 2008-10-08 17:33:27 UTC (rev 15291)
@@ -28,6 +28,8 @@
import org.hibernate.ConnectionReleaseMode;
import org.hibernate.EntityMode;
+import org.hibernate.tuple.entity.EntityTuplizerFactory;
+import org.hibernate.tuple.component.ComponentTuplizerFactory;
import org.hibernate.cache.QueryCacheFactory;
import org.hibernate.cache.RegionFactory;
import org.hibernate.connection.ConnectionProvider;
@@ -92,6 +94,8 @@
private boolean dataDefinitionInTransactionSupported;
private boolean strictJPAQLCompliance;
private boolean namedQueryStartupCheckingEnabled;
+ private EntityTuplizerFactory entityTuplizerFactory;
+// private ComponentTuplizerFactory componentTuplizerFactory; todo : HHH-3517 and HHH-1907
// private BytecodeProvider bytecodeProvider;
/**
@@ -286,9 +290,17 @@
return namedQueryStartupCheckingEnabled;
}
+ public EntityTuplizerFactory getEntityTuplizerFactory() {
+ return entityTuplizerFactory;
+ }
- // package protected setters ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+// public ComponentTuplizerFactory getComponentTuplizerFactory() {
+// return componentTuplizerFactory;
+// }
+
+// package protected setters ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
// void setShowSqlEnabled(boolean b) {
// showSql = b;
// }
@@ -473,7 +485,15 @@
this.namedQueryStartupCheckingEnabled = namedQueryStartupCheckingEnabled;
}
+ void setEntityTuplizerFactory(EntityTuplizerFactory entityTuplizerFactory) {
+ this.entityTuplizerFactory = entityTuplizerFactory;
+ }
+// void setComponentTuplizerFactory(ComponentTuplizerFactory componentTuplizerFactory) {
+// this.componentTuplizerFactory = componentTuplizerFactory;
+// }
+
+
// public BytecodeProvider getBytecodeProvider() {
// return bytecodeProvider;
// }
Modified: core/trunk/core/src/main/java/org/hibernate/tuple/component/ComponentEntityModeToTuplizerMapping.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/tuple/component/ComponentEntityModeToTuplizerMapping.java 2008-10-08 17:32:21 UTC (rev 15290)
+++ core/trunk/core/src/main/java/org/hibernate/tuple/component/ComponentEntityModeToTuplizerMapping.java 2008-10-08 17:33:27 UTC (rev 15291)
@@ -29,8 +29,6 @@
import org.hibernate.mapping.Component;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.EntityMode;
-import org.hibernate.HibernateException;
-import org.hibernate.util.ReflectHelper;
import java.util.Map;
import java.util.HashMap;
@@ -47,7 +45,8 @@
*/
class ComponentEntityModeToTuplizerMapping extends EntityModeToTuplizerMapping implements Serializable {
- private static final Class[] COMPONENT_TUP_CTOR_SIG = new Class[] { Component.class };
+ // todo : move this to SF per HHH-3517; also see HHH-1907 and ComponentMetamodel
+ private ComponentTuplizerFactory componentTuplizerFactory = new ComponentTuplizerFactory();
public ComponentEntityModeToTuplizerMapping(Component component) {
PersistentClass owner = component.getOwner();
@@ -59,24 +58,24 @@
}
// Build the dynamic-map tuplizer...
- Tuplizer dynamicMapTuplizer = null;
- String tuplizerImpl = ( String ) userSuppliedTuplizerImpls.remove( EntityMode.MAP );
- if ( tuplizerImpl == null ) {
- dynamicMapTuplizer = new DynamicMapComponentTuplizer( component );
+ Tuplizer dynamicMapTuplizer;
+ String tuplizerClassName = ( String ) userSuppliedTuplizerImpls.remove( EntityMode.MAP );
+ if ( tuplizerClassName == null ) {
+ dynamicMapTuplizer = componentTuplizerFactory.constructDefaultTuplizer( EntityMode.MAP, component );
}
else {
- dynamicMapTuplizer = buildComponentTuplizer( tuplizerImpl, component );
+ dynamicMapTuplizer = componentTuplizerFactory.constructTuplizer( tuplizerClassName, component );
}
// then the pojo tuplizer, using the dynamic-map tuplizer if no pojo representation is available
- tuplizerImpl = ( String ) userSuppliedTuplizerImpls.remove( EntityMode.POJO );
- Tuplizer pojoTuplizer = null;
+ tuplizerClassName = ( String ) userSuppliedTuplizerImpls.remove( EntityMode.POJO );
+ Tuplizer pojoTuplizer;
if ( owner.hasPojoRepresentation() && component.hasPojoRepresentation() ) {
- if ( tuplizerImpl == null ) {
- pojoTuplizer = new PojoComponentTuplizer( component );
+ if ( tuplizerClassName == null ) {
+ pojoTuplizer = componentTuplizerFactory.constructDefaultTuplizer( EntityMode.POJO, component );
}
else {
- pojoTuplizer = buildComponentTuplizer( tuplizerImpl, component );
+ pojoTuplizer = componentTuplizerFactory.constructTuplizer( tuplizerClassName, component );
}
}
else {
@@ -84,14 +83,14 @@
}
// then dom4j tuplizer, if dom4j representation is available
- Tuplizer dom4jTuplizer = null;
- tuplizerImpl = ( String ) userSuppliedTuplizerImpls.remove( EntityMode.DOM4J );
+ Tuplizer dom4jTuplizer;
+ tuplizerClassName = ( String ) userSuppliedTuplizerImpls.remove( EntityMode.DOM4J );
if ( owner.hasDom4jRepresentation() ) {
- if ( tuplizerImpl == null ) {
- dom4jTuplizer = new Dom4jComponentTuplizer( component );
+ if ( tuplizerClassName == null ) {
+ dom4jTuplizer = componentTuplizerFactory.constructDefaultTuplizer( EntityMode.DOM4J, component );
}
else {
- dom4jTuplizer = buildComponentTuplizer( tuplizerImpl, component );
+ dom4jTuplizer = componentTuplizerFactory.constructTuplizer( tuplizerClassName, component );
}
}
else {
@@ -113,21 +112,12 @@
if ( !userSuppliedTuplizerImpls.isEmpty() ) {
Iterator itr = userSuppliedTuplizerImpls.entrySet().iterator();
while ( itr.hasNext() ) {
- Map.Entry entry = ( Map.Entry ) itr.next();
- EntityMode entityMode = ( EntityMode ) entry.getKey();
- ComponentTuplizer tuplizer = buildComponentTuplizer( ( String ) entry.getValue(), component );
+ final Map.Entry entry = ( Map.Entry ) itr.next();
+ final EntityMode entityMode = ( EntityMode ) entry.getKey();
+ final String userTuplizerClassName = ( String ) entry.getValue();
+ ComponentTuplizer tuplizer = componentTuplizerFactory.constructTuplizer( userTuplizerClassName, component );
addTuplizer( entityMode, tuplizer );
}
}
}
-
- private ComponentTuplizer buildComponentTuplizer(String tuplizerImpl, Component component) {
- try {
- Class implClass = ReflectHelper.classForName( tuplizerImpl );
- return ( ComponentTuplizer ) implClass.getConstructor( COMPONENT_TUP_CTOR_SIG ).newInstance( new Object[] { component } );
- }
- catch( Throwable t ) {
- throw new HibernateException( "Could not build tuplizer [" + tuplizerImpl + "]", t );
- }
- }
}
Added: core/trunk/core/src/main/java/org/hibernate/tuple/component/ComponentTuplizerFactory.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/tuple/component/ComponentTuplizerFactory.java (rev 0)
+++ core/trunk/core/src/main/java/org/hibernate/tuple/component/ComponentTuplizerFactory.java 2008-10-08 17:33:27 UTC (rev 15291)
@@ -0,0 +1,160 @@
+/*
+ * 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.tuple.component;
+
+import java.util.Map;
+import java.lang.reflect.Constructor;
+import java.io.Serializable;
+
+import org.hibernate.util.FastHashMap;
+import org.hibernate.util.ReflectHelper;
+import org.hibernate.EntityMode;
+import org.hibernate.HibernateException;
+import org.hibernate.mapping.Component;
+
+/**
+ * A registry allowing users to define the default {@link ComponentTuplizer} class to use per {@link EntityMode}.
+ *
+ * @author Steve Ebersole
+ */
+public class ComponentTuplizerFactory implements Serializable {
+
+ private static final Class[] COMPONENT_TUP_CTOR_SIG = new Class[] { Component.class };
+
+ private Map defaultImplClassByMode = buildBaseMapping();
+
+ /**
+ * Method allowing registration of the tuplizer class to use as default for a particular entity-mode.
+ *
+ * @param entityMode The entity-mode for which to register the tuplizer class
+ * @param tuplizerClass The class to use as the default tuplizer for the given entity-mode.
+ */
+ public void registerDefaultTuplizerClass(EntityMode entityMode, Class tuplizerClass) {
+ assert isComponentTuplizerImplementor( tuplizerClass )
+ : "Specified tuplizer class [" + tuplizerClass.getName() + "] does not implement " + ComponentTuplizer.class.getName();
+ assert hasProperConstructor( tuplizerClass )
+ : "Specified tuplizer class [" + tuplizerClass.getName() + "] is not properly instantiatable";
+
+ defaultImplClassByMode.put( entityMode, tuplizerClass );
+ }
+
+ /**
+ * Construct an instance of the given tuplizer class.
+ *
+ * @param tuplizerClassName The name of the tuplizer class to instantiate
+ * @param metadata The metadata for the component.
+ *
+ * @return The instantiated tuplizer
+ *
+ * @throws HibernateException If class name cannot be resolved to a class reference, or if the
+ * {@link Constructor#newInstance} call fails.
+ */
+ public ComponentTuplizer constructTuplizer(String tuplizerClassName, Component metadata) {
+ try {
+ Class tuplizerClass = ReflectHelper.classForName( tuplizerClassName );
+ return constructTuplizer( tuplizerClass, metadata );
+ }
+ catch ( ClassNotFoundException e ) {
+ throw new HibernateException( "Could not locate specified tuplizer class [" + tuplizerClassName + "]" );
+ }
+ }
+
+ /**
+ * Construct an instance of the given tuplizer class.
+ *
+ * @param tuplizerClass The tuplizer class to instantiate
+ * @param metadata The metadata for the component.
+ *
+ * @return The instantiated tuplizer
+ *
+ * @throws HibernateException if the {@link java.lang.reflect.Constructor#newInstance} call fails.
+ */
+ public ComponentTuplizer constructTuplizer(Class tuplizerClass, Component metadata) {
+ Constructor ctor = getProperConstructor( tuplizerClass );
+ assert ctor != null : "Unable to locate proper constructor for tuplizer [" + tuplizerClass.getName() + "]";
+ try {
+ return ( ComponentTuplizer ) ctor.newInstance( new Object[] { metadata } );
+ }
+ catch ( Throwable t ) {
+ throw new HibernateException( "Unable to instantiate default tuplizer [" + tuplizerClass.getName() + "]", t );
+ }
+ }
+
+ /**
+ * Construct am instance of the default tuplizer for the given entity-mode.
+ *
+ * @param entityMode The entity mode for which to build a default tuplizer.
+ * @param metadata The metadata for the component.
+ *
+ * @return The instantiated tuplizer
+ *
+ * @throws HibernateException If no default tuplizer found for that entity-mode; may be re-thrown from
+ * {@link #constructTuplizer} too.
+ */
+ public ComponentTuplizer constructDefaultTuplizer(EntityMode entityMode, Component metadata) {
+ Class tuplizerClass = ( Class ) defaultImplClassByMode.get( entityMode );
+ if ( tuplizerClass == null ) {
+ throw new HibernateException( "could not determine default tuplizer class to use [" + entityMode + "]" );
+ }
+
+ return constructTuplizer( tuplizerClass, metadata );
+ }
+
+ private boolean isComponentTuplizerImplementor(Class tuplizerClass) {
+ return ReflectHelper.implementsInterface( tuplizerClass, ComponentTuplizer.class );
+ }
+
+ private boolean hasProperConstructor(Class tuplizerClass) {
+ return getProperConstructor( tuplizerClass ) != null;
+ }
+
+ private Constructor getProperConstructor(Class clazz) {
+ Constructor ctor = null;
+ try {
+ ctor = clazz.getDeclaredConstructor( COMPONENT_TUP_CTOR_SIG );
+ if ( ! ReflectHelper.isPublic( ctor ) ) {
+ try {
+ // found a ctor, but it was not publicly accessible so try to request accessibility
+ ctor.setAccessible( true );
+ }
+ catch ( SecurityException e ) {
+ ctor = null;
+ }
+ }
+ }
+ catch ( NoSuchMethodException ignore ) {
+ }
+
+ return ctor;
+ }
+
+ private static Map buildBaseMapping() {
+ Map map = new FastHashMap();
+ map.put( EntityMode.POJO, PojoComponentTuplizer.class );
+ map.put( EntityMode.DOM4J, Dom4jComponentTuplizer.class );
+ map.put( EntityMode.MAP, DynamicMapComponentTuplizer.class );
+ return map;
+ }
+}
\ No newline at end of file
Modified: core/trunk/core/src/main/java/org/hibernate/tuple/entity/EntityEntityModeToTuplizerMapping.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/tuple/entity/EntityEntityModeToTuplizerMapping.java 2008-10-08 17:32:21 UTC (rev 15290)
+++ core/trunk/core/src/main/java/org/hibernate/tuple/entity/EntityEntityModeToTuplizerMapping.java 2008-10-08 17:33:27 UTC (rev 15291)
@@ -28,8 +28,6 @@
import org.hibernate.tuple.Tuplizer;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.EntityMode;
-import org.hibernate.HibernateException;
-import org.hibernate.util.ReflectHelper;
import java.util.Iterator;
import java.util.Map;
@@ -46,8 +44,6 @@
*/
public class EntityEntityModeToTuplizerMapping extends EntityModeToTuplizerMapping implements Serializable {
- private static final Class[] ENTITY_TUP_CTOR_SIG = new Class[] { EntityMetamodel.class, PersistentClass.class };
-
/**
* Instantiates a EntityEntityModeToTuplizerMapping based on the given
* entity mapping and metamodel definitions.
@@ -56,6 +52,10 @@
* @param em The entity metamodel definition.
*/
public EntityEntityModeToTuplizerMapping(PersistentClass mappedEntity, EntityMetamodel em) {
+ final EntityTuplizerFactory entityTuplizerFactory = em.getSessionFactory()
+ .getSettings()
+ .getEntityTuplizerFactory();
+
// create our own copy of the user-supplied tuplizer impl map
Map userSuppliedTuplizerImpls = new HashMap();
if ( mappedEntity.getTuplizerMap() != null ) {
@@ -63,24 +63,24 @@
}
// Build the dynamic-map tuplizer...
- Tuplizer dynamicMapTuplizer = null;
- String tuplizerImpl = ( String ) userSuppliedTuplizerImpls.remove( EntityMode.MAP );
- if ( tuplizerImpl == null ) {
- dynamicMapTuplizer = new DynamicMapEntityTuplizer( em, mappedEntity );
+ Tuplizer dynamicMapTuplizer;
+ String tuplizerImplClassName = ( String ) userSuppliedTuplizerImpls.remove( EntityMode.MAP );
+ if ( tuplizerImplClassName == null ) {
+ dynamicMapTuplizer = entityTuplizerFactory.constructDefaultTuplizer( EntityMode.MAP, em, mappedEntity );
}
else {
- dynamicMapTuplizer = buildEntityTuplizer( tuplizerImpl, mappedEntity, em );
+ dynamicMapTuplizer = entityTuplizerFactory.constructTuplizer( tuplizerImplClassName, em, mappedEntity );
}
// then the pojo tuplizer, using the dynamic-map tuplizer if no pojo representation is available
- Tuplizer pojoTuplizer = null;
- tuplizerImpl = ( String ) userSuppliedTuplizerImpls.remove( EntityMode.POJO );
+ Tuplizer pojoTuplizer;
+ tuplizerImplClassName = ( String ) userSuppliedTuplizerImpls.remove( EntityMode.POJO );
if ( mappedEntity.hasPojoRepresentation() ) {
- if ( tuplizerImpl == null ) {
- pojoTuplizer = new PojoEntityTuplizer( em, mappedEntity );
+ if ( tuplizerImplClassName == null ) {
+ pojoTuplizer = entityTuplizerFactory.constructDefaultTuplizer( EntityMode.POJO, em, mappedEntity );
}
else {
- pojoTuplizer = buildEntityTuplizer( tuplizerImpl, mappedEntity, em );
+ pojoTuplizer = entityTuplizerFactory.constructTuplizer( tuplizerImplClassName, em, mappedEntity );
}
}
else {
@@ -88,14 +88,14 @@
}
// then dom4j tuplizer, if dom4j representation is available
- Tuplizer dom4jTuplizer = null;
- tuplizerImpl = ( String ) userSuppliedTuplizerImpls.remove( EntityMode.DOM4J );
+ Tuplizer dom4jTuplizer;
+ tuplizerImplClassName = ( String ) userSuppliedTuplizerImpls.remove( EntityMode.DOM4J );
if ( mappedEntity.hasDom4jRepresentation() ) {
- if ( tuplizerImpl == null ) {
- dom4jTuplizer = new Dom4jEntityTuplizer( em, mappedEntity );
+ if ( tuplizerImplClassName == null ) {
+ dom4jTuplizer = entityTuplizerFactory.constructDefaultTuplizer( EntityMode.DOM4J, em, mappedEntity );
}
else {
- dom4jTuplizer = buildEntityTuplizer( tuplizerImpl, mappedEntity, em );
+ dom4jTuplizer = entityTuplizerFactory.constructTuplizer( tuplizerImplClassName, em, mappedEntity );
}
}
else {
@@ -117,21 +117,12 @@
if ( !userSuppliedTuplizerImpls.isEmpty() ) {
Iterator itr = userSuppliedTuplizerImpls.entrySet().iterator();
while ( itr.hasNext() ) {
- Map.Entry entry = ( Map.Entry ) itr.next();
- EntityMode entityMode = ( EntityMode ) entry.getKey();
- EntityTuplizer tuplizer = buildEntityTuplizer( ( String ) entry.getValue(), mappedEntity, em );
+ final Map.Entry entry = ( Map.Entry ) itr.next();
+ final EntityMode entityMode = ( EntityMode ) entry.getKey();
+ final String tuplizerClassName = ( String ) entry.getValue();
+ final EntityTuplizer tuplizer = entityTuplizerFactory.constructTuplizer( tuplizerClassName, em, mappedEntity );
addTuplizer( entityMode, tuplizer );
}
}
}
-
- private static EntityTuplizer buildEntityTuplizer(String className, PersistentClass pc, EntityMetamodel em) {
- try {
- Class implClass = ReflectHelper.classForName( className );
- return ( EntityTuplizer ) implClass.getConstructor( ENTITY_TUP_CTOR_SIG ).newInstance( new Object[] { em, pc } );
- }
- catch( Throwable t ) {
- throw new HibernateException( "Could not build tuplizer [" + className + "]", t );
- }
- }
}
Modified: core/trunk/core/src/main/java/org/hibernate/tuple/entity/EntityTuplizer.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/tuple/entity/EntityTuplizer.java 2008-10-08 17:32:21 UTC (rev 15290)
+++ core/trunk/core/src/main/java/org/hibernate/tuple/entity/EntityTuplizer.java 2008-10-08 17:33:27 UTC (rev 15291)
@@ -238,4 +238,4 @@
* @throws HibernateException If we are unable to determine an entity-name within the inheritence hierarchy.
*/
public String determineConcreteSubclassEntityName(Object entityInstance, SessionFactoryImplementor factory);
-}
+}
\ No newline at end of file
Added: core/trunk/core/src/main/java/org/hibernate/tuple/entity/EntityTuplizerFactory.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/tuple/entity/EntityTuplizerFactory.java (rev 0)
+++ core/trunk/core/src/main/java/org/hibernate/tuple/entity/EntityTuplizerFactory.java 2008-10-08 17:33:27 UTC (rev 15291)
@@ -0,0 +1,173 @@
+/*
+ * 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.tuple.entity;
+
+import java.util.Map;
+import java.lang.reflect.Constructor;
+import java.io.Serializable;
+
+
+import org.hibernate.util.FastHashMap;
+import org.hibernate.util.ReflectHelper;
+import org.hibernate.EntityMode;
+import org.hibernate.HibernateException;
+import org.hibernate.mapping.PersistentClass;
+
+/**
+ * A registry allowing users to define the default {@link EntityTuplizer} class to use per {@link EntityMode}.
+ *
+ * @author Steve Ebersole
+ */
+public class EntityTuplizerFactory implements Serializable {
+
+ public static final Class[] ENTITY_TUP_CTOR_SIG = new Class[] { EntityMetamodel.class, PersistentClass.class };
+
+ private Map defaultImplClassByMode = buildBaseMapping();
+
+ /**
+ * Method allowing registration of the tuplizer class to use as default for a particular entity-mode.
+ *
+ * @param entityMode The entity-mode for which to register the tuplizer class
+ * @param tuplizerClass The class to use as the default tuplizer for the given entity-mode.
+ */
+ public void registerDefaultTuplizerClass(EntityMode entityMode, Class tuplizerClass) {
+ assert isEntityTuplizerImplementor( tuplizerClass )
+ : "Specified tuplizer class [" + tuplizerClass.getName() + "] does not implement " + EntityTuplizer.class.getName();
+ assert hasProperConstructor( tuplizerClass )
+ : "Specified tuplizer class [" + tuplizerClass.getName() + "] is not properly instantiatable";
+
+ defaultImplClassByMode.put( entityMode, tuplizerClass );
+ }
+
+ /**
+ * Construct an instance of the given tuplizer class.
+ *
+ * @param tuplizerClassName The name of the tuplizer class to instantiate
+ * @param metamodel The metadata for the entity.
+ * @param persistentClass The mapping info for the entity.
+ *
+ * @return The instantiated tuplizer
+ *
+ * @throws HibernateException If class name cannot be resolved to a class reference, or if the
+ * {@link Constructor#newInstance} call fails.
+ */
+ public EntityTuplizer constructTuplizer(
+ String tuplizerClassName,
+ EntityMetamodel metamodel,
+ PersistentClass persistentClass) {
+ try {
+ Class tuplizerClass = ReflectHelper.classForName( tuplizerClassName );
+ return constructTuplizer( tuplizerClass, metamodel, persistentClass );
+ }
+ catch ( ClassNotFoundException e ) {
+ throw new HibernateException( "Could not locate specified tuplizer class [" + tuplizerClassName + "]" );
+ }
+ }
+
+ /**
+ * Construct an instance of the given tuplizer class.
+ *
+ * @param tuplizerClass The tuplizer class to instantiate
+ * @param metamodel The metadata for the entity.
+ * @param persistentClass The mapping info for the entity.
+ *
+ * @return The instantiated tuplizer
+ *
+ * @throws HibernateException if the {@link Constructor#newInstance} call fails.
+ */
+ public EntityTuplizer constructTuplizer(
+ Class tuplizerClass,
+ EntityMetamodel metamodel,
+ PersistentClass persistentClass) {
+ Constructor ctor = getProperConstructor( tuplizerClass );
+ assert ctor != null : "Unable to locate proper constructor for tuplizer [" + tuplizerClass.getName() + "]";
+ try {
+ return ( EntityTuplizer ) ctor.newInstance( new Object[] { metamodel, persistentClass } );
+ }
+ catch ( Throwable t ) {
+ throw new HibernateException( "Unable to instantiate default tuplizer [" + tuplizerClass.getName() + "]", t );
+ }
+ }
+
+ /**
+ * Construct am instance of the default tuplizer for the given entity-mode.
+ *
+ * @param entityMode The entity mode for which to build a default tuplizer.
+ * @param metamodel The entity metadata.
+ * @param persistentClass The entity mapping info.
+ *
+ * @return The instantiated tuplizer
+ *
+ * @throws HibernateException If no default tuplizer found for that entity-mode; may be re-thrown from
+ * {@link #constructTuplizer} too.
+ */
+ public EntityTuplizer constructDefaultTuplizer(
+ EntityMode entityMode,
+ EntityMetamodel metamodel,
+ PersistentClass persistentClass) {
+ Class tuplizerClass = ( Class ) defaultImplClassByMode.get( entityMode );
+ if ( tuplizerClass == null ) {
+ throw new HibernateException( "could not determine default tuplizer class to use [" + entityMode + "]" );
+ }
+
+ return constructTuplizer( tuplizerClass, metamodel, persistentClass );
+ }
+
+ private boolean isEntityTuplizerImplementor(Class tuplizerClass) {
+ return ReflectHelper.implementsInterface( tuplizerClass, EntityTuplizer.class );
+ }
+
+ private boolean hasProperConstructor(Class tuplizerClass) {
+ return getProperConstructor( tuplizerClass ) != null;
+ }
+
+ private Constructor getProperConstructor(Class clazz) {
+ Constructor ctor = null;
+ try {
+ ctor = clazz.getDeclaredConstructor( ENTITY_TUP_CTOR_SIG );
+ if ( ! ReflectHelper.isPublic( ctor ) ) {
+ try {
+ // found a ctor, but it was not publicly accessible so try to request accessibility
+ ctor.setAccessible( true );
+ }
+ catch ( SecurityException e ) {
+ ctor = null;
+ }
+ }
+ }
+ catch ( NoSuchMethodException ignore ) {
+ }
+
+ return ctor;
+ }
+
+ private static Map buildBaseMapping() {
+ Map map = new FastHashMap();
+ map.put( EntityMode.POJO, PojoEntityTuplizer.class );
+ map.put( EntityMode.DOM4J, Dom4jEntityTuplizer.class );
+ map.put( EntityMode.MAP, DynamicMapEntityTuplizer.class );
+ return map;
+ }
+}
Modified: core/trunk/core/src/main/java/org/hibernate/util/ReflectHelper.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/util/ReflectHelper.java 2008-10-08 17:32:21 UTC (rev 15290)
+++ core/trunk/core/src/main/java/org/hibernate/util/ReflectHelper.java 2008-10-08 17:33:27 UTC (rev 15291)
@@ -39,78 +39,154 @@
import org.hibernate.type.PrimitiveType;
import org.hibernate.type.Type;
-
+/**
+ * Utility class for various reflection operations.
+ *
+ * @author Gavin King
+ * @author Steve Ebersole
+ */
public final class ReflectHelper {
//TODO: this dependency is kinda Bad
private static final PropertyAccessor BASIC_PROPERTY_ACCESSOR = new BasicPropertyAccessor();
private static final PropertyAccessor DIRECT_PROPERTY_ACCESSOR = new DirectPropertyAccessor();
- private static final Class[] NO_CLASSES = new Class[0];
- private static final Class[] OBJECT = new Class[] { Object.class };
+ public static final Class[] NO_PARAM_SIGNATURE = new Class[0];
+ public static final Object[] NO_PARAMS = new Object[0];
+
+ public static final Class[] SINGLE_OBJECT_PARAM_SIGNATURE = new Class[] { Object.class };
+
private static final Method OBJECT_EQUALS;
- private static final Class[] NO_PARAM = new Class[] { };
+ private static final Method OBJECT_HASHCODE;
- private static final Method OBJECT_HASHCODE;
static {
Method eq;
Method hash;
try {
- eq = Object.class.getMethod("equals", OBJECT);
- hash = Object.class.getMethod("hashCode", NO_PARAM);
+ eq = extractEqualsMethod( Object.class );
+ hash = extractHashCodeMethod( Object.class );
}
- catch (Exception e) {
- throw new AssertionFailure("Could not find Object.equals() or Object.hashCode()", e);
+ catch ( Exception e ) {
+ throw new AssertionFailure( "Could not find Object.equals() or Object.hashCode()", e );
}
OBJECT_EQUALS = eq;
OBJECT_HASHCODE = hash;
}
+ /**
+ * Disallow instantiation of ReflectHelper.
+ */
+ private ReflectHelper() {
+ }
+
+ /**
+ * Encapsulation of getting hold of a class's {@link Object#equals equals} method.
+ *
+ * @param clazz The class from which to extract the equals method.
+ * @return The equals method reference
+ * @throws NoSuchMethodException Should indicate an attempt to extract equals method from interface.
+ */
+ public static Method extractEqualsMethod(Class clazz) throws NoSuchMethodException {
+ return clazz.getMethod( "equals", SINGLE_OBJECT_PARAM_SIGNATURE );
+ }
+
+ /**
+ * Encapsulation of getting hold of a class's {@link Object#hashCode hashCode} method.
+ *
+ * @param clazz The class from which to extract the hashCode method.
+ * @return The hashCode method reference
+ * @throws NoSuchMethodException Should indicate an attempt to extract hashCode method from interface.
+ */
+ public static Method extractHashCodeMethod(Class clazz) throws NoSuchMethodException {
+ return clazz.getMethod( "hashCode", NO_PARAM_SIGNATURE );
+ }
+
+ /**
+ * Determine if the given class defines an {@link Object#equals} override.
+ *
+ * @param clazz The class to check
+ * @return True if clazz defines an equals override.
+ */
public static boolean overridesEquals(Class clazz) {
Method equals;
try {
- equals = clazz.getMethod("equals", OBJECT);
+ equals = extractEqualsMethod( clazz );
}
- catch (NoSuchMethodException nsme) {
+ catch ( NoSuchMethodException nsme ) {
return false; //its an interface so we can't really tell anything...
}
- return !OBJECT_EQUALS.equals(equals);
+ return !OBJECT_EQUALS.equals( equals );
}
+ /**
+ * Determine if the given class defines a {@link Object#hashCode} override.
+ *
+ * @param clazz The class to check
+ * @return True if clazz defines an hashCode override.
+ */
public static boolean overridesHashCode(Class clazz) {
Method hashCode;
try {
- hashCode = clazz.getMethod("hashCode", NO_PARAM);
+ hashCode = extractHashCodeMethod( clazz );
}
- catch (NoSuchMethodException nsme) {
+ catch ( NoSuchMethodException nsme ) {
return false; //its an interface so we can't really tell anything...
}
- return !OBJECT_HASHCODE.equals(hashCode);
+ return !OBJECT_HASHCODE.equals( hashCode );
}
- public static Class reflectedPropertyClass(String className, String name) throws MappingException {
- try {
- Class clazz = ReflectHelper.classForName(className);
- return getter(clazz, name).getReturnType();
+ /**
+ * Determine if the given class implements the given interface.
+ *
+ * @param clazz The class to check
+ * @param intf The interface to check it against.
+ * @return True if the class does implement the interface, false otherwise.
+ */
+ public static boolean implementsInterface(Class clazz, Class intf) {
+ assert intf.isInterface() : "Interface to check was not an interface";
+
+ Class[] interfaces = clazz.getInterfaces();
+ for ( int i = 0; i < interfaces.length; i++ ) {
+ if ( intf.isAssignableFrom( interfaces[i] ) ) {
+ return true;
+ }
}
- catch (ClassNotFoundException cnfe) {
- throw new MappingException("class " + className + " not found while looking for property: " + name, cnfe);
- }
+ return false;
}
- private static Getter getter(Class clazz, String name) throws MappingException {
+ /**
+ * Perform resolution of a class name.
+ * <p/>
+ * Here we first check the context classloader, if one, before delegating to
+ * {@link Class#forName(String, boolean, ClassLoader)} using the caller's classloader
+ *
+ * @param name The class name
+ * @param caller The class from which this call originated (in order to access that class's loader).
+ * @return The class reference.
+ * @throws ClassNotFoundException From {@link Class#forName(String, boolean, ClassLoader)}.
+ */
+ public static Class classForName(String name, Class caller) throws ClassNotFoundException {
try {
- return BASIC_PROPERTY_ACCESSOR.getGetter(clazz, name);
+ ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
+ if ( contextClassLoader != null ) {
+ return contextClassLoader.loadClass( name );
+ }
}
- catch (PropertyNotFoundException pnfe) {
- return DIRECT_PROPERTY_ACCESSOR.getGetter(clazz, name);
+ catch ( Throwable ignore ) {
}
+ return Class.forName( name, true, caller.getClassLoader() );
}
- public static Getter getGetter(Class theClass, String name) throws MappingException {
- return BASIC_PROPERTY_ACCESSOR.getGetter(theClass, name);
- }
-
+ /**
+ * Perform resolution of a class name.
+ * <p/>
+ * Same as {@link #classForName(String, Class)} except that here we delegate to
+ * {@link Class#forName(String)} if the context classloader lookup is unsuccessful.
+ *
+ * @param name The class name
+ * @return The class reference.
+ * @throws ClassNotFoundException From {@link Class#forName(String)}.
+ */
public static Class classForName(String name) throws ClassNotFoundException {
try {
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
@@ -118,27 +194,79 @@
return contextClassLoader.loadClass(name);
}
}
- catch ( Throwable t ) {
+ catch ( Throwable ignore ) {
}
return Class.forName( name );
}
- public static Class classForName(String name, Class caller) throws ClassNotFoundException {
+ /**
+ * Is this member publicly accessible.
+ * <p/>
+ * Short-hand for {@link #isPublic(Class, Member)} passing the member + {@link Member#getDeclaringClass()}
+ *
+ * @param member The member to check
+ * @return True if the member is publicly accessible.
+ */
+ public static boolean isPublic(Member member) {
+ return isPublic( member.getDeclaringClass(), member );
+ }
+
+ /**
+ * Is this member publicly accessible.
+ *
+ * @param clazz The class which defines the member
+ * @param member The memeber.
+ * @return True if the member is publicly accessible, false otherwise.
+ */
+ public static boolean isPublic(Class clazz, Member member) {
+ return Modifier.isPublic( member.getModifiers() ) && Modifier.isPublic( clazz.getModifiers() );
+ }
+
+ /**
+ * Attempt to resolve the specified property type through reflection.
+ *
+ * @param className The name of the class owning the property.
+ * @param name The name of the property.
+ * @return The type of the property.
+ * @throws MappingException Indicates we were unable to locate the property.
+ */
+ public static Class reflectedPropertyClass(String className, String name) throws MappingException {
try {
- ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
- if ( contextClassLoader != null ) {
- return contextClassLoader.loadClass( name );
- }
+ Class clazz = ReflectHelper.classForName( className );
+ return getter( clazz, name ).getReturnType();
}
- catch ( Throwable e ) {
+ catch ( ClassNotFoundException cnfe ) {
+ throw new MappingException( "class " + className + " not found while looking for property: " + name, cnfe );
}
- return Class.forName( name, true, caller.getClassLoader() );
}
- public static boolean isPublic(Class clazz, Member member) {
- return Modifier.isPublic( member.getModifiers() ) && Modifier.isPublic( clazz.getModifiers() );
+ private static Getter getter(Class clazz, String name) throws MappingException {
+ try {
+ return BASIC_PROPERTY_ACCESSOR.getGetter( clazz, name );
+ }
+ catch ( PropertyNotFoundException pnfe ) {
+ return DIRECT_PROPERTY_ACCESSOR.getGetter( clazz, name );
+ }
}
+ /**
+ * Directly retrieve the {@link Getter} reference via the {@link BasicPropertyAccessor}.
+ *
+ * @param theClass The class owning the property
+ * @param name The name of the property
+ * @return The getter.
+ * @throws MappingException Indicates we were unable to locate the property.
+ */
+ public static Getter getGetter(Class theClass, String name) throws MappingException {
+ return BASIC_PROPERTY_ACCESSOR.getGetter( theClass, name );
+ }
+
+ /**
+ * Resolve a constant to its actual value.
+ *
+ * @param name The name
+ * @return The value
+ */
public static Object getConstantValue(String name) {
Class clazz;
try {
@@ -148,61 +276,90 @@
return null;
}
try {
- return clazz.getField( StringHelper.unqualify( name ) ).get(null);
+ return clazz.getField( StringHelper.unqualify( name ) ).get( null );
}
catch ( Throwable t ) {
return null;
}
}
+ /**
+ * Retrieve the default (no arg) constructor from the given class.
+ *
+ * @param clazz The class for which to retrieve the default ctor.
+ * @return The default constructor.
+ * @throws PropertyNotFoundException Indicates there was not publicly accessible, no-arg constructor (todo : why PropertyNotFoundException???)
+ */
public static Constructor getDefaultConstructor(Class clazz) throws PropertyNotFoundException {
+ if ( isAbstractClass( clazz ) ) {
+ return null;
+ }
- if ( isAbstractClass(clazz) ) return null;
-
try {
- Constructor constructor = clazz.getDeclaredConstructor(NO_CLASSES);
- if ( !isPublic(clazz, constructor) ) {
- constructor.setAccessible(true);
+ Constructor constructor = clazz.getDeclaredConstructor( NO_PARAM_SIGNATURE );
+ if ( !isPublic( clazz, constructor ) ) {
+ constructor.setAccessible( true );
}
return constructor;
}
- catch (NoSuchMethodException nme) {
+ catch ( NoSuchMethodException nme ) {
throw new PropertyNotFoundException(
- "Object class " + clazz.getName() +
- " must declare a default (no-argument) constructor"
+ "Object class [" + clazz.getName() + "] must declare a default (no-argument) constructor"
);
}
-
}
+ /**
+ * Determine if the given class is declared abstract.
+ *
+ * @param clazz The class to check.
+ * @return True if the class is abstract, false otherwise.
+ */
public static boolean isAbstractClass(Class clazz) {
int modifier = clazz.getModifiers();
return Modifier.isAbstract(modifier) || Modifier.isInterface(modifier);
}
-
+
+ /**
+ * Determine is the given class is declared final.
+ *
+ * @param clazz The class to check.
+ * @return True if the class is final, flase otherwise.
+ */
public static boolean isFinalClass(Class clazz) {
return Modifier.isFinal( clazz.getModifiers() );
}
+ /**
+ * Retrieve a constructor for the given class, with arguments matching the specified Hibernate mapping
+ * {@link Type types}.
+ *
+ * @param clazz The class needing instantiation
+ * @param types The types representing the required ctor param signature
+ * @return The matching constructor.
+ * @throws PropertyNotFoundException Indicates we could not locate an appropriate constructor (todo : again with PropertyNotFoundException???)
+ */
public static Constructor getConstructor(Class clazz, Type[] types) throws PropertyNotFoundException {
final Constructor[] candidates = clazz.getConstructors();
- for ( int i=0; i<candidates.length; i++ ) {
+ for ( int i = 0; i < candidates.length; i++ ) {
final Constructor constructor = candidates[i];
final Class[] params = constructor.getParameterTypes();
- if ( params.length==types.length ) {
+ if ( params.length == types.length ) {
boolean found = true;
- for ( int j=0; j<params.length; j++ ) {
+ for ( int j = 0; j < params.length; j++ ) {
final boolean ok = params[j].isAssignableFrom( types[j].getReturnedClass() ) || (
- types[j] instanceof PrimitiveType &&
- params[j] == ( (PrimitiveType) types[j] ).getPrimitiveClass()
+ types[j] instanceof PrimitiveType &&
+ params[j] == ( ( PrimitiveType ) types[j] ).getPrimitiveClass()
);
- if (!ok) {
+ if ( !ok ) {
found = false;
break;
}
}
- if (found) {
- if ( !isPublic(clazz, constructor) ) constructor.setAccessible(true);
+ if ( found ) {
+ if ( !isPublic( clazz, constructor ) ) {
+ constructor.setAccessible( true );
+ }
return constructor;
}
}
@@ -219,6 +376,4 @@
}
}
- private ReflectHelper() {}
-
}
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/dynamicentity/tuplizer2/Customer.hbm.xml
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/dynamicentity/tuplizer2/Customer.hbm.xml 2008-10-08 17:32:21 UTC (rev 15290)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/dynamicentity/tuplizer2/Customer.hbm.xml 2008-10-08 17:33:27 UTC (rev 15291)
@@ -31,7 +31,6 @@
<hibernate-mapping package="org.hibernate.test.dynamicentity">
<class name="Person" table="t_person" discriminator-value="person" abstract="false">
- <tuplizer class="org.hibernate.test.dynamicentity.tuplizer2.MyEntityTuplizer" entity-mode="pojo"/>
<id name="id">
<generator class="native"/>
</id>
@@ -46,13 +45,11 @@
</set>
<subclass name="Customer" discriminator-value="customer" abstract="false">
- <tuplizer class="org.hibernate.test.dynamicentity.tuplizer2.MyEntityTuplizer" entity-mode="pojo"/>
<many-to-one name="company" cascade="none" column="comp_id"/>
</subclass>
</class>
<class name="Company" table="t_company" abstract="false">
- <tuplizer class="org.hibernate.test.dynamicentity.tuplizer2.MyEntityTuplizer" entity-mode="pojo"/>
<id name="id">
<generator class="native"/>
</id>
@@ -60,7 +57,6 @@
</class>
<class name="Address" table="t_address" abstract="false">
- <tuplizer class="org.hibernate.test.dynamicentity.tuplizer2.MyEntityTuplizer" entity-mode="pojo"/>
<id name="id">
<generator class="native"/>
</id>
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/dynamicentity/tuplizer2/ImprovedTuplizerDynamicEntityTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/dynamicentity/tuplizer2/ImprovedTuplizerDynamicEntityTest.java 2008-10-08 17:32:21 UTC (rev 15290)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/dynamicentity/tuplizer2/ImprovedTuplizerDynamicEntityTest.java 2008-10-08 17:33:27 UTC (rev 15291)
@@ -31,6 +31,7 @@
import org.hibernate.test.dynamicentity.Person;
import org.hibernate.Session;
import org.hibernate.Hibernate;
+import org.hibernate.EntityMode;
import org.hibernate.cfg.Configuration;
import org.hibernate.junit.functional.FunctionalTestCase;
import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
@@ -61,6 +62,7 @@
public void configure(Configuration cfg) {
super.configure( cfg );
+ cfg.getEntityTuplizerFactory().registerDefaultTuplizerClass( EntityMode.POJO, MyEntityTuplizer.class );
}
public static TestSuite suite() {
16 years, 2 months
Hibernate SVN: r15290 - core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/dynamicentity/tuplizer2.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2008-10-08 13:32:21 -0400 (Wed, 08 Oct 2008)
New Revision: 15290
Modified:
core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/dynamicentity/tuplizer2/Customer.hbm.xml
core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/dynamicentity/tuplizer2/ImprovedTuplizerDynamicEntityTest.java
Log:
HHH-3517 : default Tuplizer impls
Modified: core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/dynamicentity/tuplizer2/Customer.hbm.xml
===================================================================
--- core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/dynamicentity/tuplizer2/Customer.hbm.xml 2008-10-08 17:23:01 UTC (rev 15289)
+++ core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/dynamicentity/tuplizer2/Customer.hbm.xml 2008-10-08 17:32:21 UTC (rev 15290)
@@ -31,7 +31,6 @@
<hibernate-mapping package="org.hibernate.test.dynamicentity">
<class name="Person" table="t_person" discriminator-value="person" abstract="false">
- <tuplizer class="org.hibernate.test.dynamicentity.tuplizer2.MyEntityTuplizer" entity-mode="pojo"/>
<id name="id">
<generator class="native"/>
</id>
@@ -46,13 +45,11 @@
</set>
<subclass name="Customer" discriminator-value="customer" abstract="false">
- <tuplizer class="org.hibernate.test.dynamicentity.tuplizer2.MyEntityTuplizer" entity-mode="pojo"/>
<many-to-one name="company" cascade="none" column="comp_id"/>
</subclass>
</class>
<class name="Company" table="t_company" abstract="false">
- <tuplizer class="org.hibernate.test.dynamicentity.tuplizer2.MyEntityTuplizer" entity-mode="pojo"/>
<id name="id">
<generator class="native"/>
</id>
@@ -60,7 +57,6 @@
</class>
<class name="Address" table="t_address" abstract="false">
- <tuplizer class="org.hibernate.test.dynamicentity.tuplizer2.MyEntityTuplizer" entity-mode="pojo"/>
<id name="id">
<generator class="native"/>
</id>
Modified: core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/dynamicentity/tuplizer2/ImprovedTuplizerDynamicEntityTest.java
===================================================================
--- core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/dynamicentity/tuplizer2/ImprovedTuplizerDynamicEntityTest.java 2008-10-08 17:23:01 UTC (rev 15289)
+++ core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/dynamicentity/tuplizer2/ImprovedTuplizerDynamicEntityTest.java 2008-10-08 17:32:21 UTC (rev 15290)
@@ -31,6 +31,7 @@
import org.hibernate.test.dynamicentity.Person;
import org.hibernate.Session;
import org.hibernate.Hibernate;
+import org.hibernate.EntityMode;
import org.hibernate.cfg.Configuration;
import org.hibernate.junit.functional.FunctionalTestCase;
import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
@@ -61,6 +62,7 @@
public void configure(Configuration cfg) {
super.configure( cfg );
+ cfg.getEntityTuplizerFactory().registerDefaultTuplizerClass( EntityMode.POJO, MyEntityTuplizer.class );
}
public static TestSuite suite() {
16 years, 2 months
Hibernate SVN: r15289 - in core/branches/Branch_3_2: src/org/hibernate/tuple/component and 3 other directories.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2008-10-08 13:23:01 -0400 (Wed, 08 Oct 2008)
New Revision: 15289
Added:
core/branches/Branch_3_2/src/org/hibernate/tuple/component/ComponentTuplizerFactory.java
core/branches/Branch_3_2/src/org/hibernate/tuple/entity/EntityTuplizerFactory.java
Modified:
core/branches/Branch_3_2/src/org/hibernate/cfg/Configuration.java
core/branches/Branch_3_2/src/org/hibernate/cfg/Settings.java
core/branches/Branch_3_2/src/org/hibernate/tuple/component/ComponentEntityModeToTuplizerMapping.java
core/branches/Branch_3_2/src/org/hibernate/tuple/entity/EntityEntityModeToTuplizerMapping.java
core/branches/Branch_3_2/src/org/hibernate/tuple/entity/EntityTuplizer.java
core/branches/Branch_3_2/src/org/hibernate/util/ReflectHelper.java
core/branches/Branch_3_2/test/org/hibernate/test/dynamicentity/tuplizer2/Customer.hbm.xml
core/branches/Branch_3_2/test/org/hibernate/test/dynamicentity/tuplizer2/ImprovedTuplizerDynamicEntityTest.java
Log:
HHH-3517 : default Tuplizer impls
Modified: core/branches/Branch_3_2/src/org/hibernate/cfg/Configuration.java
===================================================================
--- core/branches/Branch_3_2/src/org/hibernate/cfg/Configuration.java 2008-10-08 17:21:15 UTC (rev 15288)
+++ core/branches/Branch_3_2/src/org/hibernate/cfg/Configuration.java 2008-10-08 17:23:01 UTC (rev 15289)
@@ -38,6 +38,7 @@
import org.hibernate.MappingException;
import org.hibernate.MappingNotFoundException;
import org.hibernate.SessionFactory;
+import org.hibernate.tuple.entity.EntityTuplizerFactory;
import org.hibernate.proxy.EntityNotFoundDelegate;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.MySQLDialect;
@@ -133,6 +134,10 @@
protected Map sqlFunctions;
protected Map namedQueries;
protected Map namedSqlQueries;
+
+ private EntityTuplizerFactory entityTuplizerFactory;
+// private ComponentTuplizerFactory componentTuplizerFactory; todo : HHH-3517 and HHH-1907
+
/**
* Map<String, SqlResultSetMapping> result set name, result set description
*/
@@ -158,6 +163,17 @@
protected final SettingsFactory settingsFactory;
+ private transient Mapping mapping = buildMapping();
+
+ protected Configuration(SettingsFactory settingsFactory) {
+ this.settingsFactory = settingsFactory;
+ reset();
+ }
+
+ public Configuration() {
+ this( new SettingsFactory() );
+ }
+
protected void reset() {
classes = new HashMap();
imports = new HashMap();
@@ -182,20 +198,17 @@
columnNameBindingPerTable = new HashMap();
namingStrategy = DefaultNamingStrategy.INSTANCE;
sqlFunctions = new HashMap();
+ entityTuplizerFactory = new EntityTuplizerFactory();
+// componentTuplizerFactory = new ComponentTuplizerFactory();
}
- private transient Mapping mapping = buildMapping();
-
-
-
- protected Configuration(SettingsFactory settingsFactory) {
- this.settingsFactory = settingsFactory;
- reset();
+ public EntityTuplizerFactory getEntityTuplizerFactory() {
+ return entityTuplizerFactory;
}
- public Configuration() {
- this( new SettingsFactory() );
- }
+// public ComponentTuplizerFactory getComponentTuplizerFactory() {
+// return componentTuplizerFactory;
+// }
/**
* Iterate the entity mappings
@@ -2066,13 +2079,20 @@
public Settings buildSettings() throws HibernateException {
Properties clone = ( Properties ) properties.clone();
PropertiesHelper.resolvePlaceHolders( clone );
- return settingsFactory.buildSettings( clone );
+ return buildSettingsInternal( clone );
}
public Settings buildSettings(Properties props) throws HibernateException {
- return settingsFactory.buildSettings( props );
+ return buildSettingsInternal( props );
}
+ private Settings buildSettingsInternal(Properties props) {
+ final Settings settings = settingsFactory.buildSettings( props );
+ settings.setEntityTuplizerFactory( this.getEntityTuplizerFactory() );
+// settings.setComponentTuplizerFactory( this.getComponentTuplizerFactory() );
+ return settings;
+ }
+
public Map getNamedSQLQueries() {
return namedSqlQueries;
}
Modified: core/branches/Branch_3_2/src/org/hibernate/cfg/Settings.java
===================================================================
--- core/branches/Branch_3_2/src/org/hibernate/cfg/Settings.java 2008-10-08 17:21:15 UTC (rev 15288)
+++ core/branches/Branch_3_2/src/org/hibernate/cfg/Settings.java 2008-10-08 17:23:01 UTC (rev 15289)
@@ -14,6 +14,7 @@
import org.hibernate.exception.SQLExceptionConverter;
import org.hibernate.EntityMode;
import org.hibernate.ConnectionReleaseMode;
+import org.hibernate.tuple.entity.EntityTuplizerFactory;
/**
* Settings that affect the behaviour of Hibernate at runtime.
@@ -67,6 +68,8 @@
private boolean dataDefinitionInTransactionSupported;
private boolean strictJPAQLCompliance;
private boolean namedQueryStartupCheckingEnabled;
+ private EntityTuplizerFactory entityTuplizerFactory;
+// private ComponentTuplizerFactory componentTuplizerFactory; todo : HHH-3517 and HHH-1907
// private BytecodeProvider bytecodeProvider;
/**
@@ -257,7 +260,15 @@
return namedQueryStartupCheckingEnabled;
}
+ public EntityTuplizerFactory getEntityTuplizerFactory() {
+ return entityTuplizerFactory;
+ }
+// public ComponentTuplizerFactory getComponentTuplizerFactory() {
+// return componentTuplizerFactory;
+// }
+
+
// package protected setters ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void setDefaultSchemaName(String string) {
@@ -440,7 +451,15 @@
this.namedQueryStartupCheckingEnabled = namedQueryStartupCheckingEnabled;
}
+ void setEntityTuplizerFactory(EntityTuplizerFactory entityTuplizerFactory) {
+ this.entityTuplizerFactory = entityTuplizerFactory;
+ }
+// void setComponentTuplizerFactory(ComponentTuplizerFactory componentTuplizerFactory) {
+// this.componentTuplizerFactory = componentTuplizerFactory;
+// }
+
+
// public BytecodeProvider getBytecodeProvider() {
// return bytecodeProvider;
// }
Modified: core/branches/Branch_3_2/src/org/hibernate/tuple/component/ComponentEntityModeToTuplizerMapping.java
===================================================================
--- core/branches/Branch_3_2/src/org/hibernate/tuple/component/ComponentEntityModeToTuplizerMapping.java 2008-10-08 17:21:15 UTC (rev 15288)
+++ core/branches/Branch_3_2/src/org/hibernate/tuple/component/ComponentEntityModeToTuplizerMapping.java 2008-10-08 17:23:01 UTC (rev 15289)
@@ -5,8 +5,6 @@
import org.hibernate.mapping.Component;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.EntityMode;
-import org.hibernate.HibernateException;
-import org.hibernate.util.ReflectHelper;
import java.util.Map;
import java.util.HashMap;
@@ -23,7 +21,8 @@
*/
class ComponentEntityModeToTuplizerMapping extends EntityModeToTuplizerMapping implements Serializable {
- private static final Class[] COMPONENT_TUP_CTOR_SIG = new Class[] { Component.class };
+ // todo : move this to SF per HHH-3517; also see HHH-1907 and ComponentMetamodel
+ private ComponentTuplizerFactory componentTuplizerFactory = new ComponentTuplizerFactory();
public ComponentEntityModeToTuplizerMapping(Component component) {
PersistentClass owner = component.getOwner();
@@ -35,24 +34,24 @@
}
// Build the dynamic-map tuplizer...
- Tuplizer dynamicMapTuplizer = null;
- String tuplizerImpl = ( String ) userSuppliedTuplizerImpls.remove( EntityMode.MAP );
- if ( tuplizerImpl == null ) {
- dynamicMapTuplizer = new DynamicMapComponentTuplizer( component );
+ Tuplizer dynamicMapTuplizer;
+ String tuplizerClassName = ( String ) userSuppliedTuplizerImpls.remove( EntityMode.MAP );
+ if ( tuplizerClassName == null ) {
+ dynamicMapTuplizer = componentTuplizerFactory.constructDefaultTuplizer( EntityMode.MAP, component );
}
else {
- dynamicMapTuplizer = buildComponentTuplizer( tuplizerImpl, component );
+ dynamicMapTuplizer = componentTuplizerFactory.constructTuplizer( tuplizerClassName, component );
}
// then the pojo tuplizer, using the dynamic-map tuplizer if no pojo representation is available
- tuplizerImpl = ( String ) userSuppliedTuplizerImpls.remove( EntityMode.POJO );
- Tuplizer pojoTuplizer = null;
+ tuplizerClassName = ( String ) userSuppliedTuplizerImpls.remove( EntityMode.POJO );
+ Tuplizer pojoTuplizer;
if ( owner.hasPojoRepresentation() && component.hasPojoRepresentation() ) {
- if ( tuplizerImpl == null ) {
- pojoTuplizer = new PojoComponentTuplizer( component );
+ if ( tuplizerClassName == null ) {
+ pojoTuplizer = componentTuplizerFactory.constructDefaultTuplizer( EntityMode.POJO, component );
}
else {
- pojoTuplizer = buildComponentTuplizer( tuplizerImpl, component );
+ pojoTuplizer = componentTuplizerFactory.constructTuplizer( tuplizerClassName, component );
}
}
else {
@@ -60,14 +59,14 @@
}
// then dom4j tuplizer, if dom4j representation is available
- Tuplizer dom4jTuplizer = null;
- tuplizerImpl = ( String ) userSuppliedTuplizerImpls.remove( EntityMode.DOM4J );
+ Tuplizer dom4jTuplizer;
+ tuplizerClassName = ( String ) userSuppliedTuplizerImpls.remove( EntityMode.DOM4J );
if ( owner.hasDom4jRepresentation() ) {
- if ( tuplizerImpl == null ) {
- dom4jTuplizer = new Dom4jComponentTuplizer( component );
+ if ( tuplizerClassName == null ) {
+ dom4jTuplizer = componentTuplizerFactory.constructDefaultTuplizer( EntityMode.DOM4J, component );
}
else {
- dom4jTuplizer = buildComponentTuplizer( tuplizerImpl, component );
+ dom4jTuplizer = componentTuplizerFactory.constructTuplizer( tuplizerClassName, component );
}
}
else {
@@ -89,21 +88,12 @@
if ( !userSuppliedTuplizerImpls.isEmpty() ) {
Iterator itr = userSuppliedTuplizerImpls.entrySet().iterator();
while ( itr.hasNext() ) {
- Map.Entry entry = ( Map.Entry ) itr.next();
- EntityMode entityMode = ( EntityMode ) entry.getKey();
- ComponentTuplizer tuplizer = buildComponentTuplizer( ( String ) entry.getValue(), component );
+ final Map.Entry entry = ( Map.Entry ) itr.next();
+ final EntityMode entityMode = ( EntityMode ) entry.getKey();
+ final String userTuplizerClassName = ( String ) entry.getValue();
+ ComponentTuplizer tuplizer = componentTuplizerFactory.constructTuplizer( userTuplizerClassName, component );
addTuplizer( entityMode, tuplizer );
}
}
}
-
- private ComponentTuplizer buildComponentTuplizer(String tuplizerImpl, Component component) {
- try {
- Class implClass = ReflectHelper.classForName( tuplizerImpl );
- return ( ComponentTuplizer ) implClass.getConstructor( COMPONENT_TUP_CTOR_SIG ).newInstance( new Object[] { component } );
- }
- catch( Throwable t ) {
- throw new HibernateException( "Could not build tuplizer [" + tuplizerImpl + "]", t );
- }
- }
}
Added: core/branches/Branch_3_2/src/org/hibernate/tuple/component/ComponentTuplizerFactory.java
===================================================================
--- core/branches/Branch_3_2/src/org/hibernate/tuple/component/ComponentTuplizerFactory.java (rev 0)
+++ core/branches/Branch_3_2/src/org/hibernate/tuple/component/ComponentTuplizerFactory.java 2008-10-08 17:23:01 UTC (rev 15289)
@@ -0,0 +1,160 @@
+/*
+ * 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.tuple.component;
+
+import java.util.Map;
+import java.lang.reflect.Constructor;
+import java.io.Serializable;
+
+import org.hibernate.util.FastHashMap;
+import org.hibernate.util.ReflectHelper;
+import org.hibernate.EntityMode;
+import org.hibernate.HibernateException;
+import org.hibernate.mapping.Component;
+
+/**
+ * A registry allowing users to define the default {@link ComponentTuplizer} class to use per {@link EntityMode}.
+ *
+ * @author Steve Ebersole
+ */
+public class ComponentTuplizerFactory implements Serializable {
+
+ private static final Class[] COMPONENT_TUP_CTOR_SIG = new Class[] { Component.class };
+
+ private Map defaultImplClassByMode = buildBaseMapping();
+
+ /**
+ * Method allowing registration of the tuplizer class to use as default for a particular entity-mode.
+ *
+ * @param entityMode The entity-mode for which to register the tuplizer class
+ * @param tuplizerClass The class to use as the default tuplizer for the given entity-mode.
+ */
+ public void registerDefaultTuplizerClass(EntityMode entityMode, Class tuplizerClass) {
+ assert isComponentTuplizerImplementor( tuplizerClass )
+ : "Specified tuplizer class [" + tuplizerClass.getName() + "] does not implement " + ComponentTuplizer.class.getName();
+ assert hasProperConstructor( tuplizerClass )
+ : "Specified tuplizer class [" + tuplizerClass.getName() + "] is not properly instantiatable";
+
+ defaultImplClassByMode.put( entityMode, tuplizerClass );
+ }
+
+ /**
+ * Construct an instance of the given tuplizer class.
+ *
+ * @param tuplizerClassName The name of the tuplizer class to instantiate
+ * @param metadata The metadata for the component.
+ *
+ * @return The instantiated tuplizer
+ *
+ * @throws HibernateException If class name cannot be resolved to a class reference, or if the
+ * {@link Constructor#newInstance} call fails.
+ */
+ public ComponentTuplizer constructTuplizer(String tuplizerClassName, Component metadata) {
+ try {
+ Class tuplizerClass = ReflectHelper.classForName( tuplizerClassName );
+ return constructTuplizer( tuplizerClass, metadata );
+ }
+ catch ( ClassNotFoundException e ) {
+ throw new HibernateException( "Could not locate specified tuplizer class [" + tuplizerClassName + "]" );
+ }
+ }
+
+ /**
+ * Construct an instance of the given tuplizer class.
+ *
+ * @param tuplizerClass The tuplizer class to instantiate
+ * @param metadata The metadata for the component.
+ *
+ * @return The instantiated tuplizer
+ *
+ * @throws HibernateException if the {@link java.lang.reflect.Constructor#newInstance} call fails.
+ */
+ public ComponentTuplizer constructTuplizer(Class tuplizerClass, Component metadata) {
+ Constructor ctor = getProperConstructor( tuplizerClass );
+ assert ctor != null : "Unable to locate proper constructor for tuplizer [" + tuplizerClass.getName() + "]";
+ try {
+ return ( ComponentTuplizer ) ctor.newInstance( new Object[] { metadata } );
+ }
+ catch ( Throwable t ) {
+ throw new HibernateException( "Unable to instantiate default tuplizer [" + tuplizerClass.getName() + "]", t );
+ }
+ }
+
+ /**
+ * Construct am instance of the default tuplizer for the given entity-mode.
+ *
+ * @param entityMode The entity mode for which to build a default tuplizer.
+ * @param metadata The metadata for the component.
+ *
+ * @return The instantiated tuplizer
+ *
+ * @throws HibernateException If no default tuplizer found for that entity-mode; may be re-thrown from
+ * {@link #constructTuplizer} too.
+ */
+ public ComponentTuplizer constructDefaultTuplizer(EntityMode entityMode, Component metadata) {
+ Class tuplizerClass = ( Class ) defaultImplClassByMode.get( entityMode );
+ if ( tuplizerClass == null ) {
+ throw new HibernateException( "could not determine default tuplizer class to use [" + entityMode + "]" );
+ }
+
+ return constructTuplizer( tuplizerClass, metadata );
+ }
+
+ private boolean isComponentTuplizerImplementor(Class tuplizerClass) {
+ return ReflectHelper.implementsInterface( tuplizerClass, ComponentTuplizer.class );
+ }
+
+ private boolean hasProperConstructor(Class tuplizerClass) {
+ return getProperConstructor( tuplizerClass ) != null;
+ }
+
+ private Constructor getProperConstructor(Class clazz) {
+ Constructor ctor = null;
+ try {
+ ctor = clazz.getDeclaredConstructor( COMPONENT_TUP_CTOR_SIG );
+ if ( ! ReflectHelper.isPublic( ctor ) ) {
+ try {
+ // found a ctor, but it was not publicly accessible so try to request accessibility
+ ctor.setAccessible( true );
+ }
+ catch ( SecurityException e ) {
+ ctor = null;
+ }
+ }
+ }
+ catch ( NoSuchMethodException ignore ) {
+ }
+
+ return ctor;
+ }
+
+ private static Map buildBaseMapping() {
+ Map map = new FastHashMap();
+ map.put( EntityMode.POJO, PojoComponentTuplizer.class );
+ map.put( EntityMode.DOM4J, Dom4jComponentTuplizer.class );
+ map.put( EntityMode.MAP, DynamicMapComponentTuplizer.class );
+ return map;
+ }
+}
Modified: core/branches/Branch_3_2/src/org/hibernate/tuple/entity/EntityEntityModeToTuplizerMapping.java
===================================================================
--- core/branches/Branch_3_2/src/org/hibernate/tuple/entity/EntityEntityModeToTuplizerMapping.java 2008-10-08 17:21:15 UTC (rev 15288)
+++ core/branches/Branch_3_2/src/org/hibernate/tuple/entity/EntityEntityModeToTuplizerMapping.java 2008-10-08 17:23:01 UTC (rev 15289)
@@ -4,8 +4,6 @@
import org.hibernate.tuple.Tuplizer;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.EntityMode;
-import org.hibernate.HibernateException;
-import org.hibernate.util.ReflectHelper;
import java.util.Iterator;
import java.util.Map;
@@ -22,8 +20,6 @@
*/
public class EntityEntityModeToTuplizerMapping extends EntityModeToTuplizerMapping implements Serializable {
- private static final Class[] ENTITY_TUP_CTOR_SIG = new Class[] { EntityMetamodel.class, PersistentClass.class };
-
/**
* Instantiates a EntityEntityModeToTuplizerMapping based on the given
* entity mapping and metamodel definitions.
@@ -32,6 +28,10 @@
* @param em The entity metamodel definition.
*/
public EntityEntityModeToTuplizerMapping(PersistentClass mappedEntity, EntityMetamodel em) {
+ final EntityTuplizerFactory entityTuplizerFactory = em.getSessionFactory()
+ .getSettings()
+ .getEntityTuplizerFactory();
+
// create our own copy of the user-supplied tuplizer impl map
Map userSuppliedTuplizerImpls = new HashMap();
if ( mappedEntity.getTuplizerMap() != null ) {
@@ -39,24 +39,24 @@
}
// Build the dynamic-map tuplizer...
- Tuplizer dynamicMapTuplizer = null;
- String tuplizerImpl = ( String ) userSuppliedTuplizerImpls.remove( EntityMode.MAP );
- if ( tuplizerImpl == null ) {
- dynamicMapTuplizer = new DynamicMapEntityTuplizer( em, mappedEntity );
+ Tuplizer dynamicMapTuplizer;
+ String tuplizerImplClassName = ( String ) userSuppliedTuplizerImpls.remove( EntityMode.MAP );
+ if ( tuplizerImplClassName == null ) {
+ dynamicMapTuplizer = entityTuplizerFactory.constructDefaultTuplizer( EntityMode.MAP, em, mappedEntity );
}
else {
- dynamicMapTuplizer = buildEntityTuplizer( tuplizerImpl, mappedEntity, em );
+ dynamicMapTuplizer = entityTuplizerFactory.constructTuplizer( tuplizerImplClassName, em, mappedEntity );
}
// then the pojo tuplizer, using the dynamic-map tuplizer if no pojo representation is available
- Tuplizer pojoTuplizer = null;
- tuplizerImpl = ( String ) userSuppliedTuplizerImpls.remove( EntityMode.POJO );
+ Tuplizer pojoTuplizer;
+ tuplizerImplClassName = ( String ) userSuppliedTuplizerImpls.remove( EntityMode.POJO );
if ( mappedEntity.hasPojoRepresentation() ) {
- if ( tuplizerImpl == null ) {
- pojoTuplizer = new PojoEntityTuplizer( em, mappedEntity );
+ if ( tuplizerImplClassName == null ) {
+ pojoTuplizer = entityTuplizerFactory.constructDefaultTuplizer( EntityMode.POJO, em, mappedEntity );
}
else {
- pojoTuplizer = buildEntityTuplizer( tuplizerImpl, mappedEntity, em );
+ pojoTuplizer = entityTuplizerFactory.constructTuplizer( tuplizerImplClassName, em, mappedEntity );
}
}
else {
@@ -64,14 +64,14 @@
}
// then dom4j tuplizer, if dom4j representation is available
- Tuplizer dom4jTuplizer = null;
- tuplizerImpl = ( String ) userSuppliedTuplizerImpls.remove( EntityMode.DOM4J );
+ Tuplizer dom4jTuplizer;
+ tuplizerImplClassName = ( String ) userSuppliedTuplizerImpls.remove( EntityMode.DOM4J );
if ( mappedEntity.hasDom4jRepresentation() ) {
- if ( tuplizerImpl == null ) {
- dom4jTuplizer = new Dom4jEntityTuplizer( em, mappedEntity );
+ if ( tuplizerImplClassName == null ) {
+ dom4jTuplizer = entityTuplizerFactory.constructDefaultTuplizer( EntityMode.DOM4J, em, mappedEntity );
}
else {
- dom4jTuplizer = buildEntityTuplizer( tuplizerImpl, mappedEntity, em );
+ dom4jTuplizer = entityTuplizerFactory.constructTuplizer( tuplizerImplClassName, em, mappedEntity );
}
}
else {
@@ -93,21 +93,12 @@
if ( !userSuppliedTuplizerImpls.isEmpty() ) {
Iterator itr = userSuppliedTuplizerImpls.entrySet().iterator();
while ( itr.hasNext() ) {
- Map.Entry entry = ( Map.Entry ) itr.next();
- EntityMode entityMode = ( EntityMode ) entry.getKey();
- EntityTuplizer tuplizer = buildEntityTuplizer( ( String ) entry.getValue(), mappedEntity, em );
+ final Map.Entry entry = ( Map.Entry ) itr.next();
+ final EntityMode entityMode = ( EntityMode ) entry.getKey();
+ final String tuplizerClassName = ( String ) entry.getValue();
+ final EntityTuplizer tuplizer = entityTuplizerFactory.constructTuplizer( tuplizerClassName, em, mappedEntity );
addTuplizer( entityMode, tuplizer );
}
}
}
-
- private static EntityTuplizer buildEntityTuplizer(String className, PersistentClass pc, EntityMetamodel em) {
- try {
- Class implClass = ReflectHelper.classForName( className );
- return ( EntityTuplizer ) implClass.getConstructor( ENTITY_TUP_CTOR_SIG ).newInstance( new Object[] { em, pc } );
- }
- catch( Throwable t ) {
- throw new HibernateException( "Could not build tuplizer [" + className + "]", t );
- }
- }
}
Modified: core/branches/Branch_3_2/src/org/hibernate/tuple/entity/EntityTuplizer.java
===================================================================
--- core/branches/Branch_3_2/src/org/hibernate/tuple/entity/EntityTuplizer.java 2008-10-08 17:21:15 UTC (rev 15288)
+++ core/branches/Branch_3_2/src/org/hibernate/tuple/entity/EntityTuplizer.java 2008-10-08 17:23:01 UTC (rev 15289)
@@ -215,4 +215,4 @@
* @throws HibernateException If we are unable to determine an entity-name within the inheritence hierarchy.
*/
public String determineConcreteSubclassEntityName(Object entityInstance, SessionFactoryImplementor factory);
-}
+}
\ No newline at end of file
Added: core/branches/Branch_3_2/src/org/hibernate/tuple/entity/EntityTuplizerFactory.java
===================================================================
--- core/branches/Branch_3_2/src/org/hibernate/tuple/entity/EntityTuplizerFactory.java (rev 0)
+++ core/branches/Branch_3_2/src/org/hibernate/tuple/entity/EntityTuplizerFactory.java 2008-10-08 17:23:01 UTC (rev 15289)
@@ -0,0 +1,173 @@
+/*
+ * 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.tuple.entity;
+
+import java.util.Map;
+import java.lang.reflect.Constructor;
+import java.io.Serializable;
+
+
+import org.hibernate.util.FastHashMap;
+import org.hibernate.util.ReflectHelper;
+import org.hibernate.EntityMode;
+import org.hibernate.HibernateException;
+import org.hibernate.mapping.PersistentClass;
+
+/**
+ * A registry allowing users to define the default {@link EntityTuplizer} class to use per {@link EntityMode}.
+ *
+ * @author Steve Ebersole
+ */
+public class EntityTuplizerFactory implements Serializable {
+
+ public static final Class[] ENTITY_TUP_CTOR_SIG = new Class[] { EntityMetamodel.class, PersistentClass.class };
+
+ private Map defaultImplClassByMode = buildBaseMapping();
+
+ /**
+ * Method allowing registration of the tuplizer class to use as default for a particular entity-mode.
+ *
+ * @param entityMode The entity-mode for which to register the tuplizer class
+ * @param tuplizerClass The class to use as the default tuplizer for the given entity-mode.
+ */
+ public void registerDefaultTuplizerClass(EntityMode entityMode, Class tuplizerClass) {
+ assert isEntityTuplizerImplementor( tuplizerClass )
+ : "Specified tuplizer class [" + tuplizerClass.getName() + "] does not implement " + EntityTuplizer.class.getName();
+ assert hasProperConstructor( tuplizerClass )
+ : "Specified tuplizer class [" + tuplizerClass.getName() + "] is not properly instantiatable";
+
+ defaultImplClassByMode.put( entityMode, tuplizerClass );
+ }
+
+ /**
+ * Construct an instance of the given tuplizer class.
+ *
+ * @param tuplizerClassName The name of the tuplizer class to instantiate
+ * @param metamodel The metadata for the entity.
+ * @param persistentClass The mapping info for the entity.
+ *
+ * @return The instantiated tuplizer
+ *
+ * @throws HibernateException If class name cannot be resolved to a class reference, or if the
+ * {@link Constructor#newInstance} call fails.
+ */
+ public EntityTuplizer constructTuplizer(
+ String tuplizerClassName,
+ EntityMetamodel metamodel,
+ PersistentClass persistentClass) {
+ try {
+ Class tuplizerClass = ReflectHelper.classForName( tuplizerClassName );
+ return constructTuplizer( tuplizerClass, metamodel, persistentClass );
+ }
+ catch ( ClassNotFoundException e ) {
+ throw new HibernateException( "Could not locate specified tuplizer class [" + tuplizerClassName + "]" );
+ }
+ }
+
+ /**
+ * Construct an instance of the given tuplizer class.
+ *
+ * @param tuplizerClass The tuplizer class to instantiate
+ * @param metamodel The metadata for the entity.
+ * @param persistentClass The mapping info for the entity.
+ *
+ * @return The instantiated tuplizer
+ *
+ * @throws HibernateException if the {@link Constructor#newInstance} call fails.
+ */
+ public EntityTuplizer constructTuplizer(
+ Class tuplizerClass,
+ EntityMetamodel metamodel,
+ PersistentClass persistentClass) {
+ Constructor ctor = getProperConstructor( tuplizerClass );
+ assert ctor != null : "Unable to locate proper constructor for tuplizer [" + tuplizerClass.getName() + "]";
+ try {
+ return ( EntityTuplizer ) ctor.newInstance( new Object[] { metamodel, persistentClass } );
+ }
+ catch ( Throwable t ) {
+ throw new HibernateException( "Unable to instantiate default tuplizer [" + tuplizerClass.getName() + "]", t );
+ }
+ }
+
+ /**
+ * Construct am instance of the default tuplizer for the given entity-mode.
+ *
+ * @param entityMode The entity mode for which to build a default tuplizer.
+ * @param metamodel The entity metadata.
+ * @param persistentClass The entity mapping info.
+ *
+ * @return The instantiated tuplizer
+ *
+ * @throws HibernateException If no default tuplizer found for that entity-mode; may be re-thrown from
+ * {@link #constructTuplizer} too.
+ */
+ public EntityTuplizer constructDefaultTuplizer(
+ EntityMode entityMode,
+ EntityMetamodel metamodel,
+ PersistentClass persistentClass) {
+ Class tuplizerClass = ( Class ) defaultImplClassByMode.get( entityMode );
+ if ( tuplizerClass == null ) {
+ throw new HibernateException( "could not determine default tuplizer class to use [" + entityMode + "]" );
+ }
+
+ return constructTuplizer( tuplizerClass, metamodel, persistentClass );
+ }
+
+ private boolean isEntityTuplizerImplementor(Class tuplizerClass) {
+ return ReflectHelper.implementsInterface( tuplizerClass, EntityTuplizer.class );
+ }
+
+ private boolean hasProperConstructor(Class tuplizerClass) {
+ return getProperConstructor( tuplizerClass ) != null;
+ }
+
+ private Constructor getProperConstructor(Class clazz) {
+ Constructor ctor = null;
+ try {
+ ctor = clazz.getDeclaredConstructor( ENTITY_TUP_CTOR_SIG );
+ if ( ! ReflectHelper.isPublic( ctor ) ) {
+ try {
+ // found a ctor, but it was not publicly accessible so try to request accessibility
+ ctor.setAccessible( true );
+ }
+ catch ( SecurityException e ) {
+ ctor = null;
+ }
+ }
+ }
+ catch ( NoSuchMethodException ignore ) {
+ }
+
+ return ctor;
+ }
+
+ private static Map buildBaseMapping() {
+ Map map = new FastHashMap();
+ map.put( EntityMode.POJO, PojoEntityTuplizer.class );
+ map.put( EntityMode.DOM4J, Dom4jEntityTuplizer.class );
+ map.put( EntityMode.MAP, DynamicMapEntityTuplizer.class );
+ return map;
+ }
+}
Modified: core/branches/Branch_3_2/src/org/hibernate/util/ReflectHelper.java
===================================================================
--- core/branches/Branch_3_2/src/org/hibernate/util/ReflectHelper.java 2008-10-08 17:21:15 UTC (rev 15288)
+++ core/branches/Branch_3_2/src/org/hibernate/util/ReflectHelper.java 2008-10-08 17:23:01 UTC (rev 15289)
@@ -16,78 +16,154 @@
import org.hibernate.type.PrimitiveType;
import org.hibernate.type.Type;
-
+/**
+ * Utility class for various reflection operations.
+ *
+ * @author Gavin King
+ * @author Steve Ebersole
+ */
public final class ReflectHelper {
//TODO: this dependency is kinda Bad
private static final PropertyAccessor BASIC_PROPERTY_ACCESSOR = new BasicPropertyAccessor();
private static final PropertyAccessor DIRECT_PROPERTY_ACCESSOR = new DirectPropertyAccessor();
- private static final Class[] NO_CLASSES = new Class[0];
- private static final Class[] OBJECT = new Class[] { Object.class };
+ public static final Class[] NO_PARAM_SIGNATURE = new Class[0];
+ public static final Object[] NO_PARAMS = new Object[0];
+
+ public static final Class[] SINGLE_OBJECT_PARAM_SIGNATURE = new Class[] { Object.class };
+
private static final Method OBJECT_EQUALS;
- private static final Class[] NO_PARAM = new Class[] { };
+ private static final Method OBJECT_HASHCODE;
- private static final Method OBJECT_HASHCODE;
static {
Method eq;
Method hash;
try {
- eq = Object.class.getMethod("equals", OBJECT);
- hash = Object.class.getMethod("hashCode", NO_PARAM);
+ eq = extractEqualsMethod( Object.class );
+ hash = extractHashCodeMethod( Object.class );
}
- catch (Exception e) {
- throw new AssertionFailure("Could not find Object.equals() or Object.hashCode()", e);
+ catch ( Exception e ) {
+ throw new AssertionFailure( "Could not find Object.equals() or Object.hashCode()", e );
}
OBJECT_EQUALS = eq;
OBJECT_HASHCODE = hash;
}
+ /**
+ * Disallow instantiation of ReflectHelper.
+ */
+ private ReflectHelper() {
+ }
+
+ /**
+ * Encapsulation of getting hold of a class's {@link Object#equals equals} method.
+ *
+ * @param clazz The class from which to extract the equals method.
+ * @return The equals method reference
+ * @throws NoSuchMethodException Should indicate an attempt to extract equals method from interface.
+ */
+ public static Method extractEqualsMethod(Class clazz) throws NoSuchMethodException {
+ return clazz.getMethod( "equals", SINGLE_OBJECT_PARAM_SIGNATURE );
+ }
+
+ /**
+ * Encapsulation of getting hold of a class's {@link Object#hashCode hashCode} method.
+ *
+ * @param clazz The class from which to extract the hashCode method.
+ * @return The hashCode method reference
+ * @throws NoSuchMethodException Should indicate an attempt to extract hashCode method from interface.
+ */
+ public static Method extractHashCodeMethod(Class clazz) throws NoSuchMethodException {
+ return clazz.getMethod( "hashCode", NO_PARAM_SIGNATURE );
+ }
+
+ /**
+ * Determine if the given class defines an {@link Object#equals} override.
+ *
+ * @param clazz The class to check
+ * @return True if clazz defines an equals override.
+ */
public static boolean overridesEquals(Class clazz) {
Method equals;
try {
- equals = clazz.getMethod("equals", OBJECT);
+ equals = extractEqualsMethod( clazz );
}
- catch (NoSuchMethodException nsme) {
+ catch ( NoSuchMethodException nsme ) {
return false; //its an interface so we can't really tell anything...
}
- return !OBJECT_EQUALS.equals(equals);
+ return !OBJECT_EQUALS.equals( equals );
}
+ /**
+ * Determine if the given class defines a {@link Object#hashCode} override.
+ *
+ * @param clazz The class to check
+ * @return True if clazz defines an hashCode override.
+ */
public static boolean overridesHashCode(Class clazz) {
Method hashCode;
try {
- hashCode = clazz.getMethod("hashCode", NO_PARAM);
+ hashCode = extractHashCodeMethod( clazz );
}
- catch (NoSuchMethodException nsme) {
+ catch ( NoSuchMethodException nsme ) {
return false; //its an interface so we can't really tell anything...
}
- return !OBJECT_HASHCODE.equals(hashCode);
+ return !OBJECT_HASHCODE.equals( hashCode );
}
- public static Class reflectedPropertyClass(String className, String name) throws MappingException {
- try {
- Class clazz = ReflectHelper.classForName(className);
- return getter(clazz, name).getReturnType();
+ /**
+ * Determine if the given class implements the given interface.
+ *
+ * @param clazz The class to check
+ * @param intf The interface to check it against.
+ * @return True if the class does implement the interface, false otherwise.
+ */
+ public static boolean implementsInterface(Class clazz, Class intf) {
+ assert intf.isInterface() : "Interface to check was not an interface";
+
+ Class[] interfaces = clazz.getInterfaces();
+ for ( int i = 0; i < interfaces.length; i++ ) {
+ if ( intf.isAssignableFrom( interfaces[i] ) ) {
+ return true;
+ }
}
- catch (ClassNotFoundException cnfe) {
- throw new MappingException("class " + className + " not found while looking for property: " + name, cnfe);
- }
+ return false;
}
- private static Getter getter(Class clazz, String name) throws MappingException {
+ /**
+ * Perform resolution of a class name.
+ * <p/>
+ * Here we first check the context classloader, if one, before delegating to
+ * {@link Class#forName(String, boolean, ClassLoader)} using the caller's classloader
+ *
+ * @param name The class name
+ * @param caller The class from which this call originated (in order to access that class's loader).
+ * @return The class reference.
+ * @throws ClassNotFoundException From {@link Class#forName(String, boolean, ClassLoader)}.
+ */
+ public static Class classForName(String name, Class caller) throws ClassNotFoundException {
try {
- return BASIC_PROPERTY_ACCESSOR.getGetter(clazz, name);
+ ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
+ if ( contextClassLoader != null ) {
+ return contextClassLoader.loadClass( name );
+ }
}
- catch (PropertyNotFoundException pnfe) {
- return DIRECT_PROPERTY_ACCESSOR.getGetter(clazz, name);
+ catch ( Throwable ignore ) {
}
+ return Class.forName( name, true, caller.getClassLoader() );
}
- public static Getter getGetter(Class theClass, String name) throws MappingException {
- return BASIC_PROPERTY_ACCESSOR.getGetter(theClass, name);
- }
-
+ /**
+ * Perform resolution of a class name.
+ * <p/>
+ * Same as {@link #classForName(String, Class)} except that here we delegate to
+ * {@link Class#forName(String)} if the context classloader lookup is unsuccessful.
+ *
+ * @param name The class name
+ * @return The class reference.
+ * @throws ClassNotFoundException From {@link Class#forName(String)}.
+ */
public static Class classForName(String name) throws ClassNotFoundException {
try {
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
@@ -95,27 +171,79 @@
return contextClassLoader.loadClass(name);
}
}
- catch ( Throwable t ) {
+ catch ( Throwable ignore ) {
}
return Class.forName( name );
}
- public static Class classForName(String name, Class caller) throws ClassNotFoundException {
+ /**
+ * Is this member publicly accessible.
+ * <p/>
+ * Short-hand for {@link #isPublic(Class, Member)} passing the member + {@link Member#getDeclaringClass()}
+ *
+ * @param member The member to check
+ * @return True if the member is publicly accessible.
+ */
+ public static boolean isPublic(Member member) {
+ return isPublic( member.getDeclaringClass(), member );
+ }
+
+ /**
+ * Is this member publicly accessible.
+ *
+ * @param clazz The class which defines the member
+ * @param member The memeber.
+ * @return True if the member is publicly accessible, false otherwise.
+ */
+ public static boolean isPublic(Class clazz, Member member) {
+ return Modifier.isPublic( member.getModifiers() ) && Modifier.isPublic( clazz.getModifiers() );
+ }
+
+ /**
+ * Attempt to resolve the specified property type through reflection.
+ *
+ * @param className The name of the class owning the property.
+ * @param name The name of the property.
+ * @return The type of the property.
+ * @throws MappingException Indicates we were unable to locate the property.
+ */
+ public static Class reflectedPropertyClass(String className, String name) throws MappingException {
try {
- ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
- if ( contextClassLoader != null ) {
- return contextClassLoader.loadClass( name );
- }
+ Class clazz = ReflectHelper.classForName( className );
+ return getter( clazz, name ).getReturnType();
}
- catch ( Throwable e ) {
+ catch ( ClassNotFoundException cnfe ) {
+ throw new MappingException( "class " + className + " not found while looking for property: " + name, cnfe );
}
- return Class.forName( name, true, caller.getClassLoader() );
}
- public static boolean isPublic(Class clazz, Member member) {
- return Modifier.isPublic( member.getModifiers() ) && Modifier.isPublic( clazz.getModifiers() );
+ private static Getter getter(Class clazz, String name) throws MappingException {
+ try {
+ return BASIC_PROPERTY_ACCESSOR.getGetter( clazz, name );
+ }
+ catch ( PropertyNotFoundException pnfe ) {
+ return DIRECT_PROPERTY_ACCESSOR.getGetter( clazz, name );
+ }
}
+ /**
+ * Directly retrieve the {@link Getter} reference via the {@link BasicPropertyAccessor}.
+ *
+ * @param theClass The class owning the property
+ * @param name The name of the property
+ * @return The getter.
+ * @throws MappingException Indicates we were unable to locate the property.
+ */
+ public static Getter getGetter(Class theClass, String name) throws MappingException {
+ return BASIC_PROPERTY_ACCESSOR.getGetter( theClass, name );
+ }
+
+ /**
+ * Resolve a constant to its actual value.
+ *
+ * @param name The name
+ * @return The value
+ */
public static Object getConstantValue(String name) {
Class clazz;
try {
@@ -125,61 +253,90 @@
return null;
}
try {
- return clazz.getField( StringHelper.unqualify( name ) ).get(null);
+ return clazz.getField( StringHelper.unqualify( name ) ).get( null );
}
catch ( Throwable t ) {
return null;
}
}
+ /**
+ * Retrieve the default (no arg) constructor from the given class.
+ *
+ * @param clazz The class for which to retrieve the default ctor.
+ * @return The default constructor.
+ * @throws PropertyNotFoundException Indicates there was not publicly accessible, no-arg constructor (todo : why PropertyNotFoundException???)
+ */
public static Constructor getDefaultConstructor(Class clazz) throws PropertyNotFoundException {
+ if ( isAbstractClass( clazz ) ) {
+ return null;
+ }
- if ( isAbstractClass(clazz) ) return null;
-
try {
- Constructor constructor = clazz.getDeclaredConstructor(NO_CLASSES);
- if ( !isPublic(clazz, constructor) ) {
- constructor.setAccessible(true);
+ Constructor constructor = clazz.getDeclaredConstructor( NO_PARAM_SIGNATURE );
+ if ( !isPublic( clazz, constructor ) ) {
+ constructor.setAccessible( true );
}
return constructor;
}
- catch (NoSuchMethodException nme) {
+ catch ( NoSuchMethodException nme ) {
throw new PropertyNotFoundException(
- "Object class " + clazz.getName() +
- " must declare a default (no-argument) constructor"
+ "Object class [" + clazz.getName() + "] must declare a default (no-argument) constructor"
);
}
-
}
+ /**
+ * Determine if the given class is declared abstract.
+ *
+ * @param clazz The class to check.
+ * @return True if the class is abstract, false otherwise.
+ */
public static boolean isAbstractClass(Class clazz) {
int modifier = clazz.getModifiers();
return Modifier.isAbstract(modifier) || Modifier.isInterface(modifier);
}
-
+
+ /**
+ * Determine is the given class is declared final.
+ *
+ * @param clazz The class to check.
+ * @return True if the class is final, flase otherwise.
+ */
public static boolean isFinalClass(Class clazz) {
return Modifier.isFinal( clazz.getModifiers() );
}
+ /**
+ * Retrieve a constructor for the given class, with arguments matching the specified Hibernate mapping
+ * {@link Type types}.
+ *
+ * @param clazz The class needing instantiation
+ * @param types The types representing the required ctor param signature
+ * @return The matching constructor.
+ * @throws PropertyNotFoundException Indicates we could not locate an appropriate constructor (todo : again with PropertyNotFoundException???)
+ */
public static Constructor getConstructor(Class clazz, Type[] types) throws PropertyNotFoundException {
final Constructor[] candidates = clazz.getConstructors();
- for ( int i=0; i<candidates.length; i++ ) {
+ for ( int i = 0; i < candidates.length; i++ ) {
final Constructor constructor = candidates[i];
final Class[] params = constructor.getParameterTypes();
- if ( params.length==types.length ) {
+ if ( params.length == types.length ) {
boolean found = true;
- for ( int j=0; j<params.length; j++ ) {
+ for ( int j = 0; j < params.length; j++ ) {
final boolean ok = params[j].isAssignableFrom( types[j].getReturnedClass() ) || (
- types[j] instanceof PrimitiveType &&
- params[j] == ( (PrimitiveType) types[j] ).getPrimitiveClass()
+ types[j] instanceof PrimitiveType &&
+ params[j] == ( ( PrimitiveType ) types[j] ).getPrimitiveClass()
);
- if (!ok) {
+ if ( !ok ) {
found = false;
break;
}
}
- if (found) {
- if ( !isPublic(clazz, constructor) ) constructor.setAccessible(true);
+ if ( found ) {
+ if ( !isPublic( clazz, constructor ) ) {
+ constructor.setAccessible( true );
+ }
return constructor;
}
}
@@ -196,6 +353,4 @@
}
}
- private ReflectHelper() {}
-
}
Modified: core/branches/Branch_3_2/test/org/hibernate/test/dynamicentity/tuplizer2/Customer.hbm.xml
===================================================================
--- core/branches/Branch_3_2/test/org/hibernate/test/dynamicentity/tuplizer2/Customer.hbm.xml 2008-10-08 17:21:15 UTC (rev 15288)
+++ core/branches/Branch_3_2/test/org/hibernate/test/dynamicentity/tuplizer2/Customer.hbm.xml 2008-10-08 17:23:01 UTC (rev 15289)
@@ -31,7 +31,6 @@
<hibernate-mapping package="org.hibernate.test.dynamicentity">
<class name="Person" table="t_person" discriminator-value="person" abstract="false">
- <tuplizer class="org.hibernate.test.dynamicentity.tuplizer2.MyEntityTuplizer" entity-mode="pojo"/>
<id name="id">
<generator class="native"/>
</id>
@@ -46,13 +45,11 @@
</set>
<subclass name="Customer" discriminator-value="customer" abstract="false">
- <tuplizer class="org.hibernate.test.dynamicentity.tuplizer2.MyEntityTuplizer" entity-mode="pojo"/>
<many-to-one name="company" cascade="none" column="comp_id"/>
</subclass>
</class>
<class name="Company" table="t_company" abstract="false">
- <tuplizer class="org.hibernate.test.dynamicentity.tuplizer2.MyEntityTuplizer" entity-mode="pojo"/>
<id name="id">
<generator class="native"/>
</id>
@@ -60,7 +57,6 @@
</class>
<class name="Address" table="t_address" abstract="false">
- <tuplizer class="org.hibernate.test.dynamicentity.tuplizer2.MyEntityTuplizer" entity-mode="pojo"/>
<id name="id">
<generator class="native"/>
</id>
Modified: core/branches/Branch_3_2/test/org/hibernate/test/dynamicentity/tuplizer2/ImprovedTuplizerDynamicEntityTest.java
===================================================================
--- core/branches/Branch_3_2/test/org/hibernate/test/dynamicentity/tuplizer2/ImprovedTuplizerDynamicEntityTest.java 2008-10-08 17:21:15 UTC (rev 15288)
+++ core/branches/Branch_3_2/test/org/hibernate/test/dynamicentity/tuplizer2/ImprovedTuplizerDynamicEntityTest.java 2008-10-08 17:23:01 UTC (rev 15289)
@@ -31,6 +31,7 @@
import org.hibernate.test.dynamicentity.Person;
import org.hibernate.Session;
import org.hibernate.Hibernate;
+import org.hibernate.EntityMode;
import org.hibernate.cfg.Configuration;
import org.hibernate.junit.functional.FunctionalTestCase;
import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
@@ -61,6 +62,7 @@
public void configure(Configuration cfg) {
super.configure( cfg );
+ cfg.getEntityTuplizerFactory().registerDefaultTuplizerClass( EntityMode.POJO, MyEntityTuplizer.class );
}
public static TestSuite suite() {
16 years, 2 months