Hibernate SVN: r11080 - in trunk/Hibernate3: src/org/hibernate/hql/classic and 9 other directories.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2007-01-23 11:29:18 -0500 (Tue, 23 Jan 2007)
New Revision: 11080
Added:
trunk/Hibernate3/test/org/hibernate/test/dialect/functional/
trunk/Hibernate3/test/org/hibernate/test/dialect/functional/DialectFunctionalTestsSuite.java
trunk/Hibernate3/test/org/hibernate/test/dialect/functional/cache/
trunk/Hibernate3/test/org/hibernate/test/dialect/functional/cache/SQLFunctionsInterSystemsTest.java
trunk/Hibernate3/test/org/hibernate/test/dialect/functional/cache/TestInterSystemsFunctionsClass.hbm.xml
trunk/Hibernate3/test/org/hibernate/test/dialect/functional/cache/TestInterSystemsFunctionsClass.java
trunk/Hibernate3/test/org/hibernate/test/dialect/unit/
trunk/Hibernate3/test/org/hibernate/test/dialect/unit/DialectUnitTestsSuite.java
trunk/Hibernate3/test/org/hibernate/test/dialect/unit/lockhint/
trunk/Hibernate3/test/org/hibernate/test/dialect/unit/lockhint/AbstractLockHintTest.java
trunk/Hibernate3/test/org/hibernate/test/dialect/unit/lockhint/SQLServerLockHintsTest.java
trunk/Hibernate3/test/org/hibernate/test/dialect/unit/lockhint/SybaseLockHintsTest.java
Removed:
trunk/Hibernate3/test/org/hibernate/test/dialect/cache/
Modified:
trunk/Hibernate3/src/org/hibernate/dialect/Dialect.java
trunk/Hibernate3/src/org/hibernate/dialect/SQLServerDialect.java
trunk/Hibernate3/src/org/hibernate/dialect/SybaseDialect.java
trunk/Hibernate3/src/org/hibernate/hql/classic/QueryTranslatorImpl.java
trunk/Hibernate3/src/org/hibernate/loader/AbstractEntityJoinWalker.java
trunk/Hibernate3/src/org/hibernate/loader/criteria/CriteriaLoader.java
trunk/Hibernate3/src/org/hibernate/loader/hql/QueryLoader.java
trunk/Hibernate3/test/org/hibernate/test/AllTests.java
Log:
HHH-1889 : LockModes + Sybase / SQL Server
Modified: trunk/Hibernate3/src/org/hibernate/dialect/Dialect.java
===================================================================
--- trunk/Hibernate3/src/org/hibernate/dialect/Dialect.java 2007-01-23 13:54:45 UTC (rev 11079)
+++ trunk/Hibernate3/src/org/hibernate/dialect/Dialect.java 2007-01-23 16:29:18 UTC (rev 11080)
@@ -38,6 +38,7 @@
import org.hibernate.sql.ANSIJoinFragment;
import org.hibernate.sql.CaseFragment;
import org.hibernate.sql.JoinFragment;
+import org.hibernate.sql.ForUpdateFragment;
import org.hibernate.type.Type;
import org.hibernate.util.ReflectHelper;
import org.hibernate.util.StringHelper;
@@ -901,7 +902,24 @@
return tableName;
}
+ /**
+ * Modifies the given SQL by applying the appropriate updates for the specified
+ * lock modes and key columns.
+ * <p/>
+ * The behavior here is that of an ANSI SQL <tt>SELECT FOR UPDATE</tt>. This
+ * method is really intended to allow dialects which do not support
+ * <tt>SELECT FOR UPDATE</tt> to achieve this in their own fashion.
+ *
+ * @param sql the SQL string to modify
+ * @param aliasedLockModes a map of lock modes indexed by aliased table names.
+ * @param keyColumnNames a map of key columns indexed by aliased table names.
+ * @return the modified SQL string.
+ */
+ public String applyLocksToSql(String sql, Map aliasedLockModes, Map keyColumnNames) {
+ return sql + new ForUpdateFragment( this, aliasedLockModes, keyColumnNames ).toFragmentString();
+ }
+
// temporary table support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/**
Modified: trunk/Hibernate3/src/org/hibernate/dialect/SQLServerDialect.java
===================================================================
--- trunk/Hibernate3/src/org/hibernate/dialect/SQLServerDialect.java 2007-01-23 13:54:45 UTC (rev 11079)
+++ trunk/Hibernate3/src/org/hibernate/dialect/SQLServerDialect.java 2007-01-23 16:29:18 UTC (rev 11080)
@@ -2,16 +2,19 @@
package org.hibernate.dialect;
import java.sql.Types;
+import java.util.Map;
+import java.util.Iterator;
import org.hibernate.Hibernate;
import org.hibernate.LockMode;
+import org.hibernate.util.StringHelper;
import org.hibernate.dialect.function.SQLFunctionTemplate;
import org.hibernate.dialect.function.StandardSQLFunction;
import org.hibernate.dialect.function.AnsiTrimEmulationFunction;
/**
* A dialect for Microsoft SQL Server 2000 and 2005
- *
+ *
* @author Gavin King
*/
public class SQLServerDialect extends SybaseDialect {
@@ -20,10 +23,10 @@
registerColumnType( Types.VARBINARY, "image" );
registerColumnType( Types.VARBINARY, 8000, "varbinary($l)" );
- registerFunction( "second", new SQLFunctionTemplate(Hibernate.INTEGER, "datepart(second, ?1)") );
- registerFunction( "minute", new SQLFunctionTemplate(Hibernate.INTEGER, "datepart(minute, ?1)") );
- registerFunction( "hour", new SQLFunctionTemplate(Hibernate.INTEGER, "datepart(hour, ?1)") );
- registerFunction( "locate", new StandardSQLFunction("charindex", Hibernate.INTEGER) );
+ registerFunction( "second", new SQLFunctionTemplate( Hibernate.INTEGER, "datepart(second, ?1)" ) );
+ registerFunction( "minute", new SQLFunctionTemplate( Hibernate.INTEGER, "datepart(minute, ?1)" ) );
+ registerFunction( "hour", new SQLFunctionTemplate( Hibernate.INTEGER, "datepart(hour, ?1)" ) );
+ registerFunction( "locate", new StandardSQLFunction( "charindex", Hibernate.INTEGER ) );
registerFunction( "extract", new SQLFunctionTemplate( Hibernate.INTEGER, "datepart(?1, ?3)" ) );
registerFunction( "mod", new SQLFunctionTemplate( Hibernate.INTEGER, "?1 % ?2" ) );
@@ -31,7 +34,7 @@
registerFunction( "trim", new AnsiTrimEmulationFunction() );
- registerKeyword("top");
+ registerKeyword( "top" );
}
public String getNoColumnsInsertString() {
@@ -48,10 +51,10 @@
if ( offset > 0 ) {
throw new UnsupportedOperationException( "sql server has no offset" );
}
- return new StringBuffer( querySelect.length()+8 )
- .append(querySelect)
- .insert( getAfterSelectInsertPoint(querySelect), " top " + limit )
- .toString();
+ return new StringBuffer( querySelect.length() + 8 )
+ .append( querySelect )
+ .insert( getAfterSelectInsertPoint( querySelect ), " top " + limit )
+ .toString();
}
/**
@@ -86,7 +89,7 @@
}
public String appendLockHint(LockMode mode, String tableName) {
- if ( mode.greaterThan(LockMode.READ) ) {
+ if ( mode.greaterThan( LockMode.READ ) ) {
// does this need holdlock also? : return tableName + " with (updlock, rowlock, holdlock)";
return tableName + " with (updlock, rowlock)";
}
@@ -105,7 +108,6 @@
return "select current_timestamp";
}
-
// Overridden informational metadata ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public boolean areStringComparisonsCaseInsensitive() {
Modified: trunk/Hibernate3/src/org/hibernate/dialect/SybaseDialect.java
===================================================================
--- trunk/Hibernate3/src/org/hibernate/dialect/SybaseDialect.java 2007-01-23 13:54:45 UTC (rev 11079)
+++ trunk/Hibernate3/src/org/hibernate/dialect/SybaseDialect.java 2007-01-23 16:29:18 UTC (rev 11080)
@@ -5,6 +5,8 @@
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
+import java.util.Map;
+import java.util.Iterator;
import org.hibernate.Hibernate;
import org.hibernate.LockMode;
@@ -133,13 +135,48 @@
}
public String appendLockHint(LockMode mode, String tableName) {
- if ( mode.greaterThan(LockMode.READ) ) {
+ if ( mode.greaterThan( LockMode.READ ) ) {
return tableName + " holdlock";
}
else {
return tableName;
}
}
+
+ public String applyLocksToSql(String sql, Map aliasedLockModes, Map keyColumnNames) {
+ Iterator itr = aliasedLockModes.entrySet().iterator();
+ StringBuffer buffer = new StringBuffer( sql );
+ int correction = 0;
+ while ( itr.hasNext() ) {
+ final Map.Entry entry = ( Map.Entry ) itr.next();
+ final LockMode lockMode = ( LockMode ) entry.getValue();
+ if ( lockMode.greaterThan( LockMode.READ ) ) {
+ final String alias = ( String ) entry.getKey();
+ int start = -1, end = -1;
+ if ( sql.endsWith( " " + alias ) ) {
+ start = ( sql.length() - alias.length() ) + correction;
+ end = start + alias.length();
+ }
+ else {
+ int position = sql.indexOf( " " + alias + " " );
+ if ( position <= -1 ) {
+ position = sql.indexOf( " " + alias + "," );
+ }
+ if ( position > -1 ) {
+ start = position + correction + 1;
+ end = start + alias.length();
+ }
+ }
+
+ if ( start > -1 ) {
+ final String lockHint = appendLockHint( lockMode, alias );
+ buffer.replace( start, end, lockHint );
+ correction += ( lockHint.length() - alias.length() );
+ }
+ }
+ }
+ return buffer.toString();
+ }
public int registerResultSetOutParameter(CallableStatement statement, int col) throws SQLException {
return col; // sql server just returns automatically
Modified: trunk/Hibernate3/src/org/hibernate/hql/classic/QueryTranslatorImpl.java
===================================================================
--- trunk/Hibernate3/src/org/hibernate/hql/classic/QueryTranslatorImpl.java 2007-01-23 13:54:45 UTC (rev 11079)
+++ trunk/Hibernate3/src/org/hibernate/hql/classic/QueryTranslatorImpl.java 2007-01-23 16:29:18 UTC (rev 11080)
@@ -17,12 +17,12 @@
import org.apache.commons.collections.SequencedHashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.MappingException;
import org.hibernate.QueryException;
import org.hibernate.ScrollableResults;
-import org.hibernate.hql.ParameterTranslations;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.JoinSequence;
import org.hibernate.engine.QueryParameters;
@@ -33,6 +33,7 @@
import org.hibernate.hql.FilterTranslator;
import org.hibernate.hql.HolderInstantiator;
import org.hibernate.hql.NameGenerator;
+import org.hibernate.hql.ParameterTranslations;
import org.hibernate.impl.IteratorImpl;
import org.hibernate.loader.BasicLoader;
import org.hibernate.persister.collection.CollectionPersister;
@@ -40,7 +41,6 @@
import org.hibernate.persister.entity.Loadable;
import org.hibernate.persister.entity.PropertyMapping;
import org.hibernate.persister.entity.Queryable;
-import org.hibernate.sql.ForUpdateFragment;
import org.hibernate.sql.JoinFragment;
import org.hibernate.sql.QuerySelect;
import org.hibernate.transform.ResultTransformer;
@@ -56,8 +56,7 @@
* An instance of <tt>QueryTranslator</tt> translates a Hibernate
* query string to SQL.
*/
-public class QueryTranslatorImpl extends BasicLoader
- implements FilterTranslator {
+public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator {
private static final String[] NO_RETURN_ALIASES = new String[] {};
@@ -121,6 +120,13 @@
/**
* Construct a query translator
+ *
+ * @param queryIdentifier A unique identifier for the query of which this
+ * translation is part; typically this is the original, user-supplied query string.
+ * @param queryString The "preprocessed" query string; at the very least
+ * already processed by {@link org.hibernate.hql.QuerySplitter}.
+ * @param enabledFilters Any enabled filters.
+ * @param factory The session factory.
*/
public QueryTranslatorImpl(
String queryIdentifier,
@@ -134,7 +140,11 @@
}
/**
- * Construct a query translator
+ * Construct a query translator; this form used internally.
+ *
+ * @param queryString The query string to process.
+ * @param enabledFilters Any enabled filters.
+ * @param factory The session factory.
*/
public QueryTranslatorImpl(
String queryString,
@@ -144,10 +154,16 @@
}
/**
- * Compile a subquery
+ * Compile a subquery.
+ *
+ * @param superquery The containing query of the query to be compiled.
+ *
+ * @throws org.hibernate.MappingException Indicates problems resolving
+ * things referenced in the query.
+ * @throws org.hibernate.QueryException Generally some form of syntatic
+ * failure.
*/
- void compile(QueryTranslatorImpl superquery)
- throws QueryException, MappingException {
+ void compile(QueryTranslatorImpl superquery) throws QueryException, MappingException {
this.tokenReplacements = superquery.tokenReplacements;
this.superQuery = superquery;
this.shallowQuery = true;
@@ -160,8 +176,9 @@
* Compile a "normal" query. This method may be called multiple
* times. Subsequent invocations are no-ops.
*/
- public synchronized void compile(Map replacements, boolean scalar)
- throws QueryException, MappingException {
+ public synchronized void compile(
+ Map replacements,
+ boolean scalar) throws QueryException, MappingException {
if ( !compiled ) {
this.tokenReplacements = replacements;
this.shallowQuery = scalar;
@@ -173,8 +190,10 @@
* Compile a filter. This method may be called multiple
* times. Subsequent invocations are no-ops.
*/
- public synchronized void compile(String collectionRole, Map replacements, boolean scalar)
- throws QueryException, MappingException {
+ public synchronized void compile(
+ String collectionRole,
+ Map replacements,
+ boolean scalar) throws QueryException, MappingException {
if ( !isCompiled() ) {
addFromAssociation( "this", collectionRole );
@@ -184,6 +203,11 @@
/**
* Compile the query (generate the SQL).
+ *
+ * @throws org.hibernate.MappingException Indicates problems resolving
+ * things referenced in the query.
+ * @throws org.hibernate.QueryException Generally some form of syntatic
+ * failure.
*/
private void compile() throws QueryException, MappingException {
@@ -1031,7 +1055,7 @@
keyColumnNames.put( names[i], persisters[i].getIdentifierColumnNames() );
}
}
- result = sql + new ForUpdateFragment( dialect, aliasedLockModes, keyColumnNames ).toFragmentString();
+ result = dialect.applyLocksToSql( sql, aliasedLockModes, keyColumnNames );
}
logQuery( queryString, result );
return result;
Modified: trunk/Hibernate3/src/org/hibernate/loader/AbstractEntityJoinWalker.java
===================================================================
--- trunk/Hibernate3/src/org/hibernate/loader/AbstractEntityJoinWalker.java 2007-01-23 13:54:45 UTC (rev 11079)
+++ trunk/Hibernate3/src/org/hibernate/loader/AbstractEntityJoinWalker.java 2007-01-23 16:29:18 UTC (rev 11080)
@@ -77,38 +77,37 @@
throws MappingException {
initStatementString(null, condition, orderBy, "", lockMode);
}
-
+
private void initStatementString(
final String projection,
final String condition,
final String orderBy,
final String groupBy,
- final LockMode lockMode)
- throws MappingException {
+ final LockMode lockMode) throws MappingException {
final int joins = countEntityPersisters( associations );
- suffixes = BasicLoader.generateSuffixes( joins+1 );
+ suffixes = BasicLoader.generateSuffixes( joins + 1 );
JoinFragment ojf = mergeOuterJoins( associations );
-
+
Select select = new Select( getDialect() )
- .setLockMode(lockMode)
- .setSelectClause(
- projection==null ?
- persister.selectFragment( alias, suffixes[joins] ) + selectString(associations) :
- projection
- )
- .setFromClause(
- persister.fromTableFragment(alias) +
- persister.fromJoinFragment(alias, true, true)
- )
- .setWhereClause(condition)
- .setOuterJoins(
- ojf.toFromFragmentString(),
- ojf.toWhereFragmentString() + getWhereFragment()
- )
- .setOrderByClause( orderBy( associations, orderBy ) )
- .setGroupByClause(groupBy);
+ .setLockMode( lockMode )
+ .setSelectClause(
+ projection == null ?
+ persister.selectFragment( alias, suffixes[joins] ) + selectString( associations ) :
+ projection
+ )
+ .setFromClause(
+ getDialect().appendLockHint( lockMode, persister.fromTableFragment( alias ) ) +
+ persister.fromJoinFragment( alias, true, true )
+ )
+ .setWhereClause( condition )
+ .setOuterJoins(
+ ojf.toFromFragmentString(),
+ ojf.toWhereFragmentString() + getWhereFragment()
+ )
+ .setOrderByClause( orderBy( associations, orderBy ) )
+ .setGroupByClause( groupBy );
if ( getFactory().getSettings().isCommentsEnabled() ) {
select.setComment( getComment() );
@@ -116,10 +115,8 @@
sql = select.toStatementString();
}
- /**
- * Don't bother with the discriminator, unless overridded by subclass
- */
protected String getWhereFragment() throws MappingException {
+ // here we do not bother with the discriminator.
return persister.whereJoinFragment(alias, true, true);
}
Modified: trunk/Hibernate3/src/org/hibernate/loader/criteria/CriteriaLoader.java
===================================================================
--- trunk/Hibernate3/src/org/hibernate/loader/criteria/CriteriaLoader.java 2007-01-23 13:54:45 UTC (rev 11079)
+++ trunk/Hibernate3/src/org/hibernate/loader/criteria/CriteriaLoader.java 2007-01-23 16:29:18 UTC (rev 11080)
@@ -21,7 +21,6 @@
import org.hibernate.loader.OuterJoinLoader;
import org.hibernate.persister.entity.Loadable;
import org.hibernate.persister.entity.OuterJoinLoadable;
-import org.hibernate.sql.ForUpdateFragment;
import org.hibernate.transform.ResultTransformer;
import org.hibernate.type.Type;
@@ -121,33 +120,28 @@
return querySpaces;
}
- protected String applyLocks(String sqlSelectString, Map lockModes, Dialect dialect)
- throws QueryException {
-
- if ( lockModes==null || lockModes.size()==0 ) {
+ protected String applyLocks(String sqlSelectString, Map lockModes, Dialect dialect) throws QueryException {
+ if ( lockModes == null || lockModes.isEmpty() ) {
return sqlSelectString;
}
- else {
- Map keyColumnNames = null;
- Loadable[] persisters = getEntityPersisters();
- String[] entityAliases = getAliases();
- if ( dialect.forUpdateOfColumns() ) {
- keyColumnNames = new HashMap();
- for ( int i=0; i<entityAliases.length; i++ ) {
- keyColumnNames.put(
- entityAliases[i],
- persisters[i].getIdentifierColumnNames()
- );
- }
+
+ Map keyColumnNames = null;
+ Loadable[] persisters = getEntityPersisters();
+ String[] entityAliases = getAliases();
+ if ( dialect.forUpdateOfColumns() ) {
+ keyColumnNames = new HashMap();
+ for ( int i=0; i<entityAliases.length; i++ ) {
+ keyColumnNames.put( entityAliases[i], persisters[i].getIdentifierColumnNames() );
}
- return sqlSelectString +
- new ForUpdateFragment(dialect, lockModes, keyColumnNames).toFragmentString();
}
+ return dialect.applyLocksToSql( sqlSelectString, lockModes, keyColumnNames );
}
protected LockMode[] getLockModes(Map lockModes) {
final String[] entityAliases = getAliases();
- if (entityAliases==null) return null;
+ if ( entityAliases == null ) {
+ return null;
+ }
final int size = entityAliases.length;
LockMode[] lockModesArray = new LockMode[size];
for ( int i=0; i<size; i++ ) {
@@ -162,8 +156,7 @@
}
protected List getResultList(List results, ResultTransformer resultTransformer) {
- return translator.getRootCriteria().getResultTransformer()
- .transformList(results);
+ return translator.getRootCriteria().getResultTransformer().transformList( results );
}
}
Modified: trunk/Hibernate3/src/org/hibernate/loader/hql/QueryLoader.java
===================================================================
--- trunk/Hibernate3/src/org/hibernate/loader/hql/QueryLoader.java 2007-01-23 13:54:45 UTC (rev 11079)
+++ trunk/Hibernate3/src/org/hibernate/loader/hql/QueryLoader.java 2007-01-23 16:29:18 UTC (rev 11080)
@@ -9,19 +9,14 @@
import java.util.List;
import java.util.Map;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.QueryException;
import org.hibernate.ScrollableResults;
-import org.hibernate.TypeMismatchException;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.QueryParameters;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.engine.SessionImplementor;
-import org.hibernate.engine.TypedValue;
import org.hibernate.event.EventSource;
import org.hibernate.exception.JDBCExceptionHelper;
import org.hibernate.hql.HolderInstantiator;
@@ -35,7 +30,6 @@
import org.hibernate.persister.collection.QueryableCollection;
import org.hibernate.persister.entity.Loadable;
import org.hibernate.persister.entity.Queryable;
-import org.hibernate.sql.ForUpdateFragment;
import org.hibernate.transform.ResultTransformer;
import org.hibernate.type.EntityType;
import org.hibernate.type.Type;
@@ -48,8 +42,6 @@
*/
public class QueryLoader extends BasicLoader {
- private static final Log log = LogFactory.getLog( QueryLoader.class );
-
/**
* The query translator that is delegating to this object.
*/
@@ -84,10 +76,7 @@
private LockMode[] defaultLockModes;
- private final boolean isCollectionFilter;
-
-
/**
* Creates a new Loader implementation.
*
@@ -101,7 +90,6 @@
final SelectClause selectClause) {
super( factory );
this.queryTranslator = queryTranslator;
- this.isCollectionFilter = selectClause.getWalker().isFilter();
initialize( selectClause );
postInstantiate();
}
@@ -288,15 +276,12 @@
}
}
- protected String applyLocks(String sql, Map lockModes, Dialect dialect)
- throws QueryException {
-
+ protected String applyLocks(String sql, Map lockModes, Dialect dialect) throws QueryException {
if ( lockModes == null || lockModes.size() == 0 ) {
return sql;
}
else {
// can't cache this stuff either (per-invocation)
-
//we are given a map of user alias -> lock mode
//create a new map of sql alias -> lock mode
final Map aliasedLockModes = new HashMap();
@@ -321,8 +306,7 @@
}
}
- return sql + new ForUpdateFragment( dialect, aliasedLockModes, keyColumnNames ).toFragmentString();
-
+ return dialect.applyLocksToSql( sql, aliasedLockModes, keyColumnNames );
}
}
@@ -384,31 +368,22 @@
// --- Query translator methods ---
- /**
- * Delegats
- *
- * @param session
- * @param queryParameters
- * @return
- * @throws HibernateException
- */
- public List list(SessionImplementor session, QueryParameters queryParameters)
- throws HibernateException {
+ public List list(
+ SessionImplementor session,
+ QueryParameters queryParameters) throws HibernateException {
checkQuery( queryParameters );
return list( session, queryParameters, queryTranslator.getQuerySpaces(), queryReturnTypes );
}
private void checkQuery(QueryParameters queryParameters) {
- if(hasSelectNew() && queryParameters.getResultTransformer()!=null) {
- throw new QueryException("ResultTransformer is not allowed for 'select new' queries.");
+ if ( hasSelectNew() && queryParameters.getResultTransformer() != null ) {
+ throw new QueryException( "ResultTransformer is not allowed for 'select new' queries." );
}
}
- /**
- * Return the query results as an iterator
- */
- public Iterator iterate(QueryParameters queryParameters, EventSource session)
- throws HibernateException {
+ public Iterator iterate(
+ QueryParameters queryParameters,
+ EventSource session) throws HibernateException {
checkQuery( queryParameters );
final boolean stats = session.getFactory().getStatistics().isStatisticsEnabled();
long startTime = 0;
Modified: trunk/Hibernate3/test/org/hibernate/test/AllTests.java
===================================================================
--- trunk/Hibernate3/test/org/hibernate/test/AllTests.java 2007-01-23 13:54:45 UTC (rev 11079)
+++ trunk/Hibernate3/test/org/hibernate/test/AllTests.java 2007-01-23 16:29:18 UTC (rev 11080)
@@ -30,7 +30,6 @@
import org.hibernate.test.cuk.CompositePropertyRefTest;
import org.hibernate.test.cut.CompositeUserTypeTest;
import org.hibernate.test.deletetransient.DeleteTransientEntityTest;
-import org.hibernate.test.dialect.cache.SQLFunctionsInterSystemsTest;
import org.hibernate.test.discriminator.DiscriminatorTest;
import org.hibernate.test.dynamicentity.interceptor.InterceptorDynamicEntityTest;
import org.hibernate.test.dynamicentity.tuplizer.TuplizerDynamicEntityTest;
@@ -128,6 +127,8 @@
import org.hibernate.test.version.db.DbVersionTest;
import org.hibernate.test.version.sybase.SybaseTimestampVersioningTest;
import org.hibernate.test.where.WhereTest;
+import org.hibernate.test.dialect.functional.DialectFunctionalTestsSuite;
+import org.hibernate.test.dialect.unit.DialectUnitTestsSuite;
/**
* @author Gavin King
@@ -271,12 +272,13 @@
suite.addTest( AbstractCompositeIdTest.suite() );
suite.addTest( UtilSuite.suite() );
suite.addTest( AnyTypeTest.suite() );
- suite.addTest( SQLFunctionsInterSystemsTest.suite() );
suite.addTest( LobSuite.suite() );
suite.addTest( IdentifierPropertyReferencesTest.suite() );
suite.addTest( DeleteTransientEntityTest.suite() );
suite.addTest( UserCollectionTypeTest.suite() );
suite.addTest( KeyManyToOneSuite.suite() );
+ suite.addTest( DialectFunctionalTestsSuite.suite() );
+ suite.addTest( DialectUnitTestsSuite.suite() );
return filter( suite );
}
Added: trunk/Hibernate3/test/org/hibernate/test/dialect/functional/DialectFunctionalTestsSuite.java
===================================================================
--- trunk/Hibernate3/test/org/hibernate/test/dialect/functional/DialectFunctionalTestsSuite.java (rev 0)
+++ trunk/Hibernate3/test/org/hibernate/test/dialect/functional/DialectFunctionalTestsSuite.java 2007-01-23 16:29:18 UTC (rev 11080)
@@ -0,0 +1,18 @@
+package org.hibernate.test.dialect.functional;
+
+import junit.framework.TestSuite;
+
+import org.hibernate.test.dialect.functional.cache.SQLFunctionsInterSystemsTest;
+
+/**
+ * {@inheritDoc}
+ *
+ * @author Steve Ebersole
+ */
+public class DialectFunctionalTestsSuite {
+ public static TestSuite suite() {
+ TestSuite suite = new TestSuite( "Dialect tests" );
+ suite.addTest( SQLFunctionsInterSystemsTest.suite() );
+ return suite;
+ }
+}
Copied: trunk/Hibernate3/test/org/hibernate/test/dialect/functional/cache/SQLFunctionsInterSystemsTest.java (from rev 11075, trunk/Hibernate3/test/org/hibernate/test/dialect/cache/SQLFunctionsInterSystemsTest.java)
===================================================================
--- trunk/Hibernate3/test/org/hibernate/test/dialect/functional/cache/SQLFunctionsInterSystemsTest.java (rev 0)
+++ trunk/Hibernate3/test/org/hibernate/test/dialect/functional/cache/SQLFunctionsInterSystemsTest.java 2007-01-23 16:29:18 UTC (rev 11080)
@@ -0,0 +1,740 @@
+package org.hibernate.test.dialect.functional.cache;
+
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import junit.framework.Test;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import org.hibernate.Hibernate;
+import org.hibernate.LockMode;
+import org.hibernate.Query;
+import org.hibernate.ScrollableResults;
+import org.hibernate.Transaction;
+import org.hibernate.classic.Session;
+import org.hibernate.dialect.Cache71Dialect;
+import org.hibernate.dialect.Dialect;
+import org.hibernate.dialect.HSQLDialect;
+import org.hibernate.dialect.InterbaseDialect;
+import org.hibernate.dialect.MckoiDialect;
+import org.hibernate.dialect.MySQLDialect;
+import org.hibernate.dialect.Oracle9Dialect;
+import org.hibernate.dialect.SybaseDialect;
+import org.hibernate.dialect.TimesTenDialect;
+import org.hibernate.dialect.function.SQLFunction;
+import org.hibernate.junit.functional.DatabaseSpecificFunctionalTestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+import org.hibernate.test.legacy.Blobber;
+import org.hibernate.test.legacy.Broken;
+import org.hibernate.test.legacy.Fixed;
+import org.hibernate.test.legacy.Simple;
+import org.hibernate.test.legacy.Single;
+
+/**
+ * Tests for function support on CacheSQL...
+ *
+ * @author Jonathan Levinson
+ */
+public class SQLFunctionsInterSystemsTest extends DatabaseSpecificFunctionalTestCase {
+
+ private static final Log log = LogFactory.getLog(SQLFunctionsInterSystemsTest.class);
+
+ public SQLFunctionsInterSystemsTest(String name) {
+ super(name);
+ }
+
+ public String[] getMappings() {
+ return new String[] {
+ "legacy/AltSimple.hbm.xml",
+ "legacy/Broken.hbm.xml",
+ "legacy/Blobber.hbm.xml",
+ "dialect/cache/TestInterSystemsFunctionsClass.hbm.xml"
+ };
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( SQLFunctionsInterSystemsTest.class );
+ }
+
+ public boolean appliesTo(Dialect dialect) {
+ // all these test case apply only to testing InterSystems' CacheSQL dialect
+ return dialect instanceof Cache71Dialect;
+ }
+
+ public void testDialectSQLFunctions() throws Exception {
+
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+
+ Iterator iter = s.iterate("select max(s.count) from Simple s");
+
+ if ( getDialect() instanceof MySQLDialect ) assertTrue( iter.hasNext() && iter.next()==null );
+
+ Simple simple = new Simple();
+ simple.setName("Simple Dialect Function Test");
+ simple.setAddress("Simple Address");
+ simple.setPay(new Float(45.8));
+ simple.setCount(2);
+ s.save(simple, new Long(10) );
+
+ // Test to make sure allocating an specified object operates correctly.
+ assertTrue(
+ s.find("select new org.hibernate.test.legacy.S(s.count, s.address) from Simple s").size() == 1
+ );
+
+ // Quick check the base dialect functions operate correctly
+ assertTrue(
+ s.find("select max(s.count) from Simple s").size() == 1
+ );
+ assertTrue(
+ s.find("select count(*) from Simple s").size() == 1
+ );
+
+ if ( getDialect() instanceof Cache71Dialect) {
+ // Check Oracle Dialect mix of dialect functions - no args (no parenthesis and single arg functions
+ java.util.List rset = s.find("select s.name, sysdate, floor(s.pay), round(s.pay,0) from Simple s");
+ assertNotNull("Name string should have been returned",(((Object[])rset.get(0))[0]));
+ assertNotNull("Todays Date should have been returned",(((Object[])rset.get(0))[1]));
+ assertEquals("floor(45.8) result was incorrect ", new Integer(45), ( (Object[]) rset.get(0) )[2] );
+ assertEquals("round(45.8) result was incorrect ", new Float(46), ( (Object[]) rset.get(0) )[3] );
+
+ simple.setPay(new Float(-45.8));
+ s.update(simple);
+
+ // Test type conversions while using nested functions (Float to Int).
+ rset = s.find("select abs(round(s.pay,0)) from Simple s");
+ assertEquals("abs(round(-45.8)) result was incorrect ", new Float(46), rset.get(0));
+
+ // Test a larger depth 3 function example - Not a useful combo other than for testing
+ assertTrue(
+ s.find("select floor(round(sysdate,1)) from Simple s").size() == 1
+ );
+
+ // Test the oracle standard NVL funtion as a test of multi-param functions...
+ simple.setPay(null);
+ s.update(simple);
+ Double value = (Double) s.createQuery("select mod( nvl(s.pay, 5000), 2 ) from Simple as s where s.id = 10").list().get(0);
+ assertTrue( 0 == value.intValue() );
+ }
+
+ if ( (getDialect() instanceof Cache71Dialect) ) {
+ // Test the hsql standard MOD funtion as a test of multi-param functions...
+ Double value = (Double) s.find("select MOD(s.count, 2) from Simple as s where s.id = 10" ).get(0);
+ assertTrue( 0 == value.intValue() );
+ }
+
+ /*
+ if ( (getDialect() instanceof Cache71Dialect) ) {
+ // Test the hsql standard MOD funtion as a test of multi-param functions...
+ Date value = (Date) s.find("select sysdate from Simple as s where nvl(cast(null as date), sysdate)=sysdate" ).get(0);
+ assertTrue( value.equals(new java.sql.Date(System.currentTimeMillis())));
+ }
+ */
+
+ s.delete(simple);
+ t.commit();
+ s.close();
+ }
+
+ public void testSetProperties() throws Exception {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Simple simple = new Simple();
+ simple.setName("Simple 1");
+ s.save(simple, new Long(10) );
+ Query q = s.createQuery("from Simple s where s.name=:name and s.count=:count");
+ q.setProperties(simple);
+ assertTrue( q.list().get(0)==simple );
+ //misuse of "Single" as a propertyobject, but it was the first testclass i found with a collection ;)
+ Single single = new Single() { // trivial hack to test properties with arrays.
+ String[] getStuff() { return (String[]) getSeveral().toArray(new String[getSeveral().size()]); }
+ };
+
+ List l = new ArrayList();
+ l.add("Simple 1");
+ l.add("Slimeball");
+ single.setSeveral(l);
+ q = s.createQuery("from Simple s where s.name in (:several)");
+ q.setProperties(single);
+ assertTrue( q.list().get(0)==simple );
+
+
+ q = s.createQuery("from Simple s where s.name in (:stuff)");
+ q.setProperties(single);
+ assertTrue( q.list().get(0)==simple );
+ s.delete(simple);
+ t.commit();
+ s.close();
+ }
+
+ public void testBroken() throws Exception {
+ if (getDialect() instanceof Oracle9Dialect) return;
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Broken b = new Fixed();
+ b.setId( new Long(123));
+ b.setOtherId("foobar");
+ s.save(b);
+ s.flush();
+ b.setTimestamp( new Date() );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.update(b);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ b = (Broken) s.load( Broken.class, b );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.delete(b);
+ t.commit();
+ s.close();
+ }
+
+ public void testNothinToUpdate() throws Exception {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Simple simple = new Simple();
+ simple.setName("Simple 1");
+ s.save( simple, new Long(10) );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.update( simple, new Long(10) );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.update( simple, new Long(10) );
+ s.delete(simple);
+ t.commit();
+ s.close();
+ }
+
+ public void testCachedQuery() throws Exception {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Simple simple = new Simple();
+ simple.setName("Simple 1");
+ s.save( simple, new Long(10) );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ Query q = s.createQuery("from Simple s where s.name=?");
+ q.setCacheable(true);
+ q.setString(0, "Simple 1");
+ assertTrue( q.list().size()==1 );
+ assertTrue( q.list().size()==1 );
+ assertTrue( q.list().size()==1 );
+ q = s.createQuery("from Simple s where s.name=:name");
+ q.setCacheable(true);
+ q.setString("name", "Simple 1");
+ assertTrue( q.list().size()==1 );
+ simple = (Simple) q.list().get(0);
+
+ q.setString("name", "Simple 2");
+ assertTrue( q.list().size()==0 );
+ assertTrue( q.list().size()==0 );
+ simple.setName("Simple 2");
+ assertTrue( q.list().size()==1 );
+ assertTrue( q.list().size()==1 );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ q = s.createQuery("from Simple s where s.name=:name");
+ q.setString("name", "Simple 2");
+ q.setCacheable(true);
+ assertTrue( q.list().size()==1 );
+ assertTrue( q.list().size()==1 );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.update( simple, new Long(10) );
+ s.delete(simple);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ q = s.createQuery("from Simple s where s.name=?");
+ q.setCacheable(true);
+ q.setString(0, "Simple 1");
+ assertTrue( q.list().size()==0 );
+ assertTrue( q.list().size()==0 );
+ t.commit();
+ s.close();
+ }
+
+ public void testCachedQueryRegion() throws Exception {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Simple simple = new Simple();
+ simple.setName("Simple 1");
+ s.save( simple, new Long(10) );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ Query q = s.createQuery("from Simple s where s.name=?");
+ q.setCacheRegion("foo");
+ q.setCacheable(true);
+ q.setString(0, "Simple 1");
+ assertTrue( q.list().size()==1 );
+ assertTrue( q.list().size()==1 );
+ assertTrue( q.list().size()==1 );
+ q = s.createQuery("from Simple s where s.name=:name");
+ q.setCacheRegion("foo");
+ q.setCacheable(true);
+ q.setString("name", "Simple 1");
+ assertTrue( q.list().size()==1 );
+ simple = (Simple) q.list().get(0);
+
+ q.setString("name", "Simple 2");
+ assertTrue( q.list().size()==0 );
+ assertTrue( q.list().size()==0 );
+ simple.setName("Simple 2");
+ assertTrue( q.list().size()==1 );
+ assertTrue( q.list().size()==1 );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.update( simple, new Long(10) );
+ s.delete(simple);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ q = s.createQuery("from Simple s where s.name=?");
+ q.setCacheRegion("foo");
+ q.setCacheable(true);
+ q.setString(0, "Simple 1");
+ assertTrue( q.list().size()==0 );
+ assertTrue( q.list().size()==0 );
+ t.commit();
+ s.close();
+ }
+
+ public void testSQLFunctions() throws Exception {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Simple simple = new Simple();
+ simple.setName("Simple 1");
+ s.save(simple, new Long(10) );
+
+ if ( getDialect() instanceof Cache71Dialect) {
+ s.find("from Simple s where repeat('foo', 3) = 'foofoofoo'");
+ s.find("from Simple s where repeat(s.name, 3) = 'foofoofoo'");
+ s.find("from Simple s where repeat( lower(s.name), (3 + (1-1)) / 2) = 'foofoofoo'");
+ }
+
+ assertTrue(
+ s.find("from Simple s where upper( s.name ) ='SIMPLE 1'").size()==1
+ );
+ if ( !(getDialect() instanceof HSQLDialect) ) {
+ assertTrue(
+ s.find("from Simple s where not( upper( s.name ) ='yada' or 1=2 or 'foo'='bar' or not('foo'='foo') or 'foo' like 'bar' )").size()==1
+ );
+ }
+ if ( !(getDialect() instanceof MySQLDialect) && !(getDialect() instanceof SybaseDialect) && !(getDialect() instanceof MckoiDialect) && !(getDialect() instanceof InterbaseDialect) && !(getDialect() instanceof TimesTenDialect) ) { //My SQL has a funny concatenation operator
+ assertTrue(
+ s.find("from Simple s where lower( s.name || ' foo' ) ='simple 1 foo'").size()==1
+ );
+ }
+ /* + is not concat in Cache
+ if ( (getDialect() instanceof Cache71Dialect) ) {
+ assertTrue(
+ s.find("from Simple s where lower( cons.name ' foo' ) ='simple 1 foo'").size()==1
+ );
+ }
+ */
+ if ( (getDialect() instanceof Cache71Dialect) ) {
+ assertTrue(
+ s.find("from Simple s where lower( concat(s.name, ' foo') ) ='simple 1 foo'").size()==1
+ );
+ }
+
+ Simple other = new Simple();
+ other.setName("Simple 2");
+ other.setCount(12);
+ simple.setOther(other);
+ s.save( other, new Long(20) );
+ //s.find("from Simple s where s.name ## 'cat|rat|bag'");
+ assertTrue(
+ s.find("from Simple s where upper( s.other.name ) ='SIMPLE 2'").size()==1
+ );
+ assertTrue(
+ s.find("from Simple s where not ( upper( s.other.name ) ='SIMPLE 2' )").size()==0
+ );
+ assertTrue(
+ s.find("select distinct s from Simple s where ( ( s.other.count + 3 ) = (15*2)/2 and s.count = 69) or ( ( s.other.count + 2 ) / 7 ) = 2").size()==1
+ );
+ assertTrue(
+ s.find("select s from Simple s where ( ( s.other.count + 3 ) = (15*2)/2 and s.count = 69) or ( ( s.other.count + 2 ) / 7 ) = 2 order by s.other.count").size()==1
+ );
+ Simple min = new Simple();
+ min.setCount(-1);
+ s.save(min, new Long(30) );
+ if ( ! (getDialect() instanceof MySQLDialect) && ! (getDialect() instanceof HSQLDialect) ) { //My SQL has no subqueries
+ assertTrue(
+ s.find("from Simple s where s.count > ( select min(sim.count) from Simple sim )").size()==2
+ );
+ t.commit();
+ t = s.beginTransaction();
+ assertTrue(
+ s.find("from Simple s where s = some( select sim from Simple sim where sim.count>=0 ) and s.count >= 0").size()==2
+ );
+ assertTrue(
+ s.find("from Simple s where s = some( select sim from Simple sim where sim.other.count=s.other.count ) and s.other.count > 0").size()==1
+ );
+ }
+
+ Iterator iter = s.iterate("select sum(s.count) from Simple s group by s.count having sum(s.count) > 10");
+ assertTrue( iter.hasNext() );
+ assertEquals( new Long(12), iter.next() );
+ assertTrue( !iter.hasNext() );
+ if ( ! (getDialect() instanceof MySQLDialect) ) {
+ iter = s.iterate("select s.count from Simple s group by s.count having s.count = 12");
+ assertTrue( iter.hasNext() );
+ }
+
+ s.iterate("select s.id, s.count, count(t), max(t.date) from Simple s, Simple t where s.count = t.count group by s.id, s.count order by s.count");
+
+ Query q = s.createQuery("from Simple s");
+ q.setMaxResults(10);
+ assertTrue( q.list().size()==3 );
+ q = s.createQuery("from Simple s");
+ q.setMaxResults(1);
+ assertTrue( q.list().size()==1 );
+ q = s.createQuery("from Simple s");
+ assertTrue( q.list().size()==3 );
+ q = s.createQuery("from Simple s where s.name = ?");
+ q.setString(0, "Simple 1");
+ assertTrue( q.list().size()==1 );
+ q = s.createQuery("from Simple s where s.name = ? and upper(s.name) = ?");
+ q.setString(1, "SIMPLE 1");
+ q.setString(0, "Simple 1");
+ q.setFirstResult(0);
+ assertTrue( q.iterate().hasNext() );
+ q = s.createQuery("from Simple s where s.name = :foo and upper(s.name) = :bar or s.count=:count or s.count=:count + 1");
+ q.setParameter("bar", "SIMPLE 1");
+ q.setString("foo", "Simple 1");
+ q.setInteger("count", 69);
+ q.setFirstResult(0);
+ assertTrue( q.iterate().hasNext() );
+ q = s.createQuery("select s.id from Simple s");
+ q.setFirstResult(1);
+ q.setMaxResults(2);
+ iter = q.iterate();
+ int i=0;
+ while ( iter.hasNext() ) {
+ assertTrue( iter.next() instanceof Long );
+ i++;
+ }
+ assertTrue(i==2);
+ q = s.createQuery("select all s, s.other from Simple s where s = :s");
+ q.setParameter("s", simple);
+ assertTrue( q.list().size()==1 );
+
+
+ q = s.createQuery("from Simple s where s.name in (:name_list) and s.count > :count");
+ HashSet set = new HashSet();
+ set.add("Simple 1"); set.add("foo");
+ q.setParameterList( "name_list", set );
+ q.setParameter("count", new Integer(-1) );
+ assertTrue( q.list().size()==1 );
+
+ ScrollableResults sr = s.createQuery("from Simple s").scroll();
+ sr.next();
+ sr.get(0);
+ sr.close();
+
+ s.delete(other);
+ s.delete(simple);
+ s.delete(min);
+ t.commit();
+ s.close();
+
+ }
+
+ public void testBlobClob() throws Exception {
+
+ Session s = openSession();
+ Blobber b = new Blobber();
+ b.setBlob( Hibernate.createBlob( "foo/bar/baz".getBytes() ) );
+ b.setClob( Hibernate.createClob("foo/bar/baz") );
+ s.save(b);
+ //s.refresh(b);
+ //assertTrue( b.getClob() instanceof ClobImpl );
+ s.flush();
+ s.refresh(b);
+ //b.getBlob().setBytes( 2, "abc".getBytes() );
+ log.debug("levinson: just bfore b.getClob()");
+ b.getClob().getSubString(2, 3);
+ //b.getClob().setString(2, "abc");
+ s.flush();
+ s.connection().commit();
+ s.close();
+
+ s = openSession();
+ b = (Blobber) s.load( Blobber.class, new Integer( b.getId() ) );
+ Blobber b2 = new Blobber();
+ s.save(b2);
+ b2.setBlob( b.getBlob() );
+ b.setBlob(null);
+ //assertTrue( b.getClob().getSubString(1, 3).equals("fab") );
+ b.getClob().getSubString(1, 6);
+ //b.getClob().setString(1, "qwerty");
+ s.flush();
+ s.connection().commit();
+ s.close();
+
+ s = openSession();
+ b = (Blobber) s.load( Blobber.class, new Integer( b.getId() ) );
+ b.setClob( Hibernate.createClob("xcvfxvc xcvbx cvbx cvbx cvbxcvbxcvbxcvb") );
+ s.flush();
+ s.connection().commit();
+ s.close();
+
+ s = openSession();
+ b = (Blobber) s.load( Blobber.class, new Integer( b.getId() ) );
+ assertTrue( b.getClob().getSubString(1, 7).equals("xcvfxvc") );
+ //b.getClob().setString(5, "1234567890");
+ s.flush();
+ s.connection().commit();
+ s.close();
+
+
+ /*InputStream is = getClass().getClassLoader().getResourceAsStream("jdbc20.pdf");
+ s = sessionsopenSession();
+ b = (Blobber) s.load( Blobber.class, new Integer( b.getId() ) );
+ System.out.println( is.available() );
+ int size = is.available();
+ b.setBlob( Hibernate.createBlob( is, is.available() ) );
+ s.flush();
+ s.connection().commit();
+ ResultSet rs = s.connection().createStatement().executeQuery("select datalength(blob_) from blobber where id=" + b.getId() );
+ rs.next();
+ assertTrue( size==rs.getInt(1) );
+ rs.close();
+ s.close();
+
+ s = sessionsopenSession();
+ b = (Blobber) s.load( Blobber.class, new Integer( b.getId() ) );
+ File f = new File("C:/foo.pdf");
+ f.createNewFile();
+ FileOutputStream fos = new FileOutputStream(f);
+ Blob blob = b.getBlob();
+ byte[] bytes = blob.getBytes( 1, (int) blob.length() );
+ System.out.println( bytes.length );
+ fos.write(bytes);
+ fos.flush();
+ fos.close();
+ s.close();*/
+
+ }
+
+ public void testSqlFunctionAsAlias() throws Exception {
+ String functionName = locateAppropriateDialectFunctionNameForAliasTest();
+ if (functionName == null) {
+ log.info("Dialect does not list any no-arg functions");
+ return;
+ }
+
+ log.info("Using function named [" + functionName + "] for 'function as alias' test");
+ String query = "select " + functionName + " from Simple as " + functionName + " where " + functionName + ".id = 10";
+
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Simple simple = new Simple();
+ simple.setName("Simple 1");
+ s.save( simple, new Long(10) );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ List result = s.find(query);
+ assertTrue( result.size() == 1 );
+ assertTrue(result.get(0) instanceof Simple);
+ s.delete( result.get(0) );
+ t.commit();
+ s.close();
+ }
+
+ private String locateAppropriateDialectFunctionNameForAliasTest() {
+ for (Iterator itr = getDialect().getFunctions().entrySet().iterator(); itr.hasNext(); ) {
+ final Map.Entry entry = (Map.Entry) itr.next();
+ final SQLFunction function = (SQLFunction) entry.getValue();
+ if ( !function.hasArguments() && !function.hasParenthesesIfNoArguments() ) {
+ return (String) entry.getKey();
+ }
+ }
+ return null;
+ }
+
+ public void testCachedQueryOnInsert() throws Exception {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Simple simple = new Simple();
+ simple.setName("Simple 1");
+ s.save( simple, new Long(10) );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ Query q = s.createQuery("from Simple s");
+ List list = q.setCacheable(true).list();
+ assertTrue( list.size()==1 );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ q = s.createQuery("from Simple s");
+ list = q.setCacheable(true).list();
+ assertTrue( list.size()==1 );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ Simple simple2 = new Simple();
+ simple2.setCount(133);
+ s.save( simple2, new Long(12) );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ q = s.createQuery("from Simple s");
+ list = q.setCacheable(true).list();
+ assertTrue( list.size()==2 );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ q = s.createQuery("from Simple s");
+ list = q.setCacheable(true).list();
+ assertTrue( list.size()==2 );
+ Iterator i = list.iterator();
+ while ( i.hasNext() ) s.delete( i.next() );
+ t.commit();
+ s.close();
+
+ }
+
+ public void testInterSystemsFunctions() throws Exception {
+ Calendar cal = new GregorianCalendar();
+ cal.set(1977,6,3,0,0,0);
+ java.sql.Timestamp testvalue = new java.sql.Timestamp(cal.getTimeInMillis());
+ testvalue.setNanos(0);
+ Calendar cal3 = new GregorianCalendar();
+ cal3.set(1976,2,3,0,0,0);
+ java.sql.Timestamp testvalue3 = new java.sql.Timestamp(cal3.getTimeInMillis());
+ testvalue3.setNanos(0);
+
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ try {
+ Statement stmt = s.connection().createStatement();
+ stmt.executeUpdate("DROP FUNCTION spLock FROM TestInterSystemsFunctionsClass");
+ t.commit();
+ }
+ catch (Exception ex) {
+ System.out.println("as we expected stored procedure sp does not exist when we drop it");
+
+ }
+ t = s.beginTransaction();
+ Statement stmt = s.connection().createStatement();
+ String create_function = "CREATE FUNCTION SQLUser.TestInterSystemsFunctionsClass_spLock\n" +
+ " ( INOUT pHandle %SQLProcContext, \n" +
+ " ROWID INTEGER \n" +
+ " )\n" +
+ " FOR User.TestInterSystemsFunctionsClass " +
+ " PROCEDURE\n" +
+ " RETURNS INTEGER\n" +
+ " LANGUAGE OBJECTSCRIPT\n" +
+ " {\n" +
+ " q 0\n" +
+ " }";
+ stmt.executeUpdate(create_function);
+ t.commit();
+ t = s.beginTransaction();
+
+ TestInterSystemsFunctionsClass object = new TestInterSystemsFunctionsClass();
+ object.setDateText("1977-07-03");
+ object.setDate1(testvalue);
+ object.setDate3(testvalue3);
+ s.save( object, new Long(10));
+ t.commit();
+ s.close();
+ s = openSession();
+ s.clear();
+ t = s.beginTransaction();
+ TestInterSystemsFunctionsClass test = (TestInterSystemsFunctionsClass) s.get(TestInterSystemsFunctionsClass.class, new Long(10));
+ assertTrue( test.getDate1().equals(testvalue));
+ test = (TestInterSystemsFunctionsClass) s.get(TestInterSystemsFunctionsClass.class, new Long(10), LockMode.UPGRADE);
+ assertTrue( test.getDate1().equals(testvalue));
+ Date value = (Date) s.find("select nvl(o.date,o.dateText) from TestInterSystemsFunctionsClass as o" ).get(0);
+ assertTrue( value.equals(testvalue));
+ Object nv = s.find("select nullif(o.dateText,o.dateText) from TestInterSystemsFunctionsClass as o" ).get(0);
+ assertTrue( nv == null);
+ String dateText = (String) s.find("select nvl(o.dateText,o.date) from TestInterSystemsFunctionsClass as o" ).get(0);
+ assertTrue( dateText.equals("1977-07-03"));
+ value = (Date) s.find("select ifnull(o.date,o.date1) from TestInterSystemsFunctionsClass as o" ).get(0);
+ assertTrue( value.equals(testvalue));
+ value = (Date) s.find("select ifnull(o.date3,o.date,o.date1) from TestInterSystemsFunctionsClass as o" ).get(0);
+ assertTrue( value.equals(testvalue));
+ Integer pos = (Integer) s.find("select position('07', o.dateText) from TestInterSystemsFunctionsClass as o" ).get(0);
+ assertTrue(pos.intValue() == 6);
+ String st = (String) s.find("select convert(o.date1, SQL_TIME) from TestInterSystemsFunctionsClass as o" ).get(0);
+ assertTrue( st.equals("00:00:00"));
+ java.sql.Time tm = (java.sql.Time) s.find("select cast(o.date1, time) from TestInterSystemsFunctionsClass as o" ).get(0);
+ assertTrue( tm.toString().equals("00:00:00"));
+ Double diff = (Double)s.find("select timestampdiff(SQL_TSI_FRAC_SECOND, o.date3, o.date1) from TestInterSystemsFunctionsClass as o" ).get(0);
+ assertTrue(diff.doubleValue() != 0.0);
+ diff = (Double)s.find("select timestampdiff(SQL_TSI_MONTH, o.date3, o.date1) from TestInterSystemsFunctionsClass as o" ).get(0);
+ assertTrue(diff.doubleValue() == 16.0);
+ diff = (Double)s.find("select timestampdiff(SQL_TSI_WEEK, o.date3, o.date1) from TestInterSystemsFunctionsClass as o" ).get(0);
+ assertTrue(diff.doubleValue() >= 16*4);
+ diff = (Double)s.find("select timestampdiff(SQL_TSI_YEAR, o.date3, o.date1) from TestInterSystemsFunctionsClass as o" ).get(0);
+ assertTrue(diff.doubleValue() == 1.0);
+
+ t.commit();
+ s.close();
+
+
+ }
+
+}
Copied: trunk/Hibernate3/test/org/hibernate/test/dialect/functional/cache/TestInterSystemsFunctionsClass.hbm.xml (from rev 11075, trunk/Hibernate3/test/org/hibernate/test/dialect/cache/TestInterSystemsFunctionsClass.hbm.xml)
===================================================================
--- trunk/Hibernate3/test/org/hibernate/test/dialect/functional/cache/TestInterSystemsFunctionsClass.hbm.xml (rev 0)
+++ trunk/Hibernate3/test/org/hibernate/test/dialect/functional/cache/TestInterSystemsFunctionsClass.hbm.xml 2007-01-23 16:29:18 UTC (rev 11080)
@@ -0,0 +1,18 @@
+<?xml version="1.0"?>
+<!DOCTYPE hibernate-mapping PUBLIC
+ "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+ "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
+
+<hibernate-mapping package="org.hibernate.test.dialect.functional.cache" >
+
+ <class name="TestInterSystemsFunctionsClass" table="SQLUser.TestInterSystemsFunctionsClass">
+ <id type="long" column="id_">
+ <generator class="assigned"/>
+ </id>
+ <property name="date" column="date_"/>
+ <property name="date1" column="date1_"/>
+ <property name="date3" column="date3_"/>
+ <property name="dateText" column="dateText_"/>
+ </class>
+
+</hibernate-mapping>
Copied: trunk/Hibernate3/test/org/hibernate/test/dialect/functional/cache/TestInterSystemsFunctionsClass.java (from rev 11075, trunk/Hibernate3/test/org/hibernate/test/dialect/cache/TestInterSystemsFunctionsClass.java)
===================================================================
--- trunk/Hibernate3/test/org/hibernate/test/dialect/functional/cache/TestInterSystemsFunctionsClass.java (rev 0)
+++ trunk/Hibernate3/test/org/hibernate/test/dialect/functional/cache/TestInterSystemsFunctionsClass.java 2007-01-23 16:29:18 UTC (rev 11080)
@@ -0,0 +1,51 @@
+package org.hibernate.test.dialect.functional.cache;
+
+import java.util.Date;
+
+/**
+ * Entity for testing function support of InterSystems' CacheSQL...
+ *
+ * @author Jonathan Levinson
+ */
+public class TestInterSystemsFunctionsClass {
+ private java.util.Date date3;
+ private java.util.Date date1;
+ private java.util.Date date;
+ private String dateText;
+
+ public Date getDate() {
+ return date;
+ }
+
+ public void setDate(Date date) {
+ this.date = date;
+ }
+
+
+ public String getDateText() {
+ return dateText;
+ }
+
+ public void setDateText(String dateText) {
+ this.dateText = dateText;
+ }
+
+
+ public Date getDate1() {
+ return date1;
+ }
+
+ public void setDate1(Date date1) {
+ this.date1 = date1;
+ }
+
+
+ public Date getDate3() {
+ return date3;
+ }
+
+ public void setDate3(Date date3) {
+ this.date3 = date3;
+ }
+
+}
Added: trunk/Hibernate3/test/org/hibernate/test/dialect/unit/DialectUnitTestsSuite.java
===================================================================
--- trunk/Hibernate3/test/org/hibernate/test/dialect/unit/DialectUnitTestsSuite.java (rev 0)
+++ trunk/Hibernate3/test/org/hibernate/test/dialect/unit/DialectUnitTestsSuite.java 2007-01-23 16:29:18 UTC (rev 11080)
@@ -0,0 +1,20 @@
+package org.hibernate.test.dialect.unit;
+
+import junit.framework.TestSuite;
+
+import org.hibernate.test.dialect.unit.lockhint.SybaseLockHintsTest;
+import org.hibernate.test.dialect.unit.lockhint.SQLServerLockHintsTest;
+
+/**
+ * Suite of all unit tests of the Dialect(s).
+ *
+ * @author Steve Ebersole
+ */
+public class DialectUnitTestsSuite {
+ public static TestSuite suite() {
+ TestSuite suite = new TestSuite( "Dialect unit-tests" );
+ suite.addTest( SybaseLockHintsTest.suite() );
+ suite.addTest( SQLServerLockHintsTest.suite() );
+ return suite;
+ }
+}
Added: trunk/Hibernate3/test/org/hibernate/test/dialect/unit/lockhint/AbstractLockHintTest.java
===================================================================
--- trunk/Hibernate3/test/org/hibernate/test/dialect/unit/lockhint/AbstractLockHintTest.java (rev 0)
+++ trunk/Hibernate3/test/org/hibernate/test/dialect/unit/lockhint/AbstractLockHintTest.java 2007-01-23 16:29:18 UTC (rev 11080)
@@ -0,0 +1,64 @@
+package org.hibernate.test.dialect.unit.lockhint;
+
+import java.util.HashMap;
+import java.util.Collections;
+
+import org.hibernate.junit.UnitTestCase;
+import org.hibernate.dialect.Dialect;
+import org.hibernate.util.StringHelper;
+import org.hibernate.LockMode;
+
+/**
+ * {@inheritDoc}
+ *
+ * @author Steve Ebersole
+ */
+public abstract class AbstractLockHintTest extends UnitTestCase {
+ public AbstractLockHintTest(String string) {
+ super( string );
+ }
+
+ private Dialect dialect;
+
+ protected abstract String getLockHintUsed();
+ protected abstract Dialect getDialectUnderTest();
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ this.dialect = getDialectUnderTest();
+ }
+
+ protected void tearDown() throws Exception {
+ this.dialect = null;
+ super.tearDown();
+ }
+
+ public void testBasicLocking() {
+ new SyntaxChecker( "select xyz from ABC $HOLDER$", "a" ).verify();
+ new SyntaxChecker( "select xyz from ABC $HOLDER$ join DEF d", "a" ).verify();
+ new SyntaxChecker( "select xyz from ABC $HOLDER$, DEF d", "a" ).verify();
+ }
+
+ protected class SyntaxChecker {
+ private final String aliasToLock;
+ private final String rawSql;
+ private final String expectedProcessedSql;
+
+ public SyntaxChecker(String template) {
+ this( template, "" );
+ }
+
+ public SyntaxChecker(String template, String aliasToLock) {
+ this.aliasToLock = aliasToLock;
+ rawSql = StringHelper.replace( template, "$HOLDER$", aliasToLock );
+ expectedProcessedSql = StringHelper.replace( template, "$HOLDER$", aliasToLock + " " + getLockHintUsed() );
+ }
+
+ public void verify() {
+ HashMap lockModes = new HashMap();
+ lockModes.put( aliasToLock, LockMode.UPGRADE );
+ String actualProcessedSql = dialect.applyLocksToSql( rawSql, lockModes, Collections.EMPTY_MAP );
+ assertEquals( expectedProcessedSql, actualProcessedSql );
+ }
+ }
+}
Added: trunk/Hibernate3/test/org/hibernate/test/dialect/unit/lockhint/SQLServerLockHintsTest.java
===================================================================
--- trunk/Hibernate3/test/org/hibernate/test/dialect/unit/lockhint/SQLServerLockHintsTest.java (rev 0)
+++ trunk/Hibernate3/test/org/hibernate/test/dialect/unit/lockhint/SQLServerLockHintsTest.java 2007-01-23 16:29:18 UTC (rev 11080)
@@ -0,0 +1,31 @@
+package org.hibernate.test.dialect.unit.lockhint;
+
+import junit.framework.TestSuite;
+
+import org.hibernate.dialect.Dialect;
+import org.hibernate.dialect.SQLServerDialect;
+
+/**
+ * {@inheritDoc}
+ *
+ * @author Steve Ebersole
+ */
+public class SQLServerLockHintsTest extends AbstractLockHintTest {
+ public static final Dialect DIALECT = new SQLServerDialect();
+
+ public SQLServerLockHintsTest(String string) {
+ super( string );
+ }
+
+ protected String getLockHintUsed() {
+ return "with (updlock, rowlock)";
+ }
+
+ protected Dialect getDialectUnderTest() {
+ return DIALECT;
+ }
+
+ public static TestSuite suite() {
+ return new TestSuite( SQLServerLockHintsTest.class );
+ }
+}
Added: trunk/Hibernate3/test/org/hibernate/test/dialect/unit/lockhint/SybaseLockHintsTest.java
===================================================================
--- trunk/Hibernate3/test/org/hibernate/test/dialect/unit/lockhint/SybaseLockHintsTest.java (rev 0)
+++ trunk/Hibernate3/test/org/hibernate/test/dialect/unit/lockhint/SybaseLockHintsTest.java 2007-01-23 16:29:18 UTC (rev 11080)
@@ -0,0 +1,31 @@
+package org.hibernate.test.dialect.unit.lockhint;
+
+import junit.framework.TestSuite;
+
+import org.hibernate.dialect.Dialect;
+import org.hibernate.dialect.SybaseDialect;
+
+/**
+ * {@inheritDoc}
+ *
+ * @author Steve Ebersole
+ */
+public class SybaseLockHintsTest extends AbstractLockHintTest {
+ public static final Dialect DIALECT = new SybaseDialect();
+
+ public SybaseLockHintsTest(String string) {
+ super( string );
+ }
+
+ protected String getLockHintUsed() {
+ return "holdlock";
+ }
+
+ protected Dialect getDialectUnderTest() {
+ return DIALECT;
+ }
+
+ public static TestSuite suite() {
+ return new TestSuite( SybaseLockHintsTest.class );
+ }
+}
17 years, 12 months
Hibernate SVN: r11079 - branches/Branch_3_2/Hibernate3/src/org/hibernate/engine.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2007-01-23 08:54:45 -0500 (Tue, 23 Jan 2007)
New Revision: 11079
Modified:
branches/Branch_3_2/Hibernate3/src/org/hibernate/engine/StatefulPersistenceContext.java
Log:
HHH-2112 : persistence-context cached db snapshot;
javadocs
Modified: branches/Branch_3_2/Hibernate3/src/org/hibernate/engine/StatefulPersistenceContext.java
===================================================================
--- branches/Branch_3_2/Hibernate3/src/org/hibernate/engine/StatefulPersistenceContext.java 2007-01-23 13:54:33 UTC (rev 11078)
+++ branches/Branch_3_2/Hibernate3/src/org/hibernate/engine/StatefulPersistenceContext.java 2007-01-23 13:54:45 UTC (rev 11079)
@@ -24,6 +24,7 @@
import org.hibernate.NonUniqueObjectException;
import org.hibernate.PersistentObjectException;
import org.hibernate.TransientObjectException;
+import org.hibernate.pretty.MessageHelper;
import org.hibernate.collection.PersistentCollection;
import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.persister.entity.EntityPersister;
@@ -272,9 +273,23 @@
}
}
+ /**
+ * Retrieve the cached database snapshot for the requested entity key.
+ * <p/>
+ * This differs from {@link #getDatabaseSnapshot} is two important respects:<ol>
+ * <li>no snapshot is obtained from the database if not already cached</li>
+ * <li>an entry of {@link #NO_ROW} here is interpretet as an exception</li>
+ * </ol>
+ * @param key The entity key for which to retrieve the cached snapshot
+ * @return The cached snapshot
+ * @throws IllegalStateException if the cached snapshot was == {@link #NO_ROW}.
+ */
public Object[] getCachedDatabaseSnapshot(EntityKey key) {
- //TODO: assertion failure if NO_ROW
- return (Object[]) entitySnapshotsByKey.get(key);
+ Object snapshot = entitySnapshotsByKey.get( key );
+ if ( snapshot == NO_ROW ) {
+ throw new IllegalStateException( "persistence context reported no row snapshot for " + MessageHelper.infoString( key.getEntityName(), key.getIdentifier() ) );
+ }
+ return ( Object[] ) snapshot;
}
/*public void removeDatabaseSnapshot(EntityKey key) {
@@ -482,13 +497,19 @@
/**
* Associate a proxy that was instantiated by another session with this session
+ *
+ * @param li The proxy initializer.
+ * @param proxy The proxy to reassociate.
*/
- private void reassociateProxy(LazyInitializer li, HibernateProxy proxy) throws HibernateException {
- if ( li.getSession() != this ) {
+ private void reassociateProxy(LazyInitializer li, HibernateProxy proxy) {
+ if ( li.getSession() != this.getSession() ) {
EntityPersister persister = session.getFactory().getEntityPersister( li.getEntityName() );
EntityKey key = new EntityKey( li.getIdentifier(), persister, session.getEntityMode() );
- if ( !proxiesByKey.containsKey(key) ) proxiesByKey.put(key, proxy); // any earlier proxy takes precedence
- proxy.getHibernateLazyInitializer().setSession(session);
+ // any earlier proxy takes precedence
+ if ( !proxiesByKey.containsKey( key ) ) {
+ proxiesByKey.put( key, proxy );
+ }
+ proxy.getHibernateLazyInitializer().setSession( session );
}
}
@@ -671,17 +692,23 @@
}
/**
- * Add an collection to the cache, with a given collection entry
+ * Add an collection to the cache, with a given collection entry.
+ *
+ * @param coll The collection for which we are adding an entry.
+ * @param entry The entry representing the collection.
+ * @param key The key of the collection's entry.
*/
private void addCollection(PersistentCollection coll, CollectionEntry entry, Serializable key) {
- collectionEntries.put(coll, entry);
+ collectionEntries.put( coll, entry );
CollectionKey collectionKey = new CollectionKey( entry.getLoadedPersister(), key, session.getEntityMode() );
- PersistentCollection old = (PersistentCollection) collectionsByKey.put(collectionKey, coll);
+ PersistentCollection old = ( PersistentCollection ) collectionsByKey.put( collectionKey, coll );
if ( old != null ) {
- if (old==coll) throw new AssertionFailure("bug adding collection twice");
+ if ( old == coll ) {
+ throw new AssertionFailure("bug adding collection twice");
+ }
// or should it actually throw an exception?
- old.unsetSession(session);
- collectionEntries.remove(old);
+ old.unsetSession( session );
+ collectionEntries.remove( old );
// watch out for a case where old is still referenced
// somewhere in the object graph! (which is a user error)
}
@@ -689,11 +716,13 @@
/**
* Add a collection to the cache, creating a new collection entry for it
+ *
+ * @param collection The collection for which we are adding an entry.
+ * @param persister The collection persister
*/
- private void addCollection(PersistentCollection collection, CollectionPersister persister)
- throws HibernateException {
- CollectionEntry ce = new CollectionEntry(persister, collection);
- collectionEntries.put(collection, ce);
+ private void addCollection(PersistentCollection collection, CollectionPersister persister) {
+ CollectionEntry ce = new CollectionEntry( persister, collection );
+ collectionEntries.put( collection, ce );
}
/**
@@ -1134,7 +1163,7 @@
* persistence context.
*
* @param oos The stream to which the persistence context should get written
- * @throws IOException
+ * @throws IOException serialization errors.
*/
public void serialize(ObjectOutputStream oos) throws IOException {
log.trace( "serializing persistent-context" );
17 years, 12 months
Hibernate SVN: r11078 - trunk/Hibernate3/src/org/hibernate/engine.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2007-01-23 08:54:33 -0500 (Tue, 23 Jan 2007)
New Revision: 11078
Modified:
trunk/Hibernate3/src/org/hibernate/engine/StatefulPersistenceContext.java
Log:
HHH-2112 : persistence-context cached db snapshot;
javadocs
Modified: trunk/Hibernate3/src/org/hibernate/engine/StatefulPersistenceContext.java
===================================================================
--- trunk/Hibernate3/src/org/hibernate/engine/StatefulPersistenceContext.java 2007-01-23 12:54:42 UTC (rev 11077)
+++ trunk/Hibernate3/src/org/hibernate/engine/StatefulPersistenceContext.java 2007-01-23 13:54:33 UTC (rev 11078)
@@ -24,6 +24,7 @@
import org.hibernate.NonUniqueObjectException;
import org.hibernate.PersistentObjectException;
import org.hibernate.TransientObjectException;
+import org.hibernate.pretty.MessageHelper;
import org.hibernate.collection.PersistentCollection;
import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.persister.entity.EntityPersister;
@@ -272,9 +273,23 @@
}
}
+ /**
+ * Retrieve the cached database snapshot for the requested entity key.
+ * <p/>
+ * This differs from {@link #getDatabaseSnapshot} is two important respects:<ol>
+ * <li>no snapshot is obtained from the database if not already cached</li>
+ * <li>an entry of {@link #NO_ROW} here is interpretet as an exception</li>
+ * </ol>
+ * @param key The entity key for which to retrieve the cached snapshot
+ * @return The cached snapshot
+ * @throws IllegalStateException if the cached snapshot was == {@link #NO_ROW}.
+ */
public Object[] getCachedDatabaseSnapshot(EntityKey key) {
- //TODO: assertion failure if NO_ROW
- return (Object[]) entitySnapshotsByKey.get(key);
+ Object snapshot = entitySnapshotsByKey.get( key );
+ if ( snapshot == NO_ROW ) {
+ throw new IllegalStateException( "persistence context reported no row snapshot for " + MessageHelper.infoString( key.getEntityName(), key.getIdentifier() ) );
+ }
+ return ( Object[] ) snapshot;
}
/*public void removeDatabaseSnapshot(EntityKey key) {
@@ -482,13 +497,19 @@
/**
* Associate a proxy that was instantiated by another session with this session
+ *
+ * @param li The proxy initializer.
+ * @param proxy The proxy to reassociate.
*/
- private void reassociateProxy(LazyInitializer li, HibernateProxy proxy) throws HibernateException {
- if ( li.getSession() != this ) {
+ private void reassociateProxy(LazyInitializer li, HibernateProxy proxy) {
+ if ( li.getSession() != this.getSession() ) {
EntityPersister persister = session.getFactory().getEntityPersister( li.getEntityName() );
EntityKey key = new EntityKey( li.getIdentifier(), persister, session.getEntityMode() );
- if ( !proxiesByKey.containsKey(key) ) proxiesByKey.put(key, proxy); // any earlier proxy takes precedence
- proxy.getHibernateLazyInitializer().setSession(session);
+ // any earlier proxy takes precedence
+ if ( !proxiesByKey.containsKey( key ) ) {
+ proxiesByKey.put( key, proxy );
+ }
+ proxy.getHibernateLazyInitializer().setSession( session );
}
}
@@ -669,19 +690,25 @@
throws HibernateException {
addCollection(collection, persister);
}
-
+
/**
- * Add an collection to the cache, with a given collection entry
+ * Add an collection to the cache, with a given collection entry.
+ *
+ * @param coll The collection for which we are adding an entry.
+ * @param entry The entry representing the collection.
+ * @param key The key of the collection's entry.
*/
private void addCollection(PersistentCollection coll, CollectionEntry entry, Serializable key) {
- collectionEntries.put(coll, entry);
+ collectionEntries.put( coll, entry );
CollectionKey collectionKey = new CollectionKey( entry.getLoadedPersister(), key, session.getEntityMode() );
- PersistentCollection old = (PersistentCollection) collectionsByKey.put(collectionKey, coll);
+ PersistentCollection old = ( PersistentCollection ) collectionsByKey.put( collectionKey, coll );
if ( old != null ) {
- if (old==coll) throw new AssertionFailure("bug adding collection twice");
+ if ( old == coll ) {
+ throw new AssertionFailure("bug adding collection twice");
+ }
// or should it actually throw an exception?
- old.unsetSession(session);
- collectionEntries.remove(old);
+ old.unsetSession( session );
+ collectionEntries.remove( old );
// watch out for a case where old is still referenced
// somewhere in the object graph! (which is a user error)
}
@@ -689,11 +716,13 @@
/**
* Add a collection to the cache, creating a new collection entry for it
+ *
+ * @param collection The collection for which we are adding an entry.
+ * @param persister The collection persister
*/
- private void addCollection(PersistentCollection collection, CollectionPersister persister)
- throws HibernateException {
- CollectionEntry ce = new CollectionEntry(persister, collection);
- collectionEntries.put(collection, ce);
+ private void addCollection(PersistentCollection collection, CollectionPersister persister) {
+ CollectionEntry ce = new CollectionEntry( persister, collection );
+ collectionEntries.put( collection, ce );
}
/**
@@ -1134,7 +1163,7 @@
* persistence context.
*
* @param oos The stream to which the persistence context should get written
- * @throws IOException
+ * @throws IOException serialization errors.
*/
public void serialize(ObjectOutputStream oos) throws IOException {
log.trace( "serializing persistent-context" );
17 years, 12 months
Hibernate SVN: r11077 - in branches/Branch_3_2/Hibernate3/test/org/hibernate/test: keymanytoone and 3 other directories.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2007-01-23 07:54:42 -0500 (Tue, 23 Jan 2007)
New Revision: 11077
Added:
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/KeyManyToOneSuite.java
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/Customer.java
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/EagerKeyManyToOneTest.java
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/EagerMapping.hbm.xml
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/LazyKeyManyToOneTest.java
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/LazyMapping.hbm.xml
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/Order.java
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/embedded/
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/embedded/Customer.java
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/embedded/KeyManyToOneTest.java
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/embedded/Mapping.hbm.xml
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/embedded/Order.java
Removed:
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/Card.java
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/CardField.java
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/Key.java
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/KeyManyToOneTestCase.java
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/PrimaryKey.java
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/card.hbm.xml
Modified:
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/AllTests.java
Log:
HHH-2277 : key-many-to-one (bidir + eager) : tests
Modified: branches/Branch_3_2/Hibernate3/test/org/hibernate/test/AllTests.java
===================================================================
--- branches/Branch_3_2/Hibernate3/test/org/hibernate/test/AllTests.java 2007-01-23 12:54:10 UTC (rev 11076)
+++ branches/Branch_3_2/Hibernate3/test/org/hibernate/test/AllTests.java 2007-01-23 12:54:42 UTC (rev 11077)
@@ -58,6 +58,7 @@
import org.hibernate.test.joinedsubclass.JoinedSubclassTest;
import org.hibernate.test.joinfetch.JoinFetchTest;
import org.hibernate.test.jpa.JPAComplianceSuite;
+import org.hibernate.test.keymanytoone.KeyManyToOneSuite;
import org.hibernate.test.lazycache.InstrumentCacheTest;
import org.hibernate.test.lazycache.InstrumentCacheTest2;
import org.hibernate.test.lazyonetoone.LazyOneToOneTest;
@@ -66,7 +67,6 @@
import org.hibernate.test.legacy.CacheTest;
import org.hibernate.test.legacy.ComponentNotNullTest;
import org.hibernate.test.legacy.ConfigurationPerformanceTest;
-import org.hibernate.test.legacy.CustomSQLTest;
import org.hibernate.test.legacy.FooBarTest;
import org.hibernate.test.legacy.FumTest;
import org.hibernate.test.legacy.IJ2Test;
@@ -122,12 +122,12 @@
import org.hibernate.test.unconstrained.UnconstrainedTest;
import org.hibernate.test.unidir.BackrefTest;
import org.hibernate.test.unionsubclass.UnionSubclassTest;
+import org.hibernate.test.usercollection.UserCollectionTypeTest;
import org.hibernate.test.util.UtilSuite;
import org.hibernate.test.version.VersionTest;
import org.hibernate.test.version.db.DbVersionTest;
import org.hibernate.test.version.sybase.SybaseTimestampVersioningTest;
import org.hibernate.test.where.WhereTest;
-import org.hibernate.test.usercollection.UserCollectionTypeTest;
/**
* @author Gavin King
@@ -276,9 +276,9 @@
suite.addTest( IdentifierPropertyReferencesTest.suite() );
suite.addTest( DeleteTransientEntityTest.suite() );
suite.addTest( UserCollectionTypeTest.suite() );
+ suite.addTest( KeyManyToOneSuite.suite() );
return filter( suite );
- //return suite;
}
/**
Deleted: branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/Card.java
===================================================================
--- branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/Card.java 2007-01-23 12:54:10 UTC (rev 11076)
+++ branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/Card.java 2007-01-23 12:54:42 UTC (rev 11077)
@@ -1,38 +0,0 @@
-//$Id: $
-package org.hibernate.test.keymanytoone;
-
-import java.io.Serializable;
-import java.util.Set;
-import java.util.HashSet;
-
-/**
- * @author Emmanuel Bernard
- */
-public class Card implements Serializable {
- private String id;
-
- private Set fields;
-
- public Card(String id) {
- this();
- this.id = id;
-
- }
-
- Card() {
- fields = new HashSet();
- }
-
- public String getId() {
- return id;
- }
-
- public void setId(String id) {
- this.id = id;
- }
-
- public void addField(Card card, Key key) {
- fields.add(new CardField(card, key));
- }
-}
-
Deleted: branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/CardField.java
===================================================================
--- branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/CardField.java 2007-01-23 12:54:10 UTC (rev 11076)
+++ branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/CardField.java 2007-01-23 12:54:42 UTC (rev 11077)
@@ -1,19 +0,0 @@
-//$Id: $
-package org.hibernate.test.keymanytoone;
-
-import java.io.Serializable;
-
-/**
- * @author Emmanuel Bernard
- */
-public class CardField implements Serializable {
-
- private PrimaryKey primaryKey;
-
- CardField(Card card, Key key) {
- this.primaryKey = new PrimaryKey(card, key);
- }
-
- CardField() {
- }
-}
Deleted: branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/Key.java
===================================================================
--- branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/Key.java 2007-01-23 12:54:10 UTC (rev 11076)
+++ branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/Key.java 2007-01-23 12:54:42 UTC (rev 11077)
@@ -1,18 +0,0 @@
-//$Id: $
-package org.hibernate.test.keymanytoone;
-
-import java.io.Serializable;
-
-/**
- * @author Emmanuel Bernard
- */
-public class Key implements Serializable {
- private String id;
-
- public Key(String id) {
- this.id = id;
- }
-
- Key() {
- }
-}
Added: branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/KeyManyToOneSuite.java
===================================================================
--- branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/KeyManyToOneSuite.java (rev 0)
+++ branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/KeyManyToOneSuite.java 2007-01-23 12:54:42 UTC (rev 11077)
@@ -0,0 +1,23 @@
+package org.hibernate.test.keymanytoone;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+import org.hibernate.test.keymanytoone.bidir.embedded.KeyManyToOneTest;
+import org.hibernate.test.keymanytoone.bidir.component.LazyKeyManyToOneTest;
+import org.hibernate.test.keymanytoone.bidir.component.EagerKeyManyToOneTest;
+
+/**
+ * {@inheritDoc}
+ *
+ * @author Steve Ebersole
+ */
+public class KeyManyToOneSuite {
+ public static Test suite() {
+ TestSuite suite = new TestSuite( "key-many-to-one mappings" );
+ suite.addTest( KeyManyToOneTest.suite() );
+ suite.addTest( LazyKeyManyToOneTest.suite() );
+ suite.addTest( EagerKeyManyToOneTest.suite() );
+ return suite;
+ }
+}
Deleted: branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/KeyManyToOneTestCase.java
===================================================================
--- branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/KeyManyToOneTestCase.java 2007-01-23 12:54:10 UTC (rev 11076)
+++ branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/KeyManyToOneTestCase.java 2007-01-23 12:54:42 UTC (rev 11077)
@@ -1,34 +0,0 @@
-//$Id: $
-package org.hibernate.test.keymanytoone;
-
-import org.hibernate.test.TestCase;
-import org.hibernate.Session;
-import org.hibernate.Transaction;
-
-/**
- * @author Emmanuel Bernard
- */
-public class KeyManyToOneTestCase extends TestCase {
- public void testInfiniteLoop() throws Exception {
- Card card = new Card("cardId");
- Key key = new Key("keyId");
- card.addField(card, key);
- Session s = openSession();
- Transaction tx = s.beginTransaction();
- s.persist( key );
- s.persist( card );
- s.flush();
- s.clear();
- s.get( Card.class, card.getId() );
- tx.rollback();
- }
- public KeyManyToOneTestCase(String name) {
- super( name );
- }
-
- protected String[] getMappings() {
- return new String[] {
- "keymanytoone/card.hbm.xml"
- };
- }
-}
Deleted: branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/PrimaryKey.java
===================================================================
--- branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/PrimaryKey.java 2007-01-23 12:54:10 UTC (rev 11076)
+++ branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/PrimaryKey.java 2007-01-23 12:54:42 UTC (rev 11077)
@@ -1,21 +0,0 @@
-//$Id: $
-package org.hibernate.test.keymanytoone;
-
-import java.io.Serializable;
-
-/**
- * @author Emmanuel Bernard
- */
-public class PrimaryKey implements Serializable {
- private Card card;
-
- private Key key;
-
- public PrimaryKey(Card card, Key key) {
- this.card = card;
- this.key = key;
- }
-
- PrimaryKey() {}
-
-}
Added: branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/Customer.java
===================================================================
--- branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/Customer.java (rev 0)
+++ branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/Customer.java 2007-01-23 12:54:42 UTC (rev 11077)
@@ -0,0 +1,46 @@
+package org.hibernate.test.keymanytoone.bidir.component;
+
+import java.util.Collection;
+import java.util.ArrayList;
+
+/**
+ * {@inheritDoc}
+ *
+ * @author Steve Ebersole
+ */
+public class Customer {
+ private Long id;
+ private String name;
+ private Collection orders = new ArrayList();
+
+ public Customer() {
+ }
+
+ public Customer(String name) {
+ this.name = name;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public Collection getOrders() {
+ return orders;
+ }
+
+ public void setOrders(Collection orders) {
+ this.orders = orders;
+ }
+}
Added: branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/EagerKeyManyToOneTest.java
===================================================================
--- branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/EagerKeyManyToOneTest.java (rev 0)
+++ branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/EagerKeyManyToOneTest.java 2007-01-23 12:54:42 UTC (rev 11077)
@@ -0,0 +1,92 @@
+package org.hibernate.test.keymanytoone.bidir.component;
+
+import junit.framework.Test;
+
+import org.hibernate.Session;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.cfg.Environment;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+import org.hibernate.test.TestCase;
+
+/**
+ * @author Steve Ebersole
+ */
+public class EagerKeyManyToOneTest extends TestCase {
+ public EagerKeyManyToOneTest(String name) {
+ super( name );
+ }
+
+ protected String[] getMappings() {
+ return new String[] { "keymanytoone/bidir/component/EagerMapping.hbm.xml" };
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( EagerKeyManyToOneTest.class );
+ }
+
+ protected void configure(Configuration cfg) {
+ super.configure( cfg );
+ cfg.setProperty( Environment.GENERATE_STATISTICS, "true" );
+ }
+
+ public void testSaveCascadedToKeyManyToOne() {
+ // test cascading a save to an association with a key-many-to-one which refers to a
+ // just saved entity
+ Session s = openSession();
+ s.beginTransaction();
+ Customer cust = new Customer( "Acme, Inc." );
+ Order order = new Order( new Order.Id( cust, 1 ) );
+ cust.getOrders().add( order );
+ s.save( cust );
+ s.flush();
+ assertEquals( 2, sfi().getStatistics().getEntityInsertCount() );
+ s.delete( cust );
+ s.getTransaction().commit();
+ s.close();
+ }
+
+ public void testLoadingStrategies() {
+ Session s = openSession();
+ s.beginTransaction();
+ Customer cust = new Customer( "Acme, Inc." );
+ Order order = new Order( new Order.Id( cust, 1 ) );
+ cust.getOrders().add( order );
+ s.save( cust );
+ s.getTransaction().commit();
+ s.close();
+
+ s = openSession();
+ s.beginTransaction();
+
+// Here is an example of HHH-2277
+// essentially we have a bidirectional association where one side of the
+// association is actually part of a composite PK
+//
+// The way these are mapped causes the problem because both sides
+// are defined as eager which leads to the infinite loop; if only
+// one side is marked as eager, then all is ok...
+// cust = ( Customer ) s.get( Customer.class, cust.getId() );
+// assertEquals( 1, cust.getOrders().size() );
+// s.clear();
+
+ cust = ( Customer ) s.createQuery( "from Customer" ).uniqueResult();
+ assertEquals( 1, cust.getOrders().size() );
+ s.clear();
+
+ cust = ( Customer ) s.createQuery( "from Customer c join fetch c.orders" ).uniqueResult();
+ assertEquals( 1, cust.getOrders().size() );
+ s.clear();
+
+ cust = ( Customer ) s.createQuery( "from Customer c join fetch c.orders as o join fetch o.id.customer" ).uniqueResult();
+ assertEquals( 1, cust.getOrders().size() );
+ s.clear();
+
+ cust = ( Customer ) s.createCriteria( Customer.class ).uniqueResult();
+ assertEquals( 1, cust.getOrders().size() );
+ s.clear();
+
+ s.delete( cust );
+ s.getTransaction().commit();
+ s.close();
+ }
+}
Added: branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/EagerMapping.hbm.xml
===================================================================
--- branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/EagerMapping.hbm.xml (rev 0)
+++ branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/EagerMapping.hbm.xml 2007-01-23 12:54:42 UTC (rev 11077)
@@ -0,0 +1,42 @@
+<?xml version="1.0"?>
+<!DOCTYPE hibernate-mapping PUBLIC
+ "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+ "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
+
+<!--
+ This mapping demonstrates the use of composite ids with the
+ key-many-to-one feature. Essentially a composite id where part
+ of the composition is a foreign-key to another entity.
+
+ Here, specifically, we map the key-many-to-one as a lazy
+ association.
+-->
+
+<hibernate-mapping package="org.hibernate.test.keymanytoone.bidir.component">
+
+ <class name="Customer" table="COMP_LAZY_KM2O_CUST">
+ <id name="id" column="ID" type="long">
+ <generator class="increment" />
+ </id>
+ <property name="name" column="NAME" type="string" />
+ <bag name="orders" inverse="true" cascade="all" lazy="false" fetch="join">
+ <key column="CUST_ID" />
+ <one-to-many class="Order" />
+ </bag>
+ </class>
+
+ <class name="Order" table="COMP_LAZY_KM2O_ORDR">
+ <composite-id name="id" class="Order$Id">
+ <key-many-to-one name="customer" class="Customer" column="CUST_ID" lazy="false"/>
+ <key-property name="number" column="ORDR_NUM" type="long" />
+ </composite-id>
+ <set name="items" table="COMP_LAZY_KM2O_ITEM">
+ <key>
+ <column name="CUST_ID"/>
+ <column name="ORDER_NUM"/>
+ </key>
+ <element type="string" column="ITEM_DESC" />
+ </set>
+ </class>
+
+</hibernate-mapping>
Added: branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/LazyKeyManyToOneTest.java
===================================================================
--- branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/LazyKeyManyToOneTest.java (rev 0)
+++ branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/LazyKeyManyToOneTest.java 2007-01-23 12:54:42 UTC (rev 11077)
@@ -0,0 +1,77 @@
+package org.hibernate.test.keymanytoone.bidir.component;
+
+import junit.framework.Test;
+
+import org.hibernate.test.TestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.cfg.Environment;
+import org.hibernate.Session;
+
+/**
+ * @author Steve Ebersole
+ */
+public class LazyKeyManyToOneTest extends TestCase {
+ public LazyKeyManyToOneTest(String name) {
+ super( name );
+ }
+
+ protected String[] getMappings() {
+ return new String[] { "keymanytoone/bidir/component/LazyMapping.hbm.xml" };
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( LazyKeyManyToOneTest.class );
+ }
+
+ protected void configure(Configuration cfg) {
+ super.configure( cfg );
+ cfg.setProperty( Environment.GENERATE_STATISTICS, "true" );
+ }
+
+ public void testSaveCascadedToKeyManyToOne() {
+ // test cascading a save to an association with a key-many-to-one which refers to a
+ // just saved entity
+ Session s = openSession();
+ s.beginTransaction();
+ Customer cust = new Customer( "Acme, Inc." );
+ Order order = new Order( new Order.Id( cust, 1 ) );
+ cust.getOrders().add( order );
+ s.save( cust );
+ s.flush();
+ assertEquals( 2, sfi().getStatistics().getEntityInsertCount() );
+ s.delete( cust );
+ s.getTransaction().commit();
+ s.close();
+ }
+
+ public void testLoadingStrategies() {
+ Session s = openSession();
+ s.beginTransaction();
+ Customer cust = new Customer( "Acme, Inc." );
+ Order order = new Order( new Order.Id( cust, 1 ) );
+ cust.getOrders().add( order );
+ s.save( cust );
+ s.getTransaction().commit();
+ s.close();
+
+ s = openSession();
+ s.beginTransaction();
+
+ cust = ( Customer ) s.get( Customer.class, cust.getId() );
+ assertEquals( 1, cust.getOrders().size() );
+ s.clear();
+
+ cust = ( Customer ) s.createQuery( "from Customer" ).uniqueResult();
+ assertEquals( 1, cust.getOrders().size() );
+ s.clear();
+
+ cust = ( Customer ) s.createQuery( "from Customer c join fetch c.orders" ).uniqueResult();
+ assertEquals( 1, cust.getOrders().size() );
+ s.clear();
+
+ s.delete( cust );
+ s.getTransaction().commit();
+ s.close();
+ }
+}
Added: branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/LazyMapping.hbm.xml
===================================================================
--- branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/LazyMapping.hbm.xml (rev 0)
+++ branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/LazyMapping.hbm.xml 2007-01-23 12:54:42 UTC (rev 11077)
@@ -0,0 +1,42 @@
+<?xml version="1.0"?>
+<!DOCTYPE hibernate-mapping PUBLIC
+ "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+ "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
+
+<!--
+ This mapping demonstrates the use of composite ids with the
+ key-many-to-one feature. Essentially a composite id where part
+ of the composition is a foreign-key to another entity.
+
+ Here, specifically, we map the key-many-to-one as a lazy
+ association.
+-->
+
+<hibernate-mapping package="org.hibernate.test.keymanytoone.bidir.component">
+
+ <class name="Customer" table="COMP_LAZY_KM2O_CUST">
+ <id name="id" column="ID" type="long">
+ <generator class="increment" />
+ </id>
+ <property name="name" column="NAME" type="string" />
+ <bag name="orders" inverse="true" cascade="all">
+ <key column="CUST_ID" />
+ <one-to-many class="Order" />
+ </bag>
+ </class>
+
+ <class name="Order" table="COMP_LAZY_KM2O_ORDR">
+ <composite-id name="id" class="Order$Id">
+ <key-many-to-one name="customer" class="Customer" column="CUST_ID" lazy="proxy"/>
+ <key-property name="number" column="ORDR_NUM" type="long" />
+ </composite-id>
+ <set name="items" table="COMP_LAZY_KM2O_ITEM">
+ <key>
+ <column name="CUST_ID"/>
+ <column name="ORDER_NUM"/>
+ </key>
+ <element type="string" column="ITEM_DESC" />
+ </set>
+ </class>
+
+</hibernate-mapping>
Added: branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/Order.java
===================================================================
--- branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/Order.java (rev 0)
+++ branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/Order.java 2007-01-23 12:54:42 UTC (rev 11077)
@@ -0,0 +1,86 @@
+package org.hibernate.test.keymanytoone.bidir.component;
+
+import java.io.Serializable;
+import java.util.Set;
+import java.util.HashSet;
+
+/**
+ * {@inheritDoc}
+ *
+ * @author Steve Ebersole
+ */
+public class Order {
+ private Id id;
+ private Set items = new HashSet();
+
+ public Order() {
+ }
+
+ public Order(Id id) {
+ this.id = id;
+ }
+
+ public Id getId() {
+ return id;
+ }
+
+ public void setId(Id id) {
+ this.id = id;
+ }
+
+ public Set getItems() {
+ return items;
+ }
+
+ public void setItems(Set items) {
+ this.items = items;
+ }
+
+ public static class Id implements Serializable {
+ private Customer customer;
+ private long number;
+
+ public Id() {
+ }
+
+ public Id(Customer customer, long number) {
+ this.customer = customer;
+ this.number = number;
+ }
+
+ public Customer getCustomer() {
+ return customer;
+ }
+
+ public void setCustomer(Customer customer) {
+ this.customer = customer;
+ }
+
+ public long getNumber() {
+ return number;
+ }
+
+ public void setNumber(long number) {
+ this.number = number;
+ }
+
+ public boolean equals(Object o) {
+ if ( this == o ) {
+ return true;
+ }
+ if ( o == null || getClass() != o.getClass() ) {
+ return false;
+ }
+
+ Id id = ( Id ) o;
+ return number == id.number && customer.equals( id.customer );
+ }
+
+ public int hashCode() {
+ int result;
+ result = customer.hashCode();
+ result = 31 * result + ( int ) ( number ^ ( number >>> 32 ) );
+ return result;
+ }
+ }
+}
Added: branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/embedded/Customer.java
===================================================================
--- branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/embedded/Customer.java (rev 0)
+++ branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/embedded/Customer.java 2007-01-23 12:54:42 UTC (rev 11077)
@@ -0,0 +1,46 @@
+package org.hibernate.test.keymanytoone.bidir.embedded;
+
+import java.util.Collection;
+import java.util.ArrayList;
+
+/**
+ * {@inheritDoc}
+ *
+ * @author Steve Ebersole
+ */
+public class Customer {
+ private Long id;
+ private String name;
+ private Collection orders = new ArrayList();
+
+ public Customer() {
+ }
+
+ public Customer(String name) {
+ this.name = name;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public Collection getOrders() {
+ return orders;
+ }
+
+ public void setOrders(Collection orders) {
+ this.orders = orders;
+ }
+}
Added: branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/embedded/KeyManyToOneTest.java
===================================================================
--- branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/embedded/KeyManyToOneTest.java (rev 0)
+++ branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/embedded/KeyManyToOneTest.java 2007-01-23 12:54:42 UTC (rev 11077)
@@ -0,0 +1,77 @@
+package org.hibernate.test.keymanytoone.bidir.embedded;
+
+import junit.framework.Test;
+
+import org.hibernate.test.TestCase;
+import org.hibernate.Session;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.cfg.Environment;
+
+/**
+ * @author Steve Ebersole
+ */
+public class KeyManyToOneTest extends TestCase {
+ public KeyManyToOneTest(String name) {
+ super( name );
+ }
+
+ protected String[] getMappings() {
+ return new String[] { "keymanytoone/bidir/embedded/Mapping.hbm.xml" };
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( KeyManyToOneTest.class );
+ }
+
+ protected void configure(Configuration cfg) {
+ super.configure( cfg );
+ cfg.setProperty( Environment.GENERATE_STATISTICS, "true" );
+ }
+
+ public void testSaveCascadedToKeyManyToOne() {
+ // test cascading a save to an association with a key-many-to-one which refers to a
+ // just saved entity
+ Session s = openSession();
+ s.beginTransaction();
+ Customer cust = new Customer( "Acme, Inc." );
+ Order order = new Order( cust, 1 );
+ cust.getOrders().add( order );
+ s.save( cust );
+ s.flush();
+ assertEquals( 2, sfi().getStatistics().getEntityInsertCount() );
+ s.delete( cust );
+ s.getTransaction().commit();
+ s.close();
+ }
+
+ public void testLoadingStrategies() {
+ Session s = openSession();
+ s.beginTransaction();
+ Customer cust = new Customer( "Acme, Inc." );
+ Order order = new Order( cust, 1 );
+ cust.getOrders().add( order );
+ s.save( cust );
+ s.getTransaction().commit();
+ s.close();
+
+ s = openSession();
+ s.beginTransaction();
+
+ cust = ( Customer ) s.get( Customer.class, cust.getId() );
+ assertEquals( 1, cust.getOrders().size() );
+ s.clear();
+
+ cust = ( Customer ) s.createQuery( "from Customer" ).uniqueResult();
+ assertEquals( 1, cust.getOrders().size() );
+ s.clear();
+
+ cust = ( Customer ) s.createQuery( "from Customer c join fetch c.orders" ).uniqueResult();
+ assertEquals( 1, cust.getOrders().size() );
+ s.clear();
+
+ s.delete( cust );
+ s.getTransaction().commit();
+ s.close();
+ }
+}
Added: branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/embedded/Mapping.hbm.xml
===================================================================
--- branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/embedded/Mapping.hbm.xml (rev 0)
+++ branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/embedded/Mapping.hbm.xml 2007-01-23 12:54:42 UTC (rev 11077)
@@ -0,0 +1,39 @@
+<?xml version="1.0"?>
+<!DOCTYPE hibernate-mapping PUBLIC
+ "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+ "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
+
+<!--
+ This mapping demonstrates the use of composite ids with the
+ key-many-to-one feature where the composite-id is an embedded form.
+ Essentially a composite id where part of the composition is a
+ foreign-key to another entity.
+-->
+
+<hibernate-mapping package="org.hibernate.test.keymanytoone.bidir.embedded">
+
+ <class name="Customer" table="EMBD_KM2O_CUST">
+ <id name="id" column="ID" type="long">
+ <generator class="increment" />
+ </id>
+ <property name="name" column="NAME" type="string" />
+ <bag name="orders" inverse="true" cascade="all">
+ <key column="CUST_ID" />
+ <one-to-many class="Order" />
+ </bag>
+ </class>
+
+ <class name="Order" table="EMBD_KM2O_ORDR">
+ <composite-id mapped="false">
+ <key-many-to-one name="customer" class="Customer" column="CUST_ID" lazy="false"/>
+ <key-property name="number" column="ORDR_NUM" type="long" />
+ </composite-id>
+ <set name="items" table="EMBD_KM2O_ITEM">
+ <key>
+ <column name="CUST_ID"/>
+ <column name="ORDER_NUM"/>
+ </key>
+ <element type="string" column="ITEM_DESC" />
+ </set>
+ </class>
+</hibernate-mapping>
\ No newline at end of file
Added: branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/embedded/Order.java
===================================================================
--- branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/embedded/Order.java (rev 0)
+++ branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/embedded/Order.java 2007-01-23 12:54:42 UTC (rev 11077)
@@ -0,0 +1,48 @@
+package org.hibernate.test.keymanytoone.bidir.embedded;
+
+import java.util.Set;
+import java.util.HashSet;
+import java.io.Serializable;
+
+/**
+ * {@inheritDoc}
+ *
+ * @author Steve Ebersole
+ */
+public class Order implements Serializable {
+ private Customer customer;
+ private long number;
+ private Set items = new HashSet();
+
+ public Order() {
+ }
+
+ public Order(Customer customer, long number) {
+ this.customer = customer;
+ this.number = number;
+ }
+
+ public Customer getCustomer() {
+ return customer;
+ }
+
+ public void setCustomer(Customer customer) {
+ this.customer = customer;
+ }
+
+ public long getNumber() {
+ return number;
+ }
+
+ public void setNumber(long number) {
+ this.number = number;
+ }
+
+ public Set getItems() {
+ return items;
+ }
+
+ public void setItems(Set items) {
+ this.items = items;
+ }
+}
Deleted: branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/card.hbm.xml
===================================================================
--- branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/card.hbm.xml 2007-01-23 12:54:10 UTC (rev 11076)
+++ branches/Branch_3_2/Hibernate3/test/org/hibernate/test/keymanytoone/card.hbm.xml 2007-01-23 12:54:42 UTC (rev 11077)
@@ -1,48 +0,0 @@
-<?xml version="1.0"?>
-<!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
-
-<!--
-
- This mapping demonstrates
-
- (1) use of lazy properties - this feature requires buildtime
- bytecode instrumentation; we don't think this is a very
- necessary feature, but provide it for completeleness; if
- Hibernate encounters uninstrumented classes, lazy property
- fetching will be silently disabled, to enable testing
-
- (2) use of a formula to define a "derived property"
-
--->
-
-<hibernate-mapping
- package="org.hibernate.test.keymanytoone"
- default-access="field">
-
- <class name="Card">
- <id name="id"/>
- <set name="fields" cascade="all" fetch="join" lazy="false">
- <key>
- <column name="card_id"/>
- </key>
- <one-to-many class="CardField"/>
- </set>
- </class>
- <class name="Key" table="tbl_key">
- <id name="id"/>
- </class>
- <class name="CardField">
- <composite-id name="primaryKey">
- <key-many-to-one name="card" class="Card" lazy="false">
- <column name="card_id"/>
- </key-many-to-one>
- <key-many-to-one name="key" class="Key" lazy="false">
- <column name="key_id"/>
- </key-many-to-one>
- </composite-id>
- </class>
-
-
-</hibernate-mapping>
17 years, 12 months
Hibernate SVN: r11076 - in trunk/Hibernate3/test/org/hibernate/test: keymanytoone and 3 other directories.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2007-01-23 07:54:10 -0500 (Tue, 23 Jan 2007)
New Revision: 11076
Added:
trunk/Hibernate3/test/org/hibernate/test/keymanytoone/
trunk/Hibernate3/test/org/hibernate/test/keymanytoone/KeyManyToOneSuite.java
trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/
trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/
trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/Customer.java
trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/EagerKeyManyToOneTest.java
trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/EagerMapping.hbm.xml
trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/LazyKeyManyToOneTest.java
trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/LazyMapping.hbm.xml
trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/Order.java
trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/embedded/
trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/embedded/Customer.java
trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/embedded/KeyManyToOneTest.java
trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/embedded/Mapping.hbm.xml
trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/embedded/Order.java
Modified:
trunk/Hibernate3/test/org/hibernate/test/AllTests.java
Log:
HHH-2277 : key-many-to-one (bidir + eager) : tests
Modified: trunk/Hibernate3/test/org/hibernate/test/AllTests.java
===================================================================
--- trunk/Hibernate3/test/org/hibernate/test/AllTests.java 2007-01-22 18:59:20 UTC (rev 11075)
+++ trunk/Hibernate3/test/org/hibernate/test/AllTests.java 2007-01-23 12:54:10 UTC (rev 11076)
@@ -58,6 +58,7 @@
import org.hibernate.test.joinedsubclass.JoinedSubclassTest;
import org.hibernate.test.joinfetch.JoinFetchTest;
import org.hibernate.test.jpa.JPAComplianceSuite;
+import org.hibernate.test.keymanytoone.KeyManyToOneSuite;
import org.hibernate.test.lazycache.InstrumentCacheTest;
import org.hibernate.test.lazycache.InstrumentCacheTest2;
import org.hibernate.test.lazyonetoone.LazyOneToOneTest;
@@ -275,9 +276,9 @@
suite.addTest( IdentifierPropertyReferencesTest.suite() );
suite.addTest( DeleteTransientEntityTest.suite() );
suite.addTest( UserCollectionTypeTest.suite() );
+ suite.addTest( KeyManyToOneSuite.suite() );
return filter( suite );
- //return suite;
}
/**
Added: trunk/Hibernate3/test/org/hibernate/test/keymanytoone/KeyManyToOneSuite.java
===================================================================
--- trunk/Hibernate3/test/org/hibernate/test/keymanytoone/KeyManyToOneSuite.java (rev 0)
+++ trunk/Hibernate3/test/org/hibernate/test/keymanytoone/KeyManyToOneSuite.java 2007-01-23 12:54:10 UTC (rev 11076)
@@ -0,0 +1,23 @@
+package org.hibernate.test.keymanytoone;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+import org.hibernate.test.keymanytoone.bidir.embedded.KeyManyToOneTest;
+import org.hibernate.test.keymanytoone.bidir.component.LazyKeyManyToOneTest;
+import org.hibernate.test.keymanytoone.bidir.component.EagerKeyManyToOneTest;
+
+/**
+ * {@inheritDoc}
+ *
+ * @author Steve Ebersole
+ */
+public class KeyManyToOneSuite {
+ public static Test suite() {
+ TestSuite suite = new TestSuite( "key-many-to-one mappings" );
+ suite.addTest( KeyManyToOneTest.suite() );
+ suite.addTest( LazyKeyManyToOneTest.suite() );
+ suite.addTest( EagerKeyManyToOneTest.suite() );
+ return suite;
+ }
+}
Added: trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/Customer.java
===================================================================
--- trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/Customer.java (rev 0)
+++ trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/Customer.java 2007-01-23 12:54:10 UTC (rev 11076)
@@ -0,0 +1,46 @@
+package org.hibernate.test.keymanytoone.bidir.component;
+
+import java.util.Collection;
+import java.util.ArrayList;
+
+/**
+ * {@inheritDoc}
+ *
+ * @author Steve Ebersole
+ */
+public class Customer {
+ private Long id;
+ private String name;
+ private Collection orders = new ArrayList();
+
+ public Customer() {
+ }
+
+ public Customer(String name) {
+ this.name = name;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public Collection getOrders() {
+ return orders;
+ }
+
+ public void setOrders(Collection orders) {
+ this.orders = orders;
+ }
+}
Added: trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/EagerKeyManyToOneTest.java
===================================================================
--- trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/EagerKeyManyToOneTest.java (rev 0)
+++ trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/EagerKeyManyToOneTest.java 2007-01-23 12:54:10 UTC (rev 11076)
@@ -0,0 +1,92 @@
+package org.hibernate.test.keymanytoone.bidir.component;
+
+import junit.framework.Test;
+
+import org.hibernate.Session;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.cfg.Environment;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+import org.hibernate.test.TestCase;
+
+/**
+ * @author Steve Ebersole
+ */
+public class EagerKeyManyToOneTest extends TestCase {
+ public EagerKeyManyToOneTest(String name) {
+ super( name );
+ }
+
+ protected String[] getMappings() {
+ return new String[] { "keymanytoone/bidir/component/EagerMapping.hbm.xml" };
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( EagerKeyManyToOneTest.class );
+ }
+
+ protected void configure(Configuration cfg) {
+ super.configure( cfg );
+ cfg.setProperty( Environment.GENERATE_STATISTICS, "true" );
+ }
+
+ public void testSaveCascadedToKeyManyToOne() {
+ // test cascading a save to an association with a key-many-to-one which refers to a
+ // just saved entity
+ Session s = openSession();
+ s.beginTransaction();
+ Customer cust = new Customer( "Acme, Inc." );
+ Order order = new Order( new Order.Id( cust, 1 ) );
+ cust.getOrders().add( order );
+ s.save( cust );
+ s.flush();
+ assertEquals( 2, sfi().getStatistics().getEntityInsertCount() );
+ s.delete( cust );
+ s.getTransaction().commit();
+ s.close();
+ }
+
+ public void testLoadingStrategies() {
+ Session s = openSession();
+ s.beginTransaction();
+ Customer cust = new Customer( "Acme, Inc." );
+ Order order = new Order( new Order.Id( cust, 1 ) );
+ cust.getOrders().add( order );
+ s.save( cust );
+ s.getTransaction().commit();
+ s.close();
+
+ s = openSession();
+ s.beginTransaction();
+
+// Here is an example of HHH-2277
+// essentially we have a bidirectional association where one side of the
+// association is actually part of a composite PK
+//
+// The way these are mapped causes the problem because both sides
+// are defined as eager which leads to the infinite loop; if only
+// one side is marked as eager, then all is ok...
+// cust = ( Customer ) s.get( Customer.class, cust.getId() );
+// assertEquals( 1, cust.getOrders().size() );
+// s.clear();
+
+ cust = ( Customer ) s.createQuery( "from Customer" ).uniqueResult();
+ assertEquals( 1, cust.getOrders().size() );
+ s.clear();
+
+ cust = ( Customer ) s.createQuery( "from Customer c join fetch c.orders" ).uniqueResult();
+ assertEquals( 1, cust.getOrders().size() );
+ s.clear();
+
+ cust = ( Customer ) s.createQuery( "from Customer c join fetch c.orders as o join fetch o.id.customer" ).uniqueResult();
+ assertEquals( 1, cust.getOrders().size() );
+ s.clear();
+
+ cust = ( Customer ) s.createCriteria( Customer.class ).uniqueResult();
+ assertEquals( 1, cust.getOrders().size() );
+ s.clear();
+
+ s.delete( cust );
+ s.getTransaction().commit();
+ s.close();
+ }
+}
Added: trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/EagerMapping.hbm.xml
===================================================================
--- trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/EagerMapping.hbm.xml (rev 0)
+++ trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/EagerMapping.hbm.xml 2007-01-23 12:54:10 UTC (rev 11076)
@@ -0,0 +1,42 @@
+<?xml version="1.0"?>
+<!DOCTYPE hibernate-mapping PUBLIC
+ "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+ "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
+
+<!--
+ This mapping demonstrates the use of composite ids with the
+ key-many-to-one feature. Essentially a composite id where part
+ of the composition is a foreign-key to another entity.
+
+ Here, specifically, we map the key-many-to-one as a lazy
+ association.
+-->
+
+<hibernate-mapping package="org.hibernate.test.keymanytoone.bidir.component">
+
+ <class name="Customer" table="COMP_LAZY_KM2O_CUST">
+ <id name="id" column="ID" type="long">
+ <generator class="increment" />
+ </id>
+ <property name="name" column="NAME" type="string" />
+ <bag name="orders" inverse="true" cascade="all" lazy="false" fetch="join">
+ <key column="CUST_ID" />
+ <one-to-many class="Order" />
+ </bag>
+ </class>
+
+ <class name="Order" table="COMP_LAZY_KM2O_ORDR">
+ <composite-id name="id" class="Order$Id">
+ <key-many-to-one name="customer" class="Customer" column="CUST_ID" lazy="false"/>
+ <key-property name="number" column="ORDR_NUM" type="long" />
+ </composite-id>
+ <set name="items" table="COMP_LAZY_KM2O_ITEM">
+ <key>
+ <column name="CUST_ID"/>
+ <column name="ORDER_NUM"/>
+ </key>
+ <element type="string" column="ITEM_DESC" />
+ </set>
+ </class>
+
+</hibernate-mapping>
Added: trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/LazyKeyManyToOneTest.java
===================================================================
--- trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/LazyKeyManyToOneTest.java (rev 0)
+++ trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/LazyKeyManyToOneTest.java 2007-01-23 12:54:10 UTC (rev 11076)
@@ -0,0 +1,77 @@
+package org.hibernate.test.keymanytoone.bidir.component;
+
+import junit.framework.Test;
+
+import org.hibernate.test.TestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.cfg.Environment;
+import org.hibernate.Session;
+
+/**
+ * @author Steve Ebersole
+ */
+public class LazyKeyManyToOneTest extends TestCase {
+ public LazyKeyManyToOneTest(String name) {
+ super( name );
+ }
+
+ protected String[] getMappings() {
+ return new String[] { "keymanytoone/bidir/component/LazyMapping.hbm.xml" };
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( LazyKeyManyToOneTest.class );
+ }
+
+ protected void configure(Configuration cfg) {
+ super.configure( cfg );
+ cfg.setProperty( Environment.GENERATE_STATISTICS, "true" );
+ }
+
+ public void testSaveCascadedToKeyManyToOne() {
+ // test cascading a save to an association with a key-many-to-one which refers to a
+ // just saved entity
+ Session s = openSession();
+ s.beginTransaction();
+ Customer cust = new Customer( "Acme, Inc." );
+ Order order = new Order( new Order.Id( cust, 1 ) );
+ cust.getOrders().add( order );
+ s.save( cust );
+ s.flush();
+ assertEquals( 2, sfi().getStatistics().getEntityInsertCount() );
+ s.delete( cust );
+ s.getTransaction().commit();
+ s.close();
+ }
+
+ public void testLoadingStrategies() {
+ Session s = openSession();
+ s.beginTransaction();
+ Customer cust = new Customer( "Acme, Inc." );
+ Order order = new Order( new Order.Id( cust, 1 ) );
+ cust.getOrders().add( order );
+ s.save( cust );
+ s.getTransaction().commit();
+ s.close();
+
+ s = openSession();
+ s.beginTransaction();
+
+ cust = ( Customer ) s.get( Customer.class, cust.getId() );
+ assertEquals( 1, cust.getOrders().size() );
+ s.clear();
+
+ cust = ( Customer ) s.createQuery( "from Customer" ).uniqueResult();
+ assertEquals( 1, cust.getOrders().size() );
+ s.clear();
+
+ cust = ( Customer ) s.createQuery( "from Customer c join fetch c.orders" ).uniqueResult();
+ assertEquals( 1, cust.getOrders().size() );
+ s.clear();
+
+ s.delete( cust );
+ s.getTransaction().commit();
+ s.close();
+ }
+}
Added: trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/LazyMapping.hbm.xml
===================================================================
--- trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/LazyMapping.hbm.xml (rev 0)
+++ trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/LazyMapping.hbm.xml 2007-01-23 12:54:10 UTC (rev 11076)
@@ -0,0 +1,42 @@
+<?xml version="1.0"?>
+<!DOCTYPE hibernate-mapping PUBLIC
+ "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+ "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
+
+<!--
+ This mapping demonstrates the use of composite ids with the
+ key-many-to-one feature. Essentially a composite id where part
+ of the composition is a foreign-key to another entity.
+
+ Here, specifically, we map the key-many-to-one as a lazy
+ association.
+-->
+
+<hibernate-mapping package="org.hibernate.test.keymanytoone.bidir.component">
+
+ <class name="Customer" table="COMP_LAZY_KM2O_CUST">
+ <id name="id" column="ID" type="long">
+ <generator class="increment" />
+ </id>
+ <property name="name" column="NAME" type="string" />
+ <bag name="orders" inverse="true" cascade="all">
+ <key column="CUST_ID" />
+ <one-to-many class="Order" />
+ </bag>
+ </class>
+
+ <class name="Order" table="COMP_LAZY_KM2O_ORDR">
+ <composite-id name="id" class="Order$Id">
+ <key-many-to-one name="customer" class="Customer" column="CUST_ID" lazy="proxy"/>
+ <key-property name="number" column="ORDR_NUM" type="long" />
+ </composite-id>
+ <set name="items" table="COMP_LAZY_KM2O_ITEM">
+ <key>
+ <column name="CUST_ID"/>
+ <column name="ORDER_NUM"/>
+ </key>
+ <element type="string" column="ITEM_DESC" />
+ </set>
+ </class>
+
+</hibernate-mapping>
Added: trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/Order.java
===================================================================
--- trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/Order.java (rev 0)
+++ trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/component/Order.java 2007-01-23 12:54:10 UTC (rev 11076)
@@ -0,0 +1,86 @@
+package org.hibernate.test.keymanytoone.bidir.component;
+
+import java.io.Serializable;
+import java.util.Set;
+import java.util.HashSet;
+
+/**
+ * {@inheritDoc}
+ *
+ * @author Steve Ebersole
+ */
+public class Order {
+ private Id id;
+ private Set items = new HashSet();
+
+ public Order() {
+ }
+
+ public Order(Id id) {
+ this.id = id;
+ }
+
+ public Id getId() {
+ return id;
+ }
+
+ public void setId(Id id) {
+ this.id = id;
+ }
+
+ public Set getItems() {
+ return items;
+ }
+
+ public void setItems(Set items) {
+ this.items = items;
+ }
+
+ public static class Id implements Serializable {
+ private Customer customer;
+ private long number;
+
+ public Id() {
+ }
+
+ public Id(Customer customer, long number) {
+ this.customer = customer;
+ this.number = number;
+ }
+
+ public Customer getCustomer() {
+ return customer;
+ }
+
+ public void setCustomer(Customer customer) {
+ this.customer = customer;
+ }
+
+ public long getNumber() {
+ return number;
+ }
+
+ public void setNumber(long number) {
+ this.number = number;
+ }
+
+ public boolean equals(Object o) {
+ if ( this == o ) {
+ return true;
+ }
+ if ( o == null || getClass() != o.getClass() ) {
+ return false;
+ }
+
+ Id id = ( Id ) o;
+ return number == id.number && customer.equals( id.customer );
+ }
+
+ public int hashCode() {
+ int result;
+ result = customer.hashCode();
+ result = 31 * result + ( int ) ( number ^ ( number >>> 32 ) );
+ return result;
+ }
+ }
+}
Added: trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/embedded/Customer.java
===================================================================
--- trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/embedded/Customer.java (rev 0)
+++ trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/embedded/Customer.java 2007-01-23 12:54:10 UTC (rev 11076)
@@ -0,0 +1,46 @@
+package org.hibernate.test.keymanytoone.bidir.embedded;
+
+import java.util.Collection;
+import java.util.ArrayList;
+
+/**
+ * {@inheritDoc}
+ *
+ * @author Steve Ebersole
+ */
+public class Customer {
+ private Long id;
+ private String name;
+ private Collection orders = new ArrayList();
+
+ public Customer() {
+ }
+
+ public Customer(String name) {
+ this.name = name;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public Collection getOrders() {
+ return orders;
+ }
+
+ public void setOrders(Collection orders) {
+ this.orders = orders;
+ }
+}
Added: trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/embedded/KeyManyToOneTest.java
===================================================================
--- trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/embedded/KeyManyToOneTest.java (rev 0)
+++ trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/embedded/KeyManyToOneTest.java 2007-01-23 12:54:10 UTC (rev 11076)
@@ -0,0 +1,77 @@
+package org.hibernate.test.keymanytoone.bidir.embedded;
+
+import junit.framework.Test;
+
+import org.hibernate.test.TestCase;
+import org.hibernate.Session;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.cfg.Environment;
+
+/**
+ * @author Steve Ebersole
+ */
+public class KeyManyToOneTest extends TestCase {
+ public KeyManyToOneTest(String name) {
+ super( name );
+ }
+
+ protected String[] getMappings() {
+ return new String[] { "keymanytoone/bidir/embedded/Mapping.hbm.xml" };
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( KeyManyToOneTest.class );
+ }
+
+ protected void configure(Configuration cfg) {
+ super.configure( cfg );
+ cfg.setProperty( Environment.GENERATE_STATISTICS, "true" );
+ }
+
+ public void testSaveCascadedToKeyManyToOne() {
+ // test cascading a save to an association with a key-many-to-one which refers to a
+ // just saved entity
+ Session s = openSession();
+ s.beginTransaction();
+ Customer cust = new Customer( "Acme, Inc." );
+ Order order = new Order( cust, 1 );
+ cust.getOrders().add( order );
+ s.save( cust );
+ s.flush();
+ assertEquals( 2, sfi().getStatistics().getEntityInsertCount() );
+ s.delete( cust );
+ s.getTransaction().commit();
+ s.close();
+ }
+
+ public void testLoadingStrategies() {
+ Session s = openSession();
+ s.beginTransaction();
+ Customer cust = new Customer( "Acme, Inc." );
+ Order order = new Order( cust, 1 );
+ cust.getOrders().add( order );
+ s.save( cust );
+ s.getTransaction().commit();
+ s.close();
+
+ s = openSession();
+ s.beginTransaction();
+
+ cust = ( Customer ) s.get( Customer.class, cust.getId() );
+ assertEquals( 1, cust.getOrders().size() );
+ s.clear();
+
+ cust = ( Customer ) s.createQuery( "from Customer" ).uniqueResult();
+ assertEquals( 1, cust.getOrders().size() );
+ s.clear();
+
+ cust = ( Customer ) s.createQuery( "from Customer c join fetch c.orders" ).uniqueResult();
+ assertEquals( 1, cust.getOrders().size() );
+ s.clear();
+
+ s.delete( cust );
+ s.getTransaction().commit();
+ s.close();
+ }
+}
Added: trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/embedded/Mapping.hbm.xml
===================================================================
--- trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/embedded/Mapping.hbm.xml (rev 0)
+++ trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/embedded/Mapping.hbm.xml 2007-01-23 12:54:10 UTC (rev 11076)
@@ -0,0 +1,39 @@
+<?xml version="1.0"?>
+<!DOCTYPE hibernate-mapping PUBLIC
+ "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+ "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
+
+<!--
+ This mapping demonstrates the use of composite ids with the
+ key-many-to-one feature where the composite-id is an embedded form.
+ Essentially a composite id where part of the composition is a
+ foreign-key to another entity.
+-->
+
+<hibernate-mapping package="org.hibernate.test.keymanytoone.bidir.embedded">
+
+ <class name="Customer" table="EMBD_KM2O_CUST">
+ <id name="id" column="ID" type="long">
+ <generator class="increment" />
+ </id>
+ <property name="name" column="NAME" type="string" />
+ <bag name="orders" inverse="true" cascade="all">
+ <key column="CUST_ID" />
+ <one-to-many class="Order" />
+ </bag>
+ </class>
+
+ <class name="Order" table="EMBD_KM2O_ORDR">
+ <composite-id mapped="false">
+ <key-many-to-one name="customer" class="Customer" column="CUST_ID" lazy="false"/>
+ <key-property name="number" column="ORDR_NUM" type="long" />
+ </composite-id>
+ <set name="items" table="EMBD_KM2O_ITEM">
+ <key>
+ <column name="CUST_ID"/>
+ <column name="ORDER_NUM"/>
+ </key>
+ <element type="string" column="ITEM_DESC" />
+ </set>
+ </class>
+</hibernate-mapping>
\ No newline at end of file
Added: trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/embedded/Order.java
===================================================================
--- trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/embedded/Order.java (rev 0)
+++ trunk/Hibernate3/test/org/hibernate/test/keymanytoone/bidir/embedded/Order.java 2007-01-23 12:54:10 UTC (rev 11076)
@@ -0,0 +1,48 @@
+package org.hibernate.test.keymanytoone.bidir.embedded;
+
+import java.util.Set;
+import java.util.HashSet;
+import java.io.Serializable;
+
+/**
+ * {@inheritDoc}
+ *
+ * @author Steve Ebersole
+ */
+public class Order implements Serializable {
+ private Customer customer;
+ private long number;
+ private Set items = new HashSet();
+
+ public Order() {
+ }
+
+ public Order(Customer customer, long number) {
+ this.customer = customer;
+ this.number = number;
+ }
+
+ public Customer getCustomer() {
+ return customer;
+ }
+
+ public void setCustomer(Customer customer) {
+ this.customer = customer;
+ }
+
+ public long getNumber() {
+ return number;
+ }
+
+ public void setNumber(long number) {
+ this.number = number;
+ }
+
+ public Set getItems() {
+ return items;
+ }
+
+ public void setItems(Set items) {
+ this.items = items;
+ }
+}
17 years, 12 months
Hibernate SVN: r11075 - in branches/Branch_3_2/Hibernate3/test/org/hibernate/test/onetoone: optional and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2007-01-22 13:59:20 -0500 (Mon, 22 Jan 2007)
New Revision: 11075
Added:
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/onetoone/optional/
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/onetoone/optional/Address.java
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/onetoone/optional/Entity.java
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/onetoone/optional/OptionalOneToOneTest.java
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/onetoone/optional/Org.java
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/onetoone/optional/Person.hbm.xml
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/onetoone/optional/Person.java
Modified:
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/onetoone/OneToOneSuite.java
Log:
added tests dealing with optional one-to-one mappings
Modified: branches/Branch_3_2/Hibernate3/test/org/hibernate/test/onetoone/OneToOneSuite.java
===================================================================
--- branches/Branch_3_2/Hibernate3/test/org/hibernate/test/onetoone/OneToOneSuite.java 2007-01-22 18:59:05 UTC (rev 11074)
+++ branches/Branch_3_2/Hibernate3/test/org/hibernate/test/onetoone/OneToOneSuite.java 2007-01-22 18:59:20 UTC (rev 11075)
@@ -8,6 +8,7 @@
import org.hibernate.test.onetoone.link.OneToOneLinkTest;
import org.hibernate.test.onetoone.nopojo.DynamicMapOneToOneTest;
import org.hibernate.test.onetoone.singletable.DiscrimSubclassOneToOneTest;
+import org.hibernate.test.onetoone.optional.OptionalOneToOneTest;
/**
* {@inheritDoc}
@@ -21,6 +22,7 @@
suite.addTest( JoinedSubclassOneToOneTest.suite() );
suite.addTest( OneToOneLinkTest.suite() );
suite.addTest( DynamicMapOneToOneTest.suite() );
+ suite.addTest( OptionalOneToOneTest.suite() );
suite.addTest( DiscrimSubclassOneToOneTest.suite() );
return suite;
}
Added: branches/Branch_3_2/Hibernate3/test/org/hibernate/test/onetoone/optional/Address.java
===================================================================
--- branches/Branch_3_2/Hibernate3/test/org/hibernate/test/onetoone/optional/Address.java (rev 0)
+++ branches/Branch_3_2/Hibernate3/test/org/hibernate/test/onetoone/optional/Address.java 2007-01-22 18:59:20 UTC (rev 11075)
@@ -0,0 +1,15 @@
+package org.hibernate.test.onetoone.optional;
+
+/**
+ * @author Gavin King
+ */
+public class Address {
+ public String entityName;
+ public String street;
+ public String state;
+ public String zip;
+
+ public String toString() {
+ return this.getClass() + ":" + street;
+ }
+}
Added: branches/Branch_3_2/Hibernate3/test/org/hibernate/test/onetoone/optional/Entity.java
===================================================================
--- branches/Branch_3_2/Hibernate3/test/org/hibernate/test/onetoone/optional/Entity.java (rev 0)
+++ branches/Branch_3_2/Hibernate3/test/org/hibernate/test/onetoone/optional/Entity.java 2007-01-22 18:59:20 UTC (rev 11075)
@@ -0,0 +1,8 @@
+package org.hibernate.test.onetoone.optional;
+
+/**
+ * @author Gavin King
+ */
+public class Entity {
+ public String name;
+}
Added: branches/Branch_3_2/Hibernate3/test/org/hibernate/test/onetoone/optional/OptionalOneToOneTest.java
===================================================================
--- branches/Branch_3_2/Hibernate3/test/org/hibernate/test/onetoone/optional/OptionalOneToOneTest.java (rev 0)
+++ branches/Branch_3_2/Hibernate3/test/org/hibernate/test/onetoone/optional/OptionalOneToOneTest.java 2007-01-22 18:59:20 UTC (rev 11075)
@@ -0,0 +1,50 @@
+package org.hibernate.test.onetoone.optional;
+
+import junit.framework.Test;
+
+import org.hibernate.junit.functional.FunctionalTestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.cfg.Environment;
+import org.hibernate.Session;
+
+/**
+ * @author Gavin King
+ */
+public class OptionalOneToOneTest extends FunctionalTestCase {
+
+ public OptionalOneToOneTest(String str) {
+ super(str);
+ }
+
+ public String[] getMappings() {
+ return new String[] { "onetoone/optional/Person.hbm.xml" };
+ }
+
+ public void configure(Configuration cfg) {
+ cfg.setProperty( Environment.USE_SECOND_LEVEL_CACHE, "false");
+ cfg.setProperty(Environment.GENERATE_STATISTICS, "true");
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( OptionalOneToOneTest.class );
+ }
+
+ public void testOptionalOneToOneRetrieval() {
+ Session s = openSession();
+ s.beginTransaction();
+ Person me = new Person();
+ me.name = "Steve";
+ s.save( me );
+ s.getTransaction().commit();
+ s.close();
+
+ s = openSession();
+ s.beginTransaction();
+ me = ( Person ) s.load( Person.class, me.name );
+ assertNull( me.address );
+ s.delete( me );
+ s.getTransaction().commit();
+ s.close();
+ }
+}
Added: branches/Branch_3_2/Hibernate3/test/org/hibernate/test/onetoone/optional/Org.java
===================================================================
--- branches/Branch_3_2/Hibernate3/test/org/hibernate/test/onetoone/optional/Org.java (rev 0)
+++ branches/Branch_3_2/Hibernate3/test/org/hibernate/test/onetoone/optional/Org.java 2007-01-22 18:59:20 UTC (rev 11075)
@@ -0,0 +1,8 @@
+package org.hibernate.test.onetoone.optional;
+
+
+/**
+ * @author Gavin King
+ */
+public class Org extends Entity {
+}
Added: branches/Branch_3_2/Hibernate3/test/org/hibernate/test/onetoone/optional/Person.hbm.xml
===================================================================
--- branches/Branch_3_2/Hibernate3/test/org/hibernate/test/onetoone/optional/Person.hbm.xml (rev 0)
+++ branches/Branch_3_2/Hibernate3/test/org/hibernate/test/onetoone/optional/Person.hbm.xml 2007-01-22 18:59:20 UTC (rev 11075)
@@ -0,0 +1,38 @@
+<?xml version="1.0"?>
+<!DOCTYPE hibernate-mapping PUBLIC
+ "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+ "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
+
+<!--
+ Demonstrates mapping an "optional" one-to-one association. Basically
+ a (zero or one)-to-one.
+
+ Note that this is only conceptually possible on the non-constrained
+ side of the association (the side without the FK).
+
+ Also, it is impossible that the optional side be lazy; we must hit the
+ target table to determine whether a matching row actually exists or not.
+ This is so we can properly determine whether to use null or some value
+ for the association property's value.
+-->
+<hibernate-mapping package="org.hibernate.test.onetoone.optional" default-access="field">
+
+ <class name="Entity">
+ <id name="name"/>
+ <joined-subclass name="Person">
+ <key column="entityName"/>
+ <one-to-one name="address" cascade="all" constrained="false" outer-join="false" lazy="proxy"/>
+ </joined-subclass>
+ <joined-subclass name="Org">
+ <key column="entityName"/>
+ </joined-subclass>
+ </class>
+
+ <class name="Address">
+ <id name="entityName"/>
+ <property name="street"/>
+ <property name="state"/>
+ <property name="zip"/>
+ </class>
+
+</hibernate-mapping>
Added: branches/Branch_3_2/Hibernate3/test/org/hibernate/test/onetoone/optional/Person.java
===================================================================
--- branches/Branch_3_2/Hibernate3/test/org/hibernate/test/onetoone/optional/Person.java (rev 0)
+++ branches/Branch_3_2/Hibernate3/test/org/hibernate/test/onetoone/optional/Person.java 2007-01-22 18:59:20 UTC (rev 11075)
@@ -0,0 +1,9 @@
+package org.hibernate.test.onetoone.optional;
+
+/**
+ * @author Gavin King
+ */
+public class Person extends Entity {
+ public Address address;
+ public Address mailingAddress;
+}
17 years, 12 months
Hibernate SVN: r11074 - in trunk/Hibernate3/test/org/hibernate/test/onetoone: optional and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2007-01-22 13:59:05 -0500 (Mon, 22 Jan 2007)
New Revision: 11074
Added:
trunk/Hibernate3/test/org/hibernate/test/onetoone/optional/
trunk/Hibernate3/test/org/hibernate/test/onetoone/optional/Address.java
trunk/Hibernate3/test/org/hibernate/test/onetoone/optional/Entity.java
trunk/Hibernate3/test/org/hibernate/test/onetoone/optional/OptionalOneToOneTest.java
trunk/Hibernate3/test/org/hibernate/test/onetoone/optional/Org.java
trunk/Hibernate3/test/org/hibernate/test/onetoone/optional/Person.hbm.xml
trunk/Hibernate3/test/org/hibernate/test/onetoone/optional/Person.java
Modified:
trunk/Hibernate3/test/org/hibernate/test/onetoone/OneToOneSuite.java
Log:
added tests dealing with optional one-to-one mappings
Modified: trunk/Hibernate3/test/org/hibernate/test/onetoone/OneToOneSuite.java
===================================================================
--- trunk/Hibernate3/test/org/hibernate/test/onetoone/OneToOneSuite.java 2007-01-22 00:43:28 UTC (rev 11073)
+++ trunk/Hibernate3/test/org/hibernate/test/onetoone/OneToOneSuite.java 2007-01-22 18:59:05 UTC (rev 11074)
@@ -7,6 +7,7 @@
import org.hibernate.test.onetoone.joined.JoinedSubclassOneToOneTest;
import org.hibernate.test.onetoone.link.OneToOneLinkTest;
import org.hibernate.test.onetoone.nopojo.DynamicMapOneToOneTest;
+import org.hibernate.test.onetoone.optional.OptionalOneToOneTest;
import org.hibernate.test.onetoone.singletable.DiscrimSubclassOneToOneTest;
/**
@@ -21,6 +22,7 @@
suite.addTest( JoinedSubclassOneToOneTest.suite() );
suite.addTest( OneToOneLinkTest.suite() );
suite.addTest( DynamicMapOneToOneTest.suite() );
+ suite.addTest( OptionalOneToOneTest.suite() );
suite.addTest( DiscrimSubclassOneToOneTest.suite() );
return suite;
}
Added: trunk/Hibernate3/test/org/hibernate/test/onetoone/optional/Address.java
===================================================================
--- trunk/Hibernate3/test/org/hibernate/test/onetoone/optional/Address.java (rev 0)
+++ trunk/Hibernate3/test/org/hibernate/test/onetoone/optional/Address.java 2007-01-22 18:59:05 UTC (rev 11074)
@@ -0,0 +1,15 @@
+package org.hibernate.test.onetoone.optional;
+
+/**
+ * @author Gavin King
+ */
+public class Address {
+ public String entityName;
+ public String street;
+ public String state;
+ public String zip;
+
+ public String toString() {
+ return this.getClass() + ":" + street;
+ }
+}
Added: trunk/Hibernate3/test/org/hibernate/test/onetoone/optional/Entity.java
===================================================================
--- trunk/Hibernate3/test/org/hibernate/test/onetoone/optional/Entity.java (rev 0)
+++ trunk/Hibernate3/test/org/hibernate/test/onetoone/optional/Entity.java 2007-01-22 18:59:05 UTC (rev 11074)
@@ -0,0 +1,8 @@
+package org.hibernate.test.onetoone.optional;
+
+/**
+ * @author Gavin King
+ */
+public class Entity {
+ public String name;
+}
Added: trunk/Hibernate3/test/org/hibernate/test/onetoone/optional/OptionalOneToOneTest.java
===================================================================
--- trunk/Hibernate3/test/org/hibernate/test/onetoone/optional/OptionalOneToOneTest.java (rev 0)
+++ trunk/Hibernate3/test/org/hibernate/test/onetoone/optional/OptionalOneToOneTest.java 2007-01-22 18:59:05 UTC (rev 11074)
@@ -0,0 +1,50 @@
+package org.hibernate.test.onetoone.optional;
+
+import junit.framework.Test;
+
+import org.hibernate.junit.functional.FunctionalTestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.cfg.Environment;
+import org.hibernate.Session;
+
+/**
+ * @author Gavin King
+ */
+public class OptionalOneToOneTest extends FunctionalTestCase {
+
+ public OptionalOneToOneTest(String str) {
+ super(str);
+ }
+
+ public String[] getMappings() {
+ return new String[] { "onetoone/optional/Person.hbm.xml" };
+ }
+
+ public void configure(Configuration cfg) {
+ cfg.setProperty( Environment.USE_SECOND_LEVEL_CACHE, "false");
+ cfg.setProperty(Environment.GENERATE_STATISTICS, "true");
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( OptionalOneToOneTest.class );
+ }
+
+ public void testOptionalOneToOneRetrieval() {
+ Session s = openSession();
+ s.beginTransaction();
+ Person me = new Person();
+ me.name = "Steve";
+ s.save( me );
+ s.getTransaction().commit();
+ s.close();
+
+ s = openSession();
+ s.beginTransaction();
+ me = ( Person ) s.load( Person.class, me.name );
+ assertNull( me.address );
+ s.delete( me );
+ s.getTransaction().commit();
+ s.close();
+ }
+}
Added: trunk/Hibernate3/test/org/hibernate/test/onetoone/optional/Org.java
===================================================================
--- trunk/Hibernate3/test/org/hibernate/test/onetoone/optional/Org.java (rev 0)
+++ trunk/Hibernate3/test/org/hibernate/test/onetoone/optional/Org.java 2007-01-22 18:59:05 UTC (rev 11074)
@@ -0,0 +1,8 @@
+package org.hibernate.test.onetoone.optional;
+
+
+/**
+ * @author Gavin King
+ */
+public class Org extends Entity {
+}
Added: trunk/Hibernate3/test/org/hibernate/test/onetoone/optional/Person.hbm.xml
===================================================================
--- trunk/Hibernate3/test/org/hibernate/test/onetoone/optional/Person.hbm.xml (rev 0)
+++ trunk/Hibernate3/test/org/hibernate/test/onetoone/optional/Person.hbm.xml 2007-01-22 18:59:05 UTC (rev 11074)
@@ -0,0 +1,38 @@
+<?xml version="1.0"?>
+<!DOCTYPE hibernate-mapping PUBLIC
+ "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+ "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
+
+<!--
+ Demonstrates mapping an "optional" one-to-one association. Basically
+ a (zero or one)-to-one.
+
+ Note that this is only conceptually possible on the non-constrained
+ side of the association (the side without the FK).
+
+ Also, it is impossible that the optional side be lazy; we must hit the
+ target table to determine whether a matching row actually exists or not.
+ This is so we can properly determine whether to use null or some value
+ for the association property's value.
+-->
+<hibernate-mapping package="org.hibernate.test.onetoone.optional" default-access="field">
+
+ <class name="Entity">
+ <id name="name"/>
+ <joined-subclass name="Person">
+ <key column="entityName"/>
+ <one-to-one name="address" cascade="all" constrained="false" outer-join="false" lazy="proxy"/>
+ </joined-subclass>
+ <joined-subclass name="Org">
+ <key column="entityName"/>
+ </joined-subclass>
+ </class>
+
+ <class name="Address">
+ <id name="entityName"/>
+ <property name="street"/>
+ <property name="state"/>
+ <property name="zip"/>
+ </class>
+
+</hibernate-mapping>
Added: trunk/Hibernate3/test/org/hibernate/test/onetoone/optional/Person.java
===================================================================
--- trunk/Hibernate3/test/org/hibernate/test/onetoone/optional/Person.java (rev 0)
+++ trunk/Hibernate3/test/org/hibernate/test/onetoone/optional/Person.java 2007-01-22 18:59:05 UTC (rev 11074)
@@ -0,0 +1,9 @@
+package org.hibernate.test.onetoone.optional;
+
+/**
+ * @author Gavin King
+ */
+public class Person extends Entity {
+ public Address address;
+ public Address mailingAddress;
+}
17 years, 12 months
Hibernate SVN: r11073 - branches/Branch_3_2/HibernateExt/metadata/doc/reference/en/modules.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2007-01-21 19:43:28 -0500 (Sun, 21 Jan 2007)
New Revision: 11073
Modified:
branches/Branch_3_2/HibernateExt/metadata/doc/reference/en/modules/entity.xml
Log:
small doc error
Modified: branches/Branch_3_2/HibernateExt/metadata/doc/reference/en/modules/entity.xml
===================================================================
--- branches/Branch_3_2/HibernateExt/metadata/doc/reference/en/modules/entity.xml 2007-01-22 00:39:26 UTC (rev 11072)
+++ branches/Branch_3_2/HibernateExt/metadata/doc/reference/en/modules/entity.xml 2007-01-22 00:43:28 UTC (rev 11073)
@@ -1187,7 +1187,7 @@
</programlisting>
</sect3>
- <sect3 id="entity-mapping-association-collections">
+ <sect3 id="entity-mapping-association-collections" revision="1">
<title>Collections</title>
<sect4 id="entity-mapping-association-collections-overview"
@@ -1203,8 +1203,7 @@
annotation takes into parameter a list of comma separated (target
entity) properties to order the collection by (eg <code>firstname
asc, age desc</code>), if the string is empty, the collection will
- be ordered by id. <literal>@OrderBy</literal> currently works only
- on collections having no association table. For true indexed
+ be ordered by id. For true indexed
collections, please refer to the <xref linkend="entity-hibspec" />.
EJB3 allows you to map Maps using as a key one of the target entity
property using <literal>@MapKey(name="myProperty")</literal>
17 years, 12 months
Hibernate SVN: r11072 - branches/Branch_3_2/HibernateExt/ejb/src/java/org/hibernate/ejb.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2007-01-21 19:39:26 -0500 (Sun, 21 Jan 2007)
New Revision: 11072
Modified:
branches/Branch_3_2/HibernateExt/ejb/src/java/org/hibernate/ejb/QueryImpl.java
Log:
EJB-263 make elements unique before raising getSingleResult exceptions
Modified: branches/Branch_3_2/HibernateExt/ejb/src/java/org/hibernate/ejb/QueryImpl.java
===================================================================
--- branches/Branch_3_2/HibernateExt/ejb/src/java/org/hibernate/ejb/QueryImpl.java 2007-01-20 19:17:07 UTC (rev 11071)
+++ branches/Branch_3_2/HibernateExt/ejb/src/java/org/hibernate/ejb/QueryImpl.java 2007-01-22 00:39:26 UTC (rev 11072)
@@ -5,6 +5,8 @@
import java.util.Collection;
import java.util.Date;
import java.util.List;
+import java.util.HashSet;
+import java.util.Set;
import javax.persistence.FlushModeType;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
@@ -82,7 +84,14 @@
em.throwPersistenceException( new NoResultException( "No entity found for query" ) );
}
else if ( result.size() > 1 ) {
- em.throwPersistenceException( new NonUniqueResultException( "result returns " + result.size() + " elements") );
+ Set uniqueResult = new HashSet(result);
+ if ( uniqueResult.size() > 1 ) {
+ em.throwPersistenceException( new NonUniqueResultException( "result returns " + uniqueResult.size() + " elements") );
+ }
+ else {
+ return uniqueResult.iterator().next();
+ }
+
}
else {
return result.get(0);
17 years, 12 months
Hibernate SVN: r11071 - in trunk/Hibernate3: test/org/hibernate/test/component and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2007-01-20 14:17:07 -0500 (Sat, 20 Jan 2007)
New Revision: 11071
Modified:
trunk/Hibernate3/src/org/hibernate/action/EntityUpdateAction.java
trunk/Hibernate3/test/org/hibernate/test/component/ComponentTest.java
Log:
HHH-2366 : changing a component property not detected as dirty
Modified: trunk/Hibernate3/src/org/hibernate/action/EntityUpdateAction.java
===================================================================
--- trunk/Hibernate3/src/org/hibernate/action/EntityUpdateAction.java 2007-01-20 19:16:38 UTC (rev 11070)
+++ trunk/Hibernate3/src/org/hibernate/action/EntityUpdateAction.java 2007-01-20 19:17:07 UTC (rev 11071)
@@ -108,22 +108,26 @@
}
if ( entry.getStatus()==Status.MANAGED || persister.isVersionPropertyGenerated() ) {
+ // get the updated snapshot of the entity state by cloning current state;
+ // it is safe to copy in place, since by this time no-one else (should have)
+ // has a reference to the array
+ TypeFactory.deepCopy(
+ state,
+ persister.getPropertyTypes(),
+ persister.getPropertyCheckability(),
+ state,
+ session
+ );
if ( persister.hasUpdateGeneratedProperties() ) {
- // get the updated snapshot by cloning current state;
- // it is safe to copy in place, since by this time
- // no-one else has a reference to the array
- TypeFactory.deepCopy(
- state,
- persister.getPropertyTypes(),
- persister.getPropertyCheckability(),
- state,
- session
- );
+ // this entity defines proeprty generation, so process those generated
+ // values...
persister.processUpdateGeneratedProperties( id, instance, state, session );
if ( persister.isVersionPropertyGenerated() ) {
- nextVersion = Versioning.getVersion(state, persister);
+ nextVersion = Versioning.getVersion( state, persister );
}
}
+ // have the entity entry perform post-update processing, passing it the
+ // update state and the new version (if one).
entry.postUpdate( instance, state, nextVersion );
}
Modified: trunk/Hibernate3/test/org/hibernate/test/component/ComponentTest.java
===================================================================
--- trunk/Hibernate3/test/org/hibernate/test/component/ComponentTest.java 2007-01-20 19:16:38 UTC (rev 11070)
+++ trunk/Hibernate3/test/org/hibernate/test/component/ComponentTest.java 2007-01-20 19:17:07 UTC (rev 11071)
@@ -125,6 +125,26 @@
s.close();
}
+ public void testComponentStateChangeAndDirtiness() {
+ // test for HHH-2366
+ Session s = openSession();
+ s.beginTransaction();
+ User u = new User( "steve", "hibernater", new Person( "Steve Ebersole", new Date(), "Main St") );
+ s.persist( u );
+ s.flush();
+ long intialUpdateCount = sfi().getStatistics().getEntityUpdateCount();
+ u.getPerson().setAddress( "Austin" );
+ s.flush();
+ assertEquals( intialUpdateCount + 1, sfi().getStatistics().getEntityUpdateCount() );
+ intialUpdateCount = sfi().getStatistics().getEntityUpdateCount();
+ u.getPerson().setAddress( "Cedar Park" );
+ s.flush();
+ assertEquals( intialUpdateCount + 1, sfi().getStatistics().getEntityUpdateCount() );
+ s.delete( u );
+ s.getTransaction().commit();
+ s.close();
+ }
+
public void testComponentQueries() {
Session s = openSession();
Transaction t = s.beginTransaction();
17 years, 12 months