From: <hib...@li...> - 2006-03-22 23:27:04
|
Author: epbernard Date: 2006-03-22 18:21:44 -0500 (Wed, 22 Mar 2006) New Revision: 9679 Added: trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/transaction/JoinableCMTTransaction.java trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/transaction/JoinableCMTTransactionFactory.java trunk/HibernateExt/ejb/src/test/org/hibernate/ejb/test/ops/PersistTest.java Removed: trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/transaction/JoinableJTATransaction.java trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/transaction/JoinableJTATransactionFactory.java trunk/HibernateExt/ejb/src/test/org/hibernate/ejb/test/ops/CreateTest.java Modified: trunk/HibernateExt/ejb/lib/README.txt trunk/HibernateExt/ejb/lib/ejb3-persistence.jar trunk/HibernateExt/ejb/lib/hibernate-annotations.jar trunk/HibernateExt/ejb/lib/javassist.jar trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/AbstractEntityManagerImpl.java trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/Ejb3Configuration.java trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/EntityManagerImpl.java trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/HibernateEntityManagerImplementor.java trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/QueryImpl.java trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/TransactionImpl.java trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/packaging/PersistenceXmlLoader.java trunk/HibernateExt/ejb/src/test/org/hibernate/ejb/test/EntityManagerTest.java trunk/HibernateExt/ejb/src/test/org/hibernate/ejb/test/ejb3configuration/EntityManagerSerializationTest.java Log: EJB-117 EJB-137 EJB-134 EJB-37 Modified: trunk/HibernateExt/ejb/lib/README.txt =================================================================== --- trunk/HibernateExt/ejb/lib/README.txt 2006-03-22 22:37:25 UTC (rev 9678) +++ trunk/HibernateExt/ejb/lib/README.txt 2006-03-22 23:21:44 UTC (rev 9679) @@ -3,5 +3,5 @@ ejb3-persistence (proposed final draft): required hibernate-annotations (3.1beta9): required -javassist (3.0): required +javassist (3.1): required jboss-archive-browsing (5.0.0alpha build: CVSTag=HEAD date=200507071617): required Modified: trunk/HibernateExt/ejb/lib/ejb3-persistence.jar =================================================================== (Binary files differ) Modified: trunk/HibernateExt/ejb/lib/hibernate-annotations.jar =================================================================== (Binary files differ) Modified: trunk/HibernateExt/ejb/lib/javassist.jar =================================================================== (Binary files differ) Modified: trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/AbstractEntityManagerImpl.java =================================================================== --- trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/AbstractEntityManagerImpl.java 2006-03-22 22:37:25 UTC (rev 9678) +++ trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/AbstractEntityManagerImpl.java 2006-03-22 23:21:44 UTC (rev 9679) @@ -8,12 +8,14 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; +import javax.persistence.EntityExistsException; import javax.persistence.EntityNotFoundException; import javax.persistence.EntityTransaction; import javax.persistence.FlushModeType; import javax.persistence.LockModeType; import javax.persistence.NoResultException; import javax.persistence.NonUniqueResultException; +import javax.persistence.OptimisticLockException; import javax.persistence.PersistenceContextType; import javax.persistence.PersistenceException; import javax.persistence.Query; @@ -28,6 +30,7 @@ import org.apache.commons.logging.LogFactory; import org.hibernate.AssertionFailure; import org.hibernate.FlushMode; +import org.hibernate.HibernateException; import org.hibernate.LockMode; import org.hibernate.MappingException; import org.hibernate.ObjectDeletedException; @@ -35,12 +38,16 @@ import org.hibernate.SQLQuery; import org.hibernate.Session; import org.hibernate.StaleObjectStateException; +import org.hibernate.StaleStateException; +import org.hibernate.Transaction; import org.hibernate.UnresolvableObjectException; -import org.hibernate.Transaction; -import org.hibernate.ejb.transaction.JoinableJTATransaction; +import org.hibernate.ejb.transaction.JoinableCMTTransaction; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.engine.SessionImplementor; +import org.hibernate.exception.ConstraintViolationException; import org.hibernate.proxy.HibernateProxy; +import org.hibernate.transaction.TransactionFactory; +import org.hibernate.util.JTAHelper; /** * @author <a href="mailto:ga...@hi...">Gavin King</a> @@ -67,57 +74,87 @@ public Query createQuery(String ejbqlString) { //adjustFlushMode(); - return new QueryImpl( getSession().createQuery( ejbqlString ), this ); + try { + return new QueryImpl( getSession().createQuery( ejbqlString ), this ); + } + catch (HibernateException he) { + throwPersistenceException( he ); + return null; + } } public Query createNamedQuery(String name) { //adjustFlushMode(); - return new QueryImpl( getSession().getNamedQuery( name ), this ); + try { + return new QueryImpl( getSession().getNamedQuery( name ), this ); + } + catch (HibernateException he) { + throwPersistenceException( he ); + return null; + } } public Query createNativeQuery(String sqlString) { //adjustFlushMode(); - SQLQuery q = getSession().createSQLQuery( sqlString ); - return new QueryImpl( q, this ); + try { + SQLQuery q = getSession().createSQLQuery( sqlString ); + return new QueryImpl( q, this ); + } + catch (HibernateException he) { + throwPersistenceException( he ); + return null; + } } public Query createNativeQuery(String sqlString, Class resultClass) { //adjustFlushMode(); - SQLQuery q = getSession().createSQLQuery( sqlString ); - q.addEntity( "alias1", resultClass.getName(), LockMode.READ ); - return new QueryImpl( q, this ); + try { + SQLQuery q = getSession().createSQLQuery( sqlString ); + q.addEntity( "alias1", resultClass.getName(), LockMode.READ ); + return new QueryImpl( q, this ); + } + catch (HibernateException he) { + throwPersistenceException( he ); + return null; + } } public Query createNativeQuery(String sqlString, String resultSetMapping) { //adjustFlushMode(); - SQLQuery q = getSession().createSQLQuery( sqlString ); - q.setResultSetMapping( resultSetMapping ); - return new QueryImpl( q, this ); + try { + SQLQuery q = getSession().createSQLQuery( sqlString ); + q.setResultSetMapping( resultSetMapping ); + return new QueryImpl( q, this ); + } + catch (HibernateException he) { + throwPersistenceException( he ); + return null; + } } + @SuppressWarnings("unchecked") public <T> T getReference(Class<T> entityClass, Object primaryKey) { //adjustFlushMode(); try { - T rtn = (T) getSession().load( entityClass, (Serializable) primaryKey ); - return rtn; + return (T) getSession().load( entityClass, (Serializable) primaryKey ); } - catch (ObjectNotFoundException e) { - throwPersistenceException( new EntityNotFoundException( e.getMessage(), e ) ); - return null; //for the compiler to stop complaining - } catch (MappingException e) { throw new IllegalArgumentException( e.getMessage(), e ); } catch (ClassCastException e) { throw new IllegalArgumentException( e.getMessage(), e ); } + catch (HibernateException he) { + throwPersistenceException( he ); + return null; + } } + @SuppressWarnings("unchecked") public <A> A find(Class<A> entityClass, Object primaryKey) { //adjustFlushMode(); try { - A rtn = (A) getSession().get( entityClass, (Serializable) primaryKey ); - return rtn; + return (A) getSession().get( entityClass, (Serializable) primaryKey ); } catch (ObjectNotFoundException e) { //should not happen on the entity itself with get @@ -129,6 +166,10 @@ catch (ClassCastException e) { throw new IllegalArgumentException( e.getMessage(), e ); } + catch (HibernateException he) { + throwPersistenceException( he ); + return null; + } } private void checkTransactionNeeded() { @@ -149,8 +190,12 @@ catch (MappingException e) { throw new IllegalArgumentException( e.getMessage() ); } + catch (HibernateException he) { + throwPersistenceException( he ); + } } + @SuppressWarnings("unchecked") public <A> A merge(A entity) { checkTransactionNeeded(); //adjustFlushMode(); @@ -166,6 +211,10 @@ catch (MappingException e) { throw new IllegalArgumentException( e.getMessage(), e ); } + catch (HibernateException he) { + throwPersistenceException( he ); + return null; + } } public void remove(Object entity) { @@ -177,6 +226,9 @@ catch (MappingException e) { throw new IllegalArgumentException( e.getMessage(), e ); } + catch (HibernateException he) { + throwPersistenceException( he ); + } } public void refresh(Object entity) { @@ -185,12 +237,12 @@ try { getSession().refresh( entity ); } - catch (UnresolvableObjectException uoe) { - throwPersistenceException( new EntityNotFoundException( uoe ) ); - } catch (MappingException e) { throw new IllegalArgumentException( e.getMessage(), e ); } + catch (HibernateException he) { + throwPersistenceException( he ); + } } public boolean contains(Object entity) { @@ -205,12 +257,23 @@ catch (MappingException e) { throw new IllegalArgumentException( e.getMessage(), e ); } + catch (HibernateException he) { + throwPersistenceException( he ); + return false; + } } public void flush() { - if ( ! isTransactionInProgress() ) throw new TransactionRequiredException( "no transaction is in progress" ); - //adjustFlushMode(); - getSession().flush(); + try { + if ( ! isTransactionInProgress() ) { + throw new TransactionRequiredException( "no transaction is in progress" ); + } + //adjustFlushMode(); + getSession().flush(); + } + catch (HibernateException he) { + throwPersistenceException( he ); + } } public abstract Session getSession(); @@ -237,7 +300,12 @@ public void clear() { //adjustFlushMode(); - getSession().clear(); + try { + getSession().clear(); + } + catch (HibernateException he) { + throwPersistenceException( he ); + } } public FlushModeType getFlushMode() { @@ -265,11 +333,17 @@ } public void lock(Object entity, LockModeType lockMode) { - if ( ! isTransactionInProgress() ) throw new TransactionRequiredException( "no transaction is in progress" ); - //adjustFlushMode(); - if ( !contains( entity ) ) throw new IllegalArgumentException( "entity not in the persistence context" ); - getSession().lock( entity, getLockMode( lockMode ) ); - + try { + if ( ! isTransactionInProgress() ) { + throw new TransactionRequiredException( "no transaction is in progress" ); + } + //adjustFlushMode(); + if ( !contains( entity ) ) throw new IllegalArgumentException( "entity not in the persistence context" ); + getSession().lock( entity, getLockMode( lockMode ) ); + } + catch (HibernateException he) { + throwPersistenceException( he ); + } } private LockMode getLockMode(LockModeType lockMode) { @@ -332,41 +406,93 @@ public void joinTransaction() { //set the joined status if ( transactionType == PersistenceUnitTransactionType.JTA ) { - final Session session = getSession(); - final Transaction transaction = session.getTransaction(); - if ( transaction != null && transaction instanceof JoinableJTATransaction) { - //can't handle it if not a joinnable transaction - final JoinableJTATransaction joinableJTATransaction = (JoinableJTATransaction) session.getTransaction(); + try { + final Session session = getSession(); + final Transaction transaction = session.getTransaction(); + if ( transaction != null && transaction instanceof JoinableCMTTransaction ) { + //can't handle it if not a joinnable transaction + final JoinableCMTTransaction joinableCMTTransaction = (JoinableCMTTransaction) session.getTransaction(); - if ( joinableJTATransaction.getStatus() == JoinableJTATransaction.JoinStatus.JOINED ) return; //no-op - joinableJTATransaction.markForJoined(); - session.isOpen(); //register to the Tx - if ( joinableJTATransaction.getStatus() == JoinableJTATransaction.JoinStatus.NOT_JOINED ) { - throw new TransactionRequiredException( "No active JTA transaction on joinTransaction call" ); - } - else if ( joinableJTATransaction.getStatus() == JoinableJTATransaction.JoinStatus.MARKED_FOR_JOINED ) { - throw new AssertionFailure( "Transaction MARKED_FOR_JOINED after isOpen() call" ); - } - //register clear on rollback - joinableJTATransaction.registerSynchronization( - new Synchronization() { + if ( joinableCMTTransaction.getStatus() == JoinableCMTTransaction.JoinStatus.JOINED ) { + return; //no-op + } + joinableCMTTransaction.markForJoined(); + session.isOpen(); //register to the Tx + if ( joinableCMTTransaction.getStatus() == JoinableCMTTransaction.JoinStatus.NOT_JOINED ) { + throw new TransactionRequiredException( "No active JTA transaction on joinTransaction call" ); + } + else + if ( joinableCMTTransaction.getStatus() == JoinableCMTTransaction.JoinStatus.MARKED_FOR_JOINED ) { + throw new AssertionFailure( "Transaction MARKED_FOR_JOINED after isOpen() call" ); + } + //flush before completion and + //register clear on rollback + joinableCMTTransaction.registerSynchronization( + new Synchronization() { + public void beforeCompletion() { + boolean flush = false; + TransactionFactory.Context ctx = null; + try { + ctx = (TransactionFactory.Context) getSession(); + JoinableCMTTransaction joinable = (JoinableCMTTransaction) session.getTransaction(); + flush = !ctx.isFlushModeNever() && + //ctx.isFlushBeforeCompletionEnabled() && + //TODO probably make it ! isFlushBeforecompletion() + !JTAHelper.isRollback( joinable.getTransaction().getStatus() ); + } + catch (SystemException se) { + log.error( "could not determine transaction status", se ); + //throwPersistenceException will mark the transaction as rollbacked + throwPersistenceException( + new PersistenceException( + "could not determine transaction status in beforeCompletion()", + se + ) + ); + } + catch (HibernateException he) { + throwPersistenceException( he ); + } - public void beforeCompletion() { - } + try { + if ( flush ) { + log.trace( "automatically flushing session" ); + ctx.managedFlush(); + } + } + catch (RuntimeException re) { + //throwPersistenceException will mark the transaction as rollbacked + if ( re instanceof HibernateException ) { + throwPersistenceException( (HibernateException) re ); + } + else { + throwPersistenceException( new PersistenceException( re ) ); + } + } + } - public void afterCompletion(int status) { - if ( Status.STATUS_ROLLEDBACK == status - && transactionType == PersistenceUnitTransactionType.JTA ) { - if ( session.isOpen() ) { - session.clear(); + public void afterCompletion(int status) { + try { + if ( Status.STATUS_ROLLEDBACK == status + && transactionType == PersistenceUnitTransactionType.JTA ) { + if ( session.isOpen() ) { + session.clear(); + } + } + JoinableCMTTransaction joinable = (JoinableCMTTransaction) session.getTransaction(); + joinable.resetStatus(); } + catch (HibernateException e) { + throwPersistenceException( e ); + } } - JoinableJTATransaction joinable = (JoinableJTATransaction) session.getTransaction(); - joinable.resetStatus(); } - } - ); + ); + } } + catch (HibernateException he) { + throwPersistenceException( he ); + } } } @@ -388,8 +514,30 @@ tx = new TransactionImpl( this ); } - public PersistenceException throwPersistenceException(PersistenceException e) { + public void throwPersistenceException(PersistenceException e) { if ( ! ( e instanceof NoResultException || ( e instanceof NonUniqueResultException ) ) ) markAsRollback(); throw e; } + + public void throwPersistenceException(HibernateException e) { + if ( e instanceof StaleStateException ) { + throwPersistenceException( new OptimisticLockException( e ) ); + } + else if ( e instanceof ConstraintViolationException ) { + //FIXME this is bad cause ConstraintViolationException happens in other circumstances + throwPersistenceException( new EntityExistsException( e ) ); + } + else if ( e instanceof ObjectNotFoundException ) { + throwPersistenceException( new EntityNotFoundException( e ) ); + } + else if ( e instanceof org.hibernate.NonUniqueResultException ) { + throwPersistenceException( new NonUniqueResultException( e ) ); + } + else if ( e instanceof UnresolvableObjectException ) { + throwPersistenceException( new EntityNotFoundException( e ) ); + } + else { + throwPersistenceException( new PersistenceException( e ) ); + } + } } Modified: trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/Ejb3Configuration.java =================================================================== --- trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/Ejb3Configuration.java 2006-03-22 22:37:25 UTC (rev 9678) +++ trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/Ejb3Configuration.java 2006-03-22 23:21:44 UTC (rev 9679) @@ -47,7 +47,7 @@ import org.hibernate.ejb.packaging.JarVisitor; import org.hibernate.ejb.packaging.PersistenceMetadata; import org.hibernate.ejb.packaging.PersistenceXmlLoader; -import org.hibernate.ejb.transaction.JoinableJTATransactionFactory; +import org.hibernate.ejb.transaction.JoinableCMTTransactionFactory; import org.hibernate.ejb.util.LogHelper; import org.hibernate.engine.FilterDefinition; import org.hibernate.event.EventListeners; @@ -268,7 +268,7 @@ Properties properties = info.getProperties() != null ? info.getProperties() : new Properties(); - for ( Map.Entry entry : (Set<Map.Entry>) integration.keySet() ) { + for ( Map.Entry entry : (Set<Map.Entry>) integration.entrySet() ) { if ( entry.getKey() instanceof String && entry.getValue() instanceof String ) { properties.setProperty( (String) entry.getKey(), (String) entry.getValue() ); } @@ -667,7 +667,7 @@ //settings that always apply to a compliant EJB3 preparedProperties.setProperty( Environment.AUTOCOMMIT, "true" ); preparedProperties.setProperty( Environment.USE_IDENTIFIER_ROLLBACK, "false" ); - preparedProperties.setProperty( Environment.FLUSH_BEFORE_COMPLETION, "true" ); + preparedProperties.setProperty( Environment.FLUSH_BEFORE_COMPLETION, "false" ); preparedProperties.setProperty( HibernatePersistence.DISCARD_PC_ON_CLOSE, "false" ); //override the new defaults with the user defined ones @@ -678,7 +678,7 @@ ); boolean hasTxStrategy = StringHelper.isNotEmpty( preparedProperties.getProperty( Environment.TRANSACTION_STRATEGY ) ); if (! hasTxStrategy && transactionType == PersistenceUnitTransactionType.JTA) { - preparedProperties.setProperty( Environment.TRANSACTION_STRATEGY, JoinableJTATransactionFactory.class.getName() ); + preparedProperties.setProperty( Environment.TRANSACTION_STRATEGY, JoinableCMTTransactionFactory.class.getName() ); } else if (! hasTxStrategy && transactionType == PersistenceUnitTransactionType.RESOURCE_LOCAL) { preparedProperties.setProperty( Environment.TRANSACTION_STRATEGY, JDBCTransactionFactory.class.getName() ); @@ -686,6 +686,13 @@ else { new AssertionFailure("Unknown PersisntenceUnitTransactionType: " + transactionType); } + if (hasTxStrategy) { + log.warn("Overriding " + Environment.TRANSACTION_STRATEGY + " is dangerous, this might break the EJB3 specification implementation"); + } + if ( preparedProperties.getProperty( Environment.FLUSH_BEFORE_COMPLETION ).equals( "true" ) ) { + preparedProperties.setProperty( Environment.FLUSH_BEFORE_COMPLETION, "false" ); + log.warn("Defining " + Environment.FLUSH_BEFORE_COMPLETION + "=true ignored in HEM"); + } return preparedProperties; } Modified: trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/EntityManagerImpl.java =================================================================== --- trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/EntityManagerImpl.java 2006-03-22 22:37:25 UTC (rev 9678) +++ trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/EntityManagerImpl.java 2006-03-22 23:21:44 UTC (rev 9679) @@ -7,6 +7,7 @@ import org.hibernate.Session; import org.hibernate.SessionFactory; +import org.hibernate.HibernateException; import org.hibernate.engine.SessionImplementor; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -79,8 +80,14 @@ public boolean isOpen() { //adjustFlushMode(); //don't adjust, can't be done on closed EM - if (open) getSession().isOpen(); //to force enlistment in tx - return open; + try { + if (open) getSession().isOpen(); //to force enlistment in tx + return open; + } + catch (HibernateException he) { + throwPersistenceException(he); + return false; + } } } Modified: trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/HibernateEntityManagerImplementor.java =================================================================== --- trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/HibernateEntityManagerImplementor.java 2006-03-22 22:37:25 UTC (rev 9678) +++ trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/HibernateEntityManagerImplementor.java 2006-03-22 23:21:44 UTC (rev 9679) @@ -3,10 +3,13 @@ import javax.persistence.PersistenceException; +import org.hibernate.HibernateException; + /** * @author Emmanuel Bernard */ public interface HibernateEntityManagerImplementor extends HibernateEntityManager { boolean isTransactionInProgress(); - public PersistenceException throwPersistenceException(PersistenceException e); + public void throwPersistenceException(PersistenceException e); + public void throwPersistenceException(HibernateException e); } Modified: trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/QueryImpl.java =================================================================== --- trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/QueryImpl.java 2006-03-22 22:37:25 UTC (rev 9678) +++ trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/QueryImpl.java 2006-03-22 23:21:44 UTC (rev 9679) @@ -9,17 +9,17 @@ import javax.persistence.NoResultException; import javax.persistence.Query; import javax.persistence.TemporalType; +import static javax.persistence.TemporalType.*; import javax.persistence.TransactionRequiredException; -import static javax.persistence.TemporalType.*; import org.hibernate.CacheMode; import org.hibernate.FlushMode; -import org.hibernate.NonUniqueResultException; +import org.hibernate.HibernateException; import org.hibernate.SQLQuery; /** * @author <a href="mailto:ga...@hi...">Gavin King</a> - * @version $Revision$ + * @author Emmanuel Bernard */ public class QueryImpl implements Query, HibernateQuery { private org.hibernate.Query query; @@ -35,14 +35,27 @@ } public int executeUpdate() { - if ( ! em.isTransactionInProgress() ) { - throw em.throwPersistenceException( new TransactionRequiredException("Executing an update/delete query") ); + try { + if ( ! em.isTransactionInProgress() ) { + em.throwPersistenceException( new TransactionRequiredException("Executing an update/delete query") ); + return 0; + } + return query.executeUpdate(); } - return query.executeUpdate(); + catch (HibernateException he) { + em.throwPersistenceException(he); + return 0; + } } public List getResultList() { - return query.list(); + try { + return query.list(); + } + catch (HibernateException he) { + em.throwPersistenceException(he); + return null; + } } public Object getSingleResult() { @@ -55,9 +68,9 @@ return result; } - catch (NonUniqueResultException e) { - em.throwPersistenceException( new javax.persistence.NonUniqueResultException( e.getMessage() ) ); - return null; //for the compiler to stop complaining + catch (HibernateException he) { + em.throwPersistenceException(he); + return null; } } @@ -123,49 +136,73 @@ } public Query setParameter(String name, Object value) { - if ( value instanceof Collection ) { - query.setParameterList( name, (Collection) value ); + try { + if ( value instanceof Collection ) { + query.setParameterList( name, (Collection) value ); + } + else { + query.setParameter( name, value ); + } + return this; } - else { - query.setParameter( name, value ); + catch (HibernateException he) { + em.throwPersistenceException(he); + return null; } - return this; } public Query setParameter(String name, Date value, TemporalType temporalType) { - if ( temporalType == DATE ) { - query.setDate( name, value ); + try { + if ( temporalType == DATE ) { + query.setDate( name, value ); + } + else if ( temporalType == TIME ) { + query.setTime( name, value ); + } + else if ( temporalType == TIMESTAMP ) { + query.setTimestamp( name, value ); + } + return this; } - else if ( temporalType == TIME ) { - query.setTime( name, value ); + catch (HibernateException he) { + em.throwPersistenceException(he); + return null; } - else if ( temporalType == TIMESTAMP ) { - query.setTimestamp( name, value ); - } - return this; } public Query setParameter(String name, Calendar value, TemporalType temporalType) { - if ( temporalType == DATE ) { - query.setCalendarDate( name, value ); + try { + if ( temporalType == DATE ) { + query.setCalendarDate( name, value ); + } + else if ( temporalType == TIME ) { + throw new IllegalArgumentException( "not yet implemented" ); + } + else if ( temporalType == TIMESTAMP ) { + query.setCalendar( name, value ); + } + return this; } - else if ( temporalType == TIME ) { - throw new IllegalArgumentException( "not yet implemented" ); + catch (HibernateException he) { + em.throwPersistenceException(he); + return null; } - else if ( temporalType == TIMESTAMP ) { - query.setCalendar( name, value ); - } - return this; } public Query setParameter(int position, Object value) { - if ( isEJBQLQuery() ) { - this.setParameter( Integer.toString(position), value ); + try { + if ( isEJBQLQuery() ) { + this.setParameter( Integer.toString(position), value ); + } + else { + query.setParameter( position - 1, value ); + } + return this; } - else { - query.setParameter( position - 1, value ); + catch (HibernateException he) { + em.throwPersistenceException(he); + return null; } - return this; } private boolean isEJBQLQuery() { @@ -173,41 +210,53 @@ } public Query setParameter(int position, Date value, TemporalType temporalType) { - if ( isEJBQLQuery() ) { - String name = Integer.toString(position); - this.setParameter( name, value, temporalType ); - } - else { - if ( temporalType == DATE ) { - query.setDate( position - 1, value ); + try { + if ( isEJBQLQuery() ) { + String name = Integer.toString(position); + this.setParameter( name, value, temporalType ); } - else if ( temporalType == TIME ) { - query.setTime( position - 1, value ); + else { + if ( temporalType == DATE ) { + query.setDate( position - 1, value ); + } + else if ( temporalType == TIME ) { + query.setTime( position - 1, value ); + } + else if ( temporalType == TIMESTAMP ) { + query.setTimestamp( position - 1, value ); + } } - else if ( temporalType == TIMESTAMP ) { - query.setTimestamp( position - 1, value ); - } + return this; } - return this; + catch (HibernateException he) { + em.throwPersistenceException(he); + return null; + } } public Query setParameter(int position, Calendar value, TemporalType temporalType) { - if ( isEJBQLQuery() ) { - String name = Integer.toString(position); - this.setParameter( name, value, temporalType); - } - else { - if ( temporalType == DATE ) { - query.setCalendarDate( position - 1, value ); + try { + if ( isEJBQLQuery() ) { + String name = Integer.toString(position); + this.setParameter( name, value, temporalType); } - else if ( temporalType == TIME ) { - throw new IllegalArgumentException( "not yet implemented" ); + else { + if ( temporalType == DATE ) { + query.setCalendarDate( position - 1, value ); + } + else if ( temporalType == TIME ) { + throw new IllegalArgumentException( "not yet implemented" ); + } + else if ( temporalType == TIMESTAMP ) { + query.setCalendar( position - 1, value ); + } } - else if ( temporalType == TIMESTAMP ) { - query.setCalendar( position - 1, value ); - } + return this; } - return this; + catch (HibernateException he) { + em.throwPersistenceException(he); + return null; + } } public Query setFlushMode(FlushModeType flushMode) { Modified: trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/TransactionImpl.java =================================================================== --- trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/TransactionImpl.java 2006-03-22 22:37:25 UTC (rev 9678) +++ trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/TransactionImpl.java 2006-03-22 23:21:44 UTC (rev 9679) @@ -7,6 +7,7 @@ import org.hibernate.Session; import org.hibernate.Transaction; +import org.hibernate.HibernateException; /** * @author Gavin King @@ -27,12 +28,17 @@ } public void begin() { - rollbackOnly = false; - if ( tx != null && tx.isActive() ) { - throw new IllegalStateException( "Transaction already active" ); + try { + rollbackOnly = false; + if ( tx != null && tx.isActive() ) { + throw new IllegalStateException( "Transaction already active" ); + } + //entityManager.adjustFlushMode(); + tx = getSession().beginTransaction(); } - //entityManager.adjustFlushMode(); - tx = getSession().beginTransaction(); + catch (HibernateException he) { + entityManager.throwPersistenceException(he); + } } public void commit() { @@ -70,7 +76,7 @@ try { tx.rollback(); } - catch (RuntimeException e) { + catch (Exception e) { throw new PersistenceException("unexpected error when rollbacking", e); } finally { Modified: trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/packaging/PersistenceXmlLoader.java =================================================================== --- trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/packaging/PersistenceXmlLoader.java 2006-03-22 22:37:25 UTC (rev 9678) +++ trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/packaging/PersistenceXmlLoader.java 2006-03-22 23:21:44 UTC (rev 9679) @@ -15,9 +15,9 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.hibernate.cfg.EJB3DTDEntityResolver; import org.hibernate.ejb.HibernatePersistence; import org.hibernate.util.StringHelper; -import org.hibernate.cfg.EJB3DTDEntityResolver; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; @@ -51,8 +51,8 @@ docBuilderFactory.setNamespaceAware( true ); try { //otherwise Xerces fails in validation - docBuilderFactory.setAttribute( "http://apache.org/xml/features/validation/schema", true); - } + docBuilderFactory.setAttribute( "http://apache.org/xml/features/validation/schema", true ); + } catch (IllegalArgumentException e) { docBuilderFactory.setValidating( false ); docBuilderFactory.setNamespaceAware( false ); @@ -60,9 +60,9 @@ InputSource source = new InputSource( is ); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); docBuilder.setEntityResolver( resolver ); - docBuilder.setErrorHandler( new ErrorLogger("XML InputStream", errors, resolver) ); + docBuilder.setErrorHandler( new ErrorLogger( "XML InputStream", errors, resolver ) ); Document doc = docBuilder.parse( source ); - if ( errors.size() != 0 ) { + if ( errors.size() != 0 ) { throw new PersistenceException( "invalid persistence.xml", (Throwable) errors.get( 0 ) ); } return doc; @@ -82,19 +82,19 @@ PersistenceMetadata metadata = parsePersistenceUnit( element ); //override properties of metadata if needed String provider = (String) overrides.get( HibernatePersistence.PROVIDER ); - if (provider != null) { + if ( provider != null ) { metadata.setProvider( provider ); } String transactionType = (String) overrides.get( HibernatePersistence.TRANSACTION_TYPE ); - if (transactionType != null) { + if ( transactionType != null ) { metadata.setTransactionType( PersistenceXmlLoader.getTransactionType( transactionType ) ); } String dataSource = (String) overrides.get( HibernatePersistence.JTA_DATASOURCE ); - if (dataSource != null) { + if ( dataSource != null ) { metadata.setJtaDatasource( dataSource ); } dataSource = (String) overrides.get( HibernatePersistence.NON_JTA_DATASOURCE ); - if (dataSource != null) { + if ( dataSource != null ) { metadata.setNonJtaDatasource( dataSource ); } Properties properties = metadata.getProps(); @@ -176,33 +176,44 @@ } public static PersistenceUnitTransactionType getTransactionType(String elementContent) { - if (StringHelper.isEmpty( elementContent ) ) return PersistenceUnitTransactionType.JTA; - else if ( elementContent.equalsIgnoreCase( "JTA" ) ) return PersistenceUnitTransactionType.JTA; - else if ( elementContent.equalsIgnoreCase( "RESOURCE_LOCAL" ) ) return PersistenceUnitTransactionType.RESOURCE_LOCAL; - else throw new PersistenceException("Unknown TransactionType: " + elementContent); + if ( StringHelper.isEmpty( elementContent ) ) { + return PersistenceUnitTransactionType.JTA; + } + else if ( elementContent.equalsIgnoreCase( "JTA" ) ) { + return PersistenceUnitTransactionType.JTA; + } + else if ( elementContent.equalsIgnoreCase( "RESOURCE_LOCAL" ) ) { + return PersistenceUnitTransactionType.RESOURCE_LOCAL; + } + else { + throw new PersistenceException( "Unknown TransactionType: " + elementContent ); + } } public static class ErrorLogger implements ErrorHandler { private String file; private List errors; - private EntityResolver resolver; - ErrorLogger(String file, List errors, EntityResolver resolver) { - this.file=file; + private EntityResolver resolver; + + ErrorLogger(String file, List errors, EntityResolver resolver) { + this.file = file; this.errors = errors; - this.resolver = resolver; - } + this.resolver = resolver; + } + public void error(SAXParseException error) { - if (resolver instanceof EJB3DTDEntityResolver) - { - if (((EJB3DTDEntityResolver)resolver).isResolved() == false) return; - } - log.error( "Error parsing XML: " + file + '(' + error.getLineNumber() + ") " + error.getMessage() ); - errors.add(error); + if ( resolver instanceof EJB3DTDEntityResolver ) { + if ( ( (EJB3DTDEntityResolver) resolver ).isResolved() == false ) return; + } + log.error( "Error parsing XML: " + file + '(' + error.getLineNumber() + ") " + error.getMessage() ); + errors.add( error ); } + public void fatalError(SAXParseException error) { - log.error( "Error parsing XML: " + file + '(' + error.getLineNumber() + ") " + error.getMessage() ); - errors.add(error); + log.error( "Error parsing XML: " + file + '(' + error.getLineNumber() + ") " + error.getMessage() ); + errors.add( error ); } + public void warning(SAXParseException warn) { log.warn( "Warning parsing XML: " + file + '(' + warn.getLineNumber() + ") " + warn.getMessage() ); } Copied: trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/transaction/JoinableCMTTransaction.java (from rev 9647, trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/transaction/JoinableJTATransaction.java) =================================================================== --- trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/transaction/JoinableJTATransaction.java 2006-03-17 11:09:10 UTC (rev 9647) +++ trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/transaction/JoinableCMTTransaction.java 2006-03-22 23:21:44 UTC (rev 9679) @@ -0,0 +1,84 @@ +//$Id: $ +package org.hibernate.ejb.transaction; + +import javax.transaction.SystemException; + +import org.hibernate.HibernateException; +import org.hibernate.TransactionException; +import org.hibernate.jdbc.JDBCContext; +import org.hibernate.transaction.CMTTransaction; +import org.hibernate.transaction.TransactionFactory; +import org.hibernate.util.JTAHelper; + +/** + * Implements a joinable transaction. Until the transaction is marked for joined, the TM.isTransactionInProgress() + * must return false + * + * @author Emmanuel Bernard + */ +public class JoinableCMTTransaction extends CMTTransaction { + private JoinStatus status; + public JoinableCMTTransaction( JDBCContext jdbcContext, TransactionFactory.Context transactionContext ) { + super( jdbcContext, transactionContext ); + status = JoinStatus.MARKED_FOR_JOINED; + tryJoiningTransaction(); + } + + public boolean isTransactionInProgress( + JDBCContext jdbcContext, + TransactionFactory.Context transactionContext) { + try { + return JTAHelper.isTransactionInProgress( + transactionContext.getFactory().getTransactionManager().getTransaction() + ); + } + catch( SystemException se ) { + throw new TransactionException( "Unable to check transaction status", se ); + } + } + + void tryJoiningTransaction() { + if (status == JoinStatus.MARKED_FOR_JOINED) { + if ( isTransactionInProgress(jdbcContext, transactionContext) ) { + status = JoinStatus.JOINED; + } + else { + status = JoinStatus.NOT_JOINED; + } + } + } + + @Override + public void begin() throws HibernateException { + super.begin(); + status = JoinStatus.JOINED; + } + + @Override + public void commit() throws HibernateException { + /* this method is not supposed to be called + * it breaks the flushBeforeCompletion flag optimizeation + * regarding flushing skip. + * In its current form, it will generate too much flush() calls + */ + super.commit(); + } + + + + public JoinStatus getStatus() { + return status; + } + + public void resetStatus() { status = JoinStatus.NOT_JOINED; } + + public void markForJoined() { + if (status != JoinStatus.JOINED) status = JoinStatus.MARKED_FOR_JOINED; + } + + public static enum JoinStatus { + NOT_JOINED, + MARKED_FOR_JOINED, + JOINED + } +} Copied: trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/transaction/JoinableCMTTransactionFactory.java (from rev 9647, trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/transaction/JoinableJTATransactionFactory.java) =================================================================== --- trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/transaction/JoinableJTATransactionFactory.java 2006-03-17 11:09:10 UTC (rev 9647) +++ trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/transaction/JoinableCMTTransactionFactory.java 2006-03-22 23:21:44 UTC (rev 9679) @@ -0,0 +1,30 @@ +//$Id: $ +package org.hibernate.ejb.transaction; + +import org.hibernate.HibernateException; +import org.hibernate.Transaction; +import org.hibernate.jdbc.JDBCContext; +import org.hibernate.transaction.CMTTransactionFactory; + +/** + * A transaction is in progress if the underlying JTA tx is in progress and if the Tx is marked as + * MARKED_FOR_JOINED + * + * @author Emmanuel Bernard + */ +public class JoinableCMTTransactionFactory extends CMTTransactionFactory { + public Transaction createTransaction(JDBCContext jdbcContext, Context transactionContext) + throws HibernateException { + return new JoinableCMTTransaction( jdbcContext, transactionContext ); + } + + @Override + public boolean isTransactionInProgress( + JDBCContext jdbcContext, Context transactionContext, Transaction transaction + ) { + if ( transaction == null ) return false; //should not happen though + JoinableCMTTransaction joinableCMTTransaction = ( (JoinableCMTTransaction) transaction ); + joinableCMTTransaction.tryJoiningTransaction(); + return joinableCMTTransaction.isTransactionInProgress(jdbcContext, transactionContext); + } +} Deleted: trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/transaction/JoinableJTATransaction.java =================================================================== --- trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/transaction/JoinableJTATransaction.java 2006-03-22 22:37:25 UTC (rev 9678) +++ trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/transaction/JoinableJTATransaction.java 2006-03-22 23:21:44 UTC (rev 9679) @@ -1,89 +0,0 @@ -//$Id: $ -package org.hibernate.ejb.transaction; - -import javax.naming.InitialContext; -import javax.transaction.SystemException; -import javax.transaction.UserTransaction; - -import org.hibernate.HibernateException; -import org.hibernate.TransactionException; -import org.hibernate.jdbc.JDBCContext; -import org.hibernate.transaction.JTATransaction; -import org.hibernate.transaction.TransactionFactory; -import org.hibernate.util.JTAHelper; - -/** - * Implements a joinable transaction. Until the transaction is marked for joined, the TM.isTransactionInProgress() - * must return false - * If a - * @author Emmanuel Bernard - */ -public class JoinableJTATransaction extends JTATransaction { - private JoinStatus status; - public JoinableJTATransaction( - InitialContext context, String utName, JDBCContext jdbcContext, - TransactionFactory.Context transactionContext - ) { - super( context, utName, jdbcContext, transactionContext ); - status = JoinStatus.MARKED_FOR_JOINED; - tryJoiningTransaction(); - } - - void tryJoiningTransaction() { - if (status == JoinStatus.MARKED_FOR_JOINED) { - try { - UserTransaction ut = getUserTransaction(); - if ( ut != null && JTAHelper.isInProgress( ut.getStatus() ) ) { - status = JoinStatus.JOINED; - } - else { - status = JoinStatus.NOT_JOINED; - } - } - catch( SystemException se ) { - throw new TransactionException( "Unable to check transaction status", se ); - } - } - } - - @Override - public void begin() throws HibernateException { - super.begin(); - status = JoinStatus.JOINED; - } - - public JoinStatus getStatus() { - return status; - } - - public void resetStatus() { status = JoinStatus.NOT_JOINED; } - - public void markForJoined() { - if (status != JoinStatus.JOINED) status = JoinStatus.MARKED_FOR_JOINED; - } - - public boolean isTransactionInProgress() { - if (status != JoinableJTATransaction.JoinStatus.JOINED) { - return false; - } - try { - UserTransaction ut = getUserTransaction(); - if ( ut != null && JTAHelper.isInProgress( ut.getStatus() ) ) { - return true; - } - else { - resetStatus(); - return false; - } - } - catch( SystemException se ) { - throw new TransactionException( "Unable to check transaction status", se ); - } - } - - public static enum JoinStatus { - NOT_JOINED, - MARKED_FOR_JOINED, - JOINED - } -} Deleted: trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/transaction/JoinableJTATransactionFactory.java =================================================================== --- trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/transaction/JoinableJTATransactionFactory.java 2006-03-22 22:37:25 UTC (rev 9678) +++ trunk/HibernateExt/ejb/src/java/org/hibernate/ejb/transaction/JoinableJTATransactionFactory.java 2006-03-22 23:21:44 UTC (rev 9679) @@ -1,31 +0,0 @@ -//$Id: $ -package org.hibernate.ejb.transaction; - -import org.hibernate.HibernateException; -import org.hibernate.Transaction; -import org.hibernate.jdbc.JDBCContext; -import org.hibernate.transaction.JTATransactionFactory; - -/** - * A transaction is in progress if the underlying JTA tx is in progress and if the Tx is marked as - * MARKED_FOR_JOINED - * - * @author Emmanuel Bernard - */ -public class JoinableJTATransactionFactory extends JTATransactionFactory { - public Transaction createTransaction(JDBCContext jdbcContext, Context transactionContext) - throws HibernateException { - return new JoinableJTATransaction( context, utName, jdbcContext, transactionContext ); - } - - @Override - public boolean isTransactionInProgress( - JDBCContext jdbcContext, Context transactionContext, Transaction transaction - ) { - if ( !super.isTransactionInProgress( jdbcContext, transactionContext, transaction ) ) return false; - if ( transaction == null ) return false; //should not happen though - JoinableJTATransaction joinableJTATransaction = ( (JoinableJTATransaction) transaction ); - joinableJTATransaction.tryJoiningTransaction(); - return joinableJTATransaction.isTransactionInProgress(); - } -} Modified: trunk/HibernateExt/ejb/src/test/org/hibernate/ejb/test/EntityManagerTest.java =================================================================== --- trunk/HibernateExt/ejb/src/test/org/hibernate/ejb/test/EntityManagerTest.java 2006-03-22 22:37:25 UTC (rev 9678) +++ trunk/HibernateExt/ejb/src/test/org/hibernate/ejb/test/EntityManagerTest.java 2006-03-22 23:21:44 UTC (rev 9679) @@ -11,11 +11,11 @@ import java.util.Map; import javax.persistence.EntityManager; import javax.persistence.FlushModeType; +import javax.persistence.PersistenceException; import javax.persistence.Query; import org.hibernate.FlushMode; import org.hibernate.HibernateException; -import org.hibernate.QueryException; import org.hibernate.ejb.HibernateEntityManager; import org.hibernate.ejb.HibernateEntityManagerFactory; import org.hibernate.stat.Statistics; @@ -263,7 +263,7 @@ Query query = em.createQuery("SELECT p FETCH JOIN p.distributors FROM Item p"); query.getSingleResult(); } - catch (QueryException e) { + catch (PersistenceException e) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream( stream ); out.writeObject( e ); @@ -272,13 +272,13 @@ stream.close(); ByteArrayInputStream byteIn = new ByteArrayInputStream( serialized ); ObjectInputStream in = new ObjectInputStream(byteIn); - QueryException deserializedException = (QueryException) in.readObject(); + PersistenceException deserializedException = (PersistenceException) in.readObject(); in.close(); byteIn.close(); - assertNull( deserializedException.getCause() ); - assertNull( e.getCause() ); + assertNull( deserializedException.getCause().getCause() ); + assertNull( e.getCause().getCause() ); } - em.getTransaction().commit(); + em.getTransaction().rollback(); em.close(); Modified: trunk/HibernateExt/ejb/src/test/org/hibernate/ejb/test/ejb3configuration/EntityManagerSerializationTest.java =================================================================== --- trunk/HibernateExt/ejb/src/test/org/hibernate/ejb/test/ejb3configuration/EntityManagerSerializationTest.java 2006-03-22 22:37:25 UTC (rev 9678) +++ trunk/HibernateExt/ejb/src/test/org/hibernate/ejb/test/ejb3configuration/EntityManagerSerializationTest.java 2006-03-22 23:21:44 UTC (rev 9679) @@ -68,7 +68,7 @@ em.getTransaction().begin(); item = em.find( Item.class, item.getName() ); item.setDescr( item.getDescr() + "-Amsterdam"); - cat = em.find(Cat.class, cat.getId() ); + cat = (Cat) em.createQuery( "from " + Cat.class.getName() ).getSingleResult(); cat.setLength( 34 ); em.flush(); em.remove( item ); Deleted: trunk/HibernateExt/ejb/src/test/org/hibernate/ejb/test/ops/CreateTest.java =================================================================== --- trunk/HibernateExt/ejb/src/test/org/hibernate/ejb/test/ops/CreateTest.java 2006-03-22 22:37:25 UTC (rev 9678) +++ trunk/HibernateExt/ejb/src/test/org/hibernate/ejb/test/ops/CreateTest.java 2006-03-22 23:21:44 UTC (rev 9679) @@ -1,223 +0,0 @@ -//$Id$ -package org.hibernate.ejb.test.ops; - -import java.util.ArrayList; -import java.util.Collection; - -import junit.framework.Test; -import junit.framework.TestSuite; -import org.hibernate.PersistentObjectException; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.cfg.Configuration; -import org.hibernate.cfg.Environment; -import org.hibernate.ejb.test.EJB3TestCase; -import org.hibernate.exception.ConstraintViolationException; - -/** - * @author Gavin King - */ -public class CreateTest extends EJB3TestCase { - - public CreateTest(String str) { - super( str ); - } - - public void testCreateTree() { - - clearCounts(); - - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Node root = new Node( "root" ); - Node child = new Node( "child" ); - root.addChild( child ); - s.persist( root ); - tx.commit(); - s.close(); - - assertInsertCount( 2 ); - assertUpdateCount( 0 ); - - s = openSession(); - tx = s.beginTransaction(); - root = (Node) s.get( Node.class, "root" ); - Node child2 = new Node( "child2" ); - root.addChild( child2 ); - tx.commit(); - s.close(); - - assertInsertCount( 3 ); - assertUpdateCount( 0 ); - } - - public void testCreateTreeWithGeneratedId() { - - clearCounts(); - - Session s = openSession(); - Transaction tx = s.beginTransaction(); - NumberedNode root = new NumberedNode( "root" ); - NumberedNode child = new NumberedNode( "child" ); - root.addChild( child ); - s.persist( root ); - tx.commit(); - s.close(); - - assertInsertCount( 2 ); - assertUpdateCount( 0 ); - - s = openSession(); - tx = s.beginTransaction(); - root = (NumberedNode) s.get( NumberedNode.class, new Long( root.getId() ) ); - NumberedNode child2 = new NumberedNode( "child2" ); - root.addChild( child2 ); - tx.commit(); - s.close(); - - assertInsertCount( 3 ); - assertUpdateCount( 0 ); - } - - public void testCreateException() { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Node dupe = new Node( "dupe" ); - s.persist( dupe ); - s.persist( dupe ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - s.persist( dupe ); - try { - tx.commit(); - assertFalse( true ); - } - catch (ConstraintViolationException cve) { - //verify that an exception is thrown! - } - tx.rollback(); - s.close(); - - Node nondupe = new Node( "nondupe" ); - nondupe.addChild( dupe ); - - s = openSession(); - tx = s.beginTransaction(); - s.persist( nondupe ); - try { - tx.commit(); - assertFalse( true ); - } - catch (ConstraintViolationException cve) { - //verify that an exception is thrown! - } - tx.rollback(); - s.close(); - } - - public void testCreateExceptionWithGeneratedId() { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - NumberedNode dupe = new NumberedNode( "dupe" ); - s.persist( dupe ); - s.persist( dupe ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - try { - s.persist( dupe ); - assertFalse( true ); - } - catch (PersistentObjectException poe) { - //verify that an exception is thrown! - } - tx.rollback(); - s.close(); - - NumberedNode nondupe = new NumberedNode( "nondupe" ); - nondupe.addChild( dupe ); - - s = openSession(); - tx = s.beginTransaction(); - try { - s.persist( nondupe ); - assertFalse( true ); - } - catch (PersistentObjectException poe) { - //verify that an exception is thrown! - } - tx.rollback(); - s.close(); - } - - public void testBasic() throws Exception { - Session s; - Transaction tx; - s = openSession(); - tx = s.beginTransaction(); - Employer er = new Employer(); - Employee ee = new Employee(); - s.persist( ee ); - Collection erColl = new ArrayList(); - Collection eeColl = new ArrayList(); - erColl.add( ee ); - eeColl.add( er ); - er.setEmployees( erColl ); - ee.setEmployers( eeColl ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - er = (Employer) s.load( Employer.class, er.getId() ); - assertNotNull( er ); - assertNotNull( er.getEmployees() ); - assertEquals( 1, er.getEmployees().size() ); - Employee eeFromDb = (Employee) er.getEmployees().iterator().next(); - assertEquals( ee.getId(), eeFromDb.getId() ); - tx.commit(); - s.close(); - } - - private void clearCounts() { - getSessions().getStatistics().clear(); - } - - private void assertInsertCount(int count) { - int inserts = (int) getSessions().getStatistics().getEntityInsertCount(); - assertEquals( count, inserts ); - } - - private void assertUpdateCount(int count) { - int updates = (int) getSessions().getStatistics().getEntityUpdateCount(); - assertEquals( count, updates ); - } - - protected void configure(Configuration cfg) { - super.configure( cfg ); - cfg.setProperty( Environment.GENERATE_STATISTICS, "true" ); - cfg.setProperty( Environment.STATEMENT_BATCH_SIZE, "0" ); - } - - protected String[] getMappings() { - return new String[]{ - "ops/Node.hbm.xml", - "ops/Employer.hbm.xml" - }; - } - - public static Test suite() { - return new TestSuite( CreateTest.class ); - } - - public String getCacheConcurrencyStrategy() { - return null; - } - -} - Copied: trunk/HibernateExt/ejb/src/test/org/hibernate/ejb/test/ops/PersistTest.java (from rev 9647, trunk/HibernateExt/ejb/src/test/org/hibernate/ejb/test/ops/CreateTest.java) =================================================================== --- trunk/HibernateExt/ejb/src/test/org/hibernate/ejb/test/ops/CreateTest.java 2006-03-17 11:09:10 UTC (rev 9647) +++ trunk/HibernateExt/ejb/src/test/org/hibernate/ejb/test/ops/PersistTest.java 2006-03-22 23:21:44 UTC (rev 9679) @@ -0,0 +1,223 @@ +//$Id$ +package org.hibernate.ejb.test.ops; + +import java.util.ArrayList; +import java.util.Collection; + +import junit.framework.Test; +import junit.framework.TestSuite; +import org.hibernate.PersistentObjectException; +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.hibernate.cfg.Configuration; +import org.hibernate.cfg.Environment; +import org.hibernate.ejb.test.EJB3TestCase; +import org.hibernate.exception.ConstraintViolationException; + +/** + * @author Gavin King + */ +public class PersistTest extends EJB3TestCase { + + public PersistTest(String str) { + super( str ); + } + + public void testCreateTree() { + + clearCounts(); + + Session s = openSession(); + Transaction tx = s.beginTransaction(); + Node root = new Node( "root" ); + Node child = new Node( "child" ); + root.addChild( child ); + s.persist( root ); + tx.commit(); + s.close(); + + assertInsertCount( 2 ); + assertUpdateCount( 0 ); + + s = openSession(); + tx = s.beginTransaction(); + root = (Node) s.get( Node.class, "root" ); + Node child2 = new Node( "child2" ); + root.addChild( child2 ); + tx.commit(); + s.close(); + + assertInsertCount( 3 ); + assertUpdateCount( 0 ); + } + + public void testCreateTreeWithGeneratedId() { + + clearCounts(); + + Session s = openSession(); + Transaction tx = s.beginTransaction(); + NumberedNode root = new NumberedNode( "root" ); + NumberedNode child = new NumberedNode( "child" ); + root.addChild( child ); + s.persist( root ); + tx.commit(); + s.close(); + + assertInsertCount( 2 ); + assertUpdateCount( 0 ); + + s = openSession(); + tx = s.beginTransaction(); + root = (NumberedNode) s.get( NumberedNode.class, new Long( root.getId() ) ); + NumberedNode child2 = new NumberedNode( "child2" ); + root.addChild( child2 ); + tx.commit(); + s.close(); + + assertInsertCount( 3 ); + assertUpdateCount( 0 ); + } + + public void testCreateException() { + Session s = openSession(); + Transaction tx = s.beginTransaction(); + Node dupe = new Node( "dupe" ); + s.persist( dupe ); + s.persist( dupe ); + tx.commit(); + s.close(); + + s = openSession(); + tx = s.beginTransaction(); + s.persist( dupe ); + try { + tx.commit(); + fail("Cannot persist() twice the same entity"); + } + catch (ConstraintViolationException cve) { + //verify that an exception is thrown! + } + tx.rollback(); + s.close(); + + Node nondupe = new Node( "nondupe" ); + nondupe.addChild( dupe ); + + s = openSession(); + tx = s.beginTransaction(); + s.persist( nondupe ); + try { + tx.commit(); + assertFalse( true ); + } + catch (ConstraintViolationException cve) { + //verify that an exception is thrown! + } + tx.rollback(); + s.close(); + } + + public void testCreateExceptionWithGeneratedId() { + Session s = openSession(); + Transaction tx = s.beginTransaction(); + NumberedNode dupe = new NumberedNode( "dupe" ); + s.persist( dupe ); + s.persist( dupe ); + tx.commit(); + s.close(); + + s = openSession(); + tx = s.beginTransaction(); + try { + s.persist( dupe ); + assertFalse( true ); + } + catch (PersistentObjectException poe) { + //verify that an exception is thrown! + } + tx.rollback(); + s.close(); + + NumberedNode nondupe = new NumberedNode( "nondupe" ); + nondupe.addChild( dupe ); + + s = openSession(); + tx = s.beginTransaction(); + try { + s.persist( nondupe ); + assertFalse( true ); + } + catch (PersistentObjectException poe) { + //verify that an exception is thrown! + } + tx.rollback(); + s.close(); + } + + public void testBasic() throws Exception { + Session s; + Transaction tx; + s = openSession(); + tx = s.beginTransaction(); + Employer er = new Employer(); + Employee ee = new Employee(); + s.persist( ee ); + Collection erColl = new ArrayList(); + Collection eeColl = new ArrayList(); + erColl.add( ee ); + eeColl.add( er ); + er.setEmployees( erColl ); + ee.setEmployers( eeColl ); + tx.commit(); + s.close(); + + s = openSession(); + tx = s.beginTransaction(); + er = (Employer) s.load( Employer.class, er.getId() ); + assertNotNull( er ); + assertNotNull( er.getEmployees() ); + assertEquals( 1, er.getEmployees().size() ); + Employee eeFromDb = (Employee) er.getEmployees().iterator().next(); + assertEquals( ee.getId(), eeFromDb.getId() ); + tx.commit(); + s.close(); + } + + private void clearCounts() { + getSessions().getStatistics().clear(); + } + + private void assertInsertCount(int count) { + int inserts = (int) getSessions().getStatistics().getEntityInsertCount(); + assertEquals( count, inserts ); + } + + private void assertUpdateCount(int count) { + int updates = (int) getSessions().getStatistics().getEntityUpdateCount(); + assertEquals( count, updates ); + } + + protected void configure(Configuration cfg) { + super.configure( cfg ); + cfg.setProperty( Environment.GENERATE_STATISTICS, "true" ); + cfg.setProperty( Environment.STATEMENT_BATCH_SIZE, "0" ); + } + + protected String[] getMappings() { + return new String[]{ + "ops/Node.hbm.xml", + "ops/Employer.hbm.xml" + }; + } + + public static Test suite() { + return new TestSuite( PersistTest.class ); + } + + public String getCacheConcurrencyStrategy() { + return null; + } + +} + Property changes on: trunk/HibernateExt/ejb/src/test/org/hibernate/ejb/test/ops/PersistTest.java ___________________________________________________________________ Name: svn:executable + * Name: svn:keywords + Author Date Id Revision Name: svn:eol-style + native |