Hibernate SVN: r18055 - core/branches/Branch_3_2_4_SP1_CP/test/org/hibernate/test/filter.
by hibernate-commits@lists.jboss.org
Author: stliu
Date: 2009-11-25 01:06:17 -0500 (Wed, 25 Nov 2009)
New Revision: 18055
Modified:
core/branches/Branch_3_2_4_SP1_CP/test/org/hibernate/test/filter/DynamicFilterTest.java
Log:
JBPAPP-3098 HHH-4065 - remove annotations, due to this will be compiled to 1.4 compatible
Modified: core/branches/Branch_3_2_4_SP1_CP/test/org/hibernate/test/filter/DynamicFilterTest.java
===================================================================
--- core/branches/Branch_3_2_4_SP1_CP/test/org/hibernate/test/filter/DynamicFilterTest.java 2009-11-25 00:05:08 UTC (rev 18054)
+++ core/branches/Branch_3_2_4_SP1_CP/test/org/hibernate/test/filter/DynamicFilterTest.java 2009-11-25 06:06:17 UTC (rev 18055)
@@ -37,7 +37,6 @@
*
* @author Steve
*/
-@SuppressWarnings({ "WhileLoopReplaceableByForEach", "unchecked" })
public class DynamicFilterTest extends FunctionalTestCase {
public DynamicFilterTest(String testName) {
15 years
Hibernate SVN: r18054 - core/trunk/core/src/main/java/org/hibernate.
by hibernate-commits@lists.jboss.org
Author: smarlow(a)redhat.com
Date: 2009-11-24 19:05:08 -0500 (Tue, 24 Nov 2009)
New Revision: 18054
Modified:
core/trunk/core/src/main/java/org/hibernate/Session.java
Log:
HHH-4546 add JPA 2.0 locking. Javadoc change.
Modified: core/trunk/core/src/main/java/org/hibernate/Session.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/Session.java 2009-11-24 23:59:50 UTC (rev 18053)
+++ core/trunk/core/src/main/java/org/hibernate/Session.java 2009-11-25 00:05:08 UTC (rev 18054)
@@ -552,8 +552,9 @@
public void lock(String entityName, Object object, LockMode lockMode) throws HibernateException;
/**
- * Build a lockRequest that specifies the LockMode, pessimistic lock timeout and lock scope.
- * timeout and scope is ignored for optimistic locking.
+ * Build a LockRequest that specifies the LockMode, pessimistic lock timeout and lock scope.
+ * timeout and scope is ignored for optimistic locking. After building the LockRequest,
+ * call LockRequest.lock to perform the requested locking.
*
* Use: session.buildLockRequest().
* setLockMode(LockMode.PESSIMISTIC_WRITE).setTimeOut(1000 * 60).lock(entity);
15 years
Hibernate SVN: r18053 - in core/trunk: core/src/main/java/org/hibernate/engine and 9 other directories.
by hibernate-commits@lists.jboss.org
Author: smarlow(a)redhat.com
Date: 2009-11-24 18:59:50 -0500 (Tue, 24 Nov 2009)
New Revision: 18053
Added:
core/trunk/core/src/main/java/org/hibernate/LockOptions.java
Removed:
core/trunk/core/src/main/java/org/hibernate/LockRequest.java
Modified:
core/trunk/core/src/main/java/org/hibernate/Session.java
core/trunk/core/src/main/java/org/hibernate/engine/CascadingAction.java
core/trunk/core/src/main/java/org/hibernate/event/LoadEvent.java
core/trunk/core/src/main/java/org/hibernate/event/LockEvent.java
core/trunk/core/src/main/java/org/hibernate/event/RefreshEvent.java
core/trunk/core/src/main/java/org/hibernate/event/def/AbstractLockUpgradeEventListener.java
core/trunk/core/src/main/java/org/hibernate/event/def/DefaultLoadEventListener.java
core/trunk/core/src/main/java/org/hibernate/event/def/DefaultLockEventListener.java
core/trunk/core/src/main/java/org/hibernate/event/def/DefaultRefreshEventListener.java
core/trunk/core/src/main/java/org/hibernate/impl/SessionImpl.java
core/trunk/core/src/main/java/org/hibernate/loader/AbstractEntityJoinWalker.java
core/trunk/core/src/main/java/org/hibernate/loader/entity/BatchingEntityLoader.java
core/trunk/core/src/main/java/org/hibernate/loader/entity/EntityJoinWalker.java
core/trunk/core/src/main/java/org/hibernate/loader/entity/EntityLoader.java
core/trunk/core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java
core/trunk/core/src/main/java/org/hibernate/persister/entity/EntityPersister.java
core/trunk/core/src/main/java/org/hibernate/util/ArrayHelper.java
core/trunk/entitymanager/src/main/java/org/hibernate/ejb/AbstractEntityManagerImpl.java
core/trunk/testsuite/src/test/java/org/hibernate/test/legacy/CustomPersister.java
Log:
HHH-4546 add JPA 2.0 locking. Introduce LockOptions as the wrapper and session.buildLockRequest() (replaces session.lock()).
Copied: core/trunk/core/src/main/java/org/hibernate/LockOptions.java (from rev 18016, core/trunk/core/src/main/java/org/hibernate/LockRequest.java)
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/LockOptions.java (rev 0)
+++ core/trunk/core/src/main/java/org/hibernate/LockOptions.java 2009-11-24 23:59:50 UTC (rev 18053)
@@ -0,0 +1,114 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2009, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ *
+ */
+package org.hibernate;
+
+/**
+ * Contains locking details (LockMode, Timeout and Scope).
+ *
+ * @author Scott Marlow
+ */
+public class LockOptions
+{
+
+ public static final int NO_WAIT = 0;
+ public static final int WAIT_FOREVER = -1;
+
+ private LockMode lockMode = LockMode.NONE;
+
+ private int timeout = WAIT_FOREVER; // timeout in milliseconds, 0 = no wait, -1 = wait indefinitely
+
+ private boolean scope=false;// if true, cascade (pessimistic only) lock to collections and relationships
+ // owned by the entity.
+
+ public LockOptions() {
+
+ }
+
+
+ public LockOptions( LockMode lockMode) {
+ this.lockMode = lockMode;
+ }
+
+ /**
+ * Get the lock mode.
+ * @return the lock mode.
+ */
+ public LockMode getLockMode() {
+ return lockMode;
+ }
+
+ /**
+ * Specify the LockMode to be used. The default is LockMode.none.
+ *
+ * @param lockMode
+ * @return this LockRequest instance for operation chaining.
+ */
+ public LockOptions setLockMode(LockMode lockMode) {
+ this.lockMode = lockMode;
+ return this;
+ }
+
+ /**
+ * Get the timeout setting.
+ *
+ * @return timeout in milliseconds, -1 for indefinite wait and 0 for no wait.
+ */
+ public int getTimeOut() {
+ return timeout;
+ }
+
+ /**
+ * Specify the pessimistic lock timeout (check if your dialect supports this option).
+ * The default pessimistic lock behavior is to wait forever for the lock.
+ *
+ * @param timeout is time in milliseconds to wait for lock. -1 means wait forever and 0 means no wait.
+ * @return this LockRequest instance for operation chaining.
+ */
+ public LockOptions setTimeOut(int timeout) {
+ this.timeout = timeout;
+ return this;
+ }
+
+ /**
+ * Check if locking is cascaded to owned collections and relationships.
+ * @return true if locking will be extended to owned collections and relationships.
+ */
+ public boolean getScope() {
+ return scope;
+ }
+
+ /**
+ * Specify if LockMode should be cascaded to owned collections and relationships.
+ * The association must be mapped with <tt>cascade="lock" for scope=true to work.
+ *
+ * @param scope
+ * @return
+ */
+ public LockOptions setScope(boolean scope) {
+ this.scope = scope;
+ return this;
+ }
+
+}
Deleted: core/trunk/core/src/main/java/org/hibernate/LockRequest.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/LockRequest.java 2009-11-24 22:28:05 UTC (rev 18052)
+++ core/trunk/core/src/main/java/org/hibernate/LockRequest.java 2009-11-24 23:59:50 UTC (rev 18053)
@@ -1,115 +0,0 @@
-/*
- * Hibernate, Relational Persistence for Idiomatic Java
- *
- * Copyright (c) 2009, Red Hat Middleware LLC or third-party contributors as
- * indicated by the @author tags or express copyright attribution
- * statements applied by the authors. All third-party contributions are
- * distributed under license by Red Hat Middleware LLC.
- *
- * This copyrighted material is made available to anyone wishing to use, modify,
- * copy, or redistribute it subject to the terms and conditions of the GNU
- * Lesser General Public License, as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
- * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
- * for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this distribution; if not, write to:
- * Free Software Foundation, Inc.
- * 51 Franklin Street, Fifth Floor
- * Boston, MA 02110-1301 USA
- *
- */
-package org.hibernate;
-
-/**
- * Contains locking details (LockMode, Timeout and Scope).
- *
- * @author Scott Marlow
- */
-public class LockRequest
-{
-
- public static final int NO_WAIT = 0;
- public static final int WAIT_FOREVER = -1;
-
- private LockMode lockMode = LockMode.NONE;
-
- private int timeout = WAIT_FOREVER; // timeout in milliseconds, 0 = no wait, -1 = wait indefinitely
-
- private boolean scope=false;// if true, cascade (pessimistic only) lock to collections and relationships
- // owned by the entity.
-
- public LockRequest() {
-
- }
-
- public LockRequest( LockMode lockMode, int timeout, boolean scope ) {
- this.lockMode = lockMode;
- this.timeout = timeout;
- this.scope = scope;
- }
-
- /**
- * Get the lock mode.
- * @return the lock mode.
- */
- public LockMode getLockMode() {
- return lockMode;
- }
-
- /**
- * Specify the LockMode to be used. The default is LockMode.none.
- *
- * @param lockMode
- * @return this LockRequest instance for operation chaining.
- */
- public LockRequest setLockMode(LockMode lockMode) {
- this.lockMode = lockMode;
- return this;
- }
-
- /**
- * Get the timeout setting.
- *
- * @return timeout in milliseconds, -1 for indefinite wait and 0 for no wait.
- */
- public int getTimeOut() {
- return timeout;
- }
-
- /**
- * Specify the pessimistic lock timeout (check if your dialect supports this option).
- * The default pessimistic lock behavior is to wait forever for the lock.
- *
- * @param timeout is time in milliseconds to wait for lock. -1 means wait forever and 0 means no wait.
- * @return this LockRequest instance for operation chaining.
- */
- public LockRequest setTimeOut(int timeout) {
- this.timeout = timeout;
- return this;
- }
-
- /**
- * Check if locking is cascaded to owned collections and relationships.
- * @return true if locking will be extended to owned collections and relationships.
- */
- public boolean getScope() {
- return scope;
- }
-
- /**
- * Specify if LockMode should be cascaded to owned collections and relationships.
- * The association must be mapped with <tt>cascade="lock" for scope=true to work.
- *
- * @param scope
- * @return
- */
- public LockRequest setScope(boolean scope) {
- this.scope = scope;
- return this;
- }
-
-}
Modified: core/trunk/core/src/main/java/org/hibernate/Session.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/Session.java 2009-11-24 22:28:05 UTC (rev 18052)
+++ core/trunk/core/src/main/java/org/hibernate/Session.java 2009-11-24 23:59:50 UTC (rev 18053)
@@ -270,7 +270,7 @@
* @param lockMode the lock level
* @return the persistent instance or proxy
* @throws HibernateException
- * @deprecated LockMode parameter should be replaced with a LockRequest
+ * @deprecated LockMode parameter should be replaced with LockOptions
*/
public Object load(Class theClass, Serializable id, LockMode lockMode) throws HibernateException;
@@ -280,11 +280,11 @@
*
* @param theClass a persistent class
* @param id a valid identifier of an existing persistent instance of the class
- * @param lockRequest contains the lock level
+ * @param lockOptions contains the lock level
* @return the persistent instance or proxy
* @throws HibernateException
*/
- public Object load(Class theClass, Serializable id, LockRequest lockRequest) throws HibernateException;
+ public Object load(Class theClass, Serializable id, LockOptions lockOptions) throws HibernateException;
/**
* Return the persistent instance of the given entity class with the given identifier,
@@ -295,7 +295,7 @@
* @param lockMode the lock level
* @return the persistent instance or proxy
* @throws HibernateException
- * @deprecated LockMode parameter should be replaced with a LockRequest
+ * @deprecated LockMode parameter should be replaced with LockOptions
*/
public Object load(String entityName, Serializable id, LockMode lockMode) throws HibernateException;
@@ -305,11 +305,11 @@
*
* @param entityName a persistent class
* @param id a valid identifier of an existing persistent instance of the class
- * @param lockRequest contains the lock level
+ * @param lockOptions contains the lock level
* @return the persistent instance or proxy
* @throws HibernateException
*/
- public Object load(String entityName, Serializable id, LockRequest lockRequest) throws HibernateException;
+ public Object load(String entityName, Serializable id, LockOptions lockOptions) throws HibernateException;
/**
* Return the persistent instance of the given entity class with the given identifier,
@@ -533,7 +533,7 @@
* @param object a persistent or transient instance
* @param lockMode the lock level
* @throws HibernateException
- * @deprecated LockMode parameter should be replaced with a LockRequest
+ * @deprecated instead call buildLockRequest(LockMode).lock(object)
*/
public void lock(Object object, LockMode lockMode) throws HibernateException;
@@ -542,51 +542,27 @@
* perform a version check (<tt>LockMode.OPTIMISTIC</tt>), to upgrade to a pessimistic
* lock (<tt>LockMode.PESSIMISTIC_WRITE</tt>), or to simply reassociate a transient instance
* with a session (<tt>LockMode.NONE</tt>). This operation cascades to associated
- * instances if the association is mapped with <tt>cascade="lock" and lockRequest.getScope() == true</tt>.
- *
- * @param object a persistent or transient instance
- * @param lockRequest contains the lock level
- * @throws HibernateException
- */
- public void lock(Object object, LockRequest lockRequest) throws HibernateException;
-
- /**
- * Obtain the specified lock level upon the given object. This may be used to
- * perform a version check (<tt>LockMode.OPTIMISTIC</tt>), to upgrade to a pessimistic
- * lock (<tt>LockMode.PESSIMISTIC_WRITE</tt>), or to simply reassociate a transient instance
- * with a session (<tt>LockMode.NONE</tt>). This operation cascades to associated
* instances if the association is mapped with <tt>cascade="lock"</tt>.
*
* @param object a persistent or transient instance
* @param lockMode the lock level
* @throws HibernateException
- * @deprecated LockMode parameter should be replaced with a LockRequest
+ * @deprecated instead call buildLockRequest(LockMode).lock(entityName, object)
*/
public void lock(String entityName, Object object, LockMode lockMode) throws HibernateException;
/**
- * Obtain the specified lock level upon the given object. This may be used to
- * perform a version check (<tt>LockMode.OPTIMISTIC</tt>), to upgrade to a pessimistic
- * lock (<tt>LockMode.PESSIMISTIC_WRITE</tt>), or to simply reassociate a transient instance
- * with a session (<tt>LockMode.NONE</tt>). This operation cascades to associated
- * instances if the association is mapped with <tt>cascade="lock" and lockRequest.getScope() == true.</tt>.
- *
- * @param object a persistent or transient instance
- * @param lockRequest contains the lock level
- * @throws HibernateException
- */
- public void lock(String entityName, Object object, LockRequest lockRequest) throws HibernateException;
-
- /**
* Build a lockRequest that specifies the LockMode, pessimistic lock timeout and lock scope.
* timeout and scope is ignored for optimistic locking.
*
- * Use: LockRequest lr = session.buildLockRequest().setLockMode(LockMode.PESSIMISTIC_WRITE).setTimeOut(1000 * 60);
- * session.lock(entity, lr);
+ * Use: session.buildLockRequest().
+ * setLockMode(LockMode.PESSIMISTIC_WRITE).setTimeOut(1000 * 60).lock(entity);
*
+ * @param lockOptions contains the lock level
+ * @return a lockRequest that can be used to lock the passed object.
* @throws HibernateException
*/
- LockRequest buildLockRequest();
+ public LockRequest buildLockRequest(LockOptions lockOptions);
/**
* Re-read the state of the given instance from the underlying database. It is
@@ -613,7 +589,7 @@
* @param object a persistent or detached instance
* @param lockMode the lock mode to use
* @throws HibernateException
- * @deprecated LockMode parameter should be replaced with a LockRequest
+ * @deprecated LockMode parameter should be replaced with LockOptions
*/
public void refresh(Object object, LockMode lockMode) throws HibernateException;
@@ -624,10 +600,10 @@
* useful in certain special circumstances.
*
* @param object a persistent or detached instance
- * @param lockRequest contains the lock mode to use
+ * @param lockOptions contains the lock mode to use
* @throws HibernateException
*/
- public void refresh(Object object, LockRequest lockRequest) throws HibernateException;
+ public void refresh(Object object, LockOptions lockOptions) throws HibernateException;
/**
* Determine the current lock mode of the given object.
@@ -766,7 +742,7 @@
* @param lockMode the lock mode
* @return a persistent instance or null
* @throws HibernateException
- * @deprecated LockMode parameter should be replaced with a LockRequest
+ * @deprecated LockMode parameter should be replaced with LockOptions
*/
public Object get(Class clazz, Serializable id, LockMode lockMode) throws HibernateException;
@@ -778,11 +754,11 @@
*
* @param clazz a persistent class
* @param id an identifier
- * @param lockRequest the lock mode
+ * @param lockOptions the lock mode
* @return a persistent instance or null
* @throws HibernateException
*/
- public Object get(Class clazz, Serializable id, LockRequest lockRequest) throws HibernateException;
+ public Object get(Class clazz, Serializable id, LockOptions lockOptions) throws HibernateException;
/**
* Return the persistent instance of the given named entity with the given identifier,
@@ -807,7 +783,7 @@
* @param lockMode the lock mode
* @return a persistent instance or null
* @throws HibernateException
- * @deprecated LockMode parameter should be replaced with a LockRequest
+ * @deprecated LockMode parameter should be replaced with LockOptions
*/
public Object get(String entityName, Serializable id, LockMode lockMode) throws HibernateException;
@@ -819,11 +795,11 @@
*
* @param entityName the entity name
* @param id an identifier
- * @param lockRequest contains the lock mode
+ * @param lockOptions contains the lock mode
* @return a persistent instance or null
* @throws HibernateException
*/
- public Object get(String entityName, Serializable id, LockRequest lockRequest) throws HibernateException;
+ public Object get(String entityName, Serializable id, LockOptions lockOptions) throws HibernateException;
/**
@@ -957,4 +933,68 @@
* @see org.hibernate.engine.profile.FetchProfile for discussion of this feature
*/
public void disableFetchProfile(String name) throws UnknownProfileException;
+
+
+
+/**
+ * Contains locking details (LockMode, Timeout and Scope).
+ *
+ */
+ public interface LockRequest
+ {
+
+ static final int PESSIMISTIC_NO_WAIT = 0;
+ static final int PESSIMISTIC_WAIT_FOREVER = -1;
+
+ /**
+ * Get the lock mode.
+ * @return the lock mode.
+ */
+ LockMode getLockMode();
+
+ /**
+ * Specify the LockMode to be used. The default is LockMode.none.
+ *
+ * @param lockMode
+ * @return this LockRequest instance for operation chaining.
+ */
+ LockRequest setLockMode(LockMode lockMode);
+
+ /**
+ * Get the timeout setting.
+ *
+ * @return timeout in milliseconds, -1 for indefinite wait and 0 for no wait.
+ */
+ int getTimeOut();
+
+ /**
+ * Specify the pessimistic lock timeout (check if your dialect supports this option).
+ * The default pessimistic lock behavior is to wait forever for the lock.
+ *
+ * @param timeout is time in milliseconds to wait for lock. -1 means wait forever and 0 means no wait.
+ * @return this LockRequest instance for operation chaining.
+ */
+ LockRequest setTimeOut(int timeout);
+
+ /**
+ * Check if locking is cascaded to owned collections and relationships.
+ * @return true if locking will be extended to owned collections and relationships.
+ */
+ boolean getScope();
+
+ /**
+ * Specify if LockMode should be cascaded to owned collections and relationships.
+ * The association must be mapped with <tt>cascade="lock" for scope=true to work.
+ *
+ * @param scope
+ * @return
+ */
+ LockRequest setScope(boolean scope);
+
+ void lock(String entityName, Object object) throws HibernateException;
+
+ public void lock(Object object) throws HibernateException;
+
+ }
+
}
Modified: core/trunk/core/src/main/java/org/hibernate/engine/CascadingAction.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/engine/CascadingAction.java 2009-11-24 22:28:05 UTC (rev 18052)
+++ core/trunk/core/src/main/java/org/hibernate/engine/CascadingAction.java 2009-11-24 23:59:50 UTC (rev 18053)
@@ -34,7 +34,7 @@
import org.hibernate.LockMode;
import org.hibernate.ReplicationMode;
import org.hibernate.TransientObjectException;
-import org.hibernate.LockRequest;
+import org.hibernate.LockOptions;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.collection.PersistentCollection;
@@ -167,16 +167,16 @@
log.trace( "cascading to lock: " + entityName );
}
LockMode lockMode = LockMode.NONE;
- LockRequest lr = new LockRequest();
- if ( anything instanceof LockRequest ) {
- LockRequest lockRequest = (LockRequest)anything;
- lr.setTimeOut(lockRequest.getTimeOut());
- lr.setScope( lockRequest.getScope());
- if ( lockRequest.getScope() == true ) // cascade specified lockMode
- lockMode = lockRequest.getLockMode();
+ LockOptions lr = new LockOptions();
+ if ( anything instanceof LockOptions) {
+ LockOptions lockOptions = (LockOptions)anything;
+ lr.setTimeOut(lockOptions.getTimeOut());
+ lr.setScope( lockOptions.getScope());
+ if ( lockOptions.getScope() == true ) // cascade specified lockMode
+ lockMode = lockOptions.getLockMode();
}
lr.setLockMode(lockMode);
- session.lock( entityName, child, lr);
+ session.buildLockRequest(lr).lock(entityName, child);
}
public Iterator getCascadableChildrenIterator(EventSource session, CollectionType collectionType, Object collection) {
// lock doesn't cascade to uninitialized collections
Modified: core/trunk/core/src/main/java/org/hibernate/event/LoadEvent.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/event/LoadEvent.java 2009-11-24 22:28:05 UTC (rev 18052)
+++ core/trunk/core/src/main/java/org/hibernate/event/LoadEvent.java 2009-11-24 23:59:50 UTC (rev 18053)
@@ -27,7 +27,7 @@
import java.io.Serializable;
import org.hibernate.LockMode;
-import org.hibernate.LockRequest;
+import org.hibernate.LockOptions;
/**
* Defines an event class for the loading of an entity.
@@ -41,24 +41,24 @@
private Serializable entityId;
private String entityClassName;
private Object instanceToLoad;
- private LockRequest lockRequest;
+ private LockOptions lockOptions;
private boolean isAssociationFetch;
private Object result;
public LoadEvent(Serializable entityId, Object instanceToLoad, EventSource source) {
- this(entityId, null, instanceToLoad, new LockRequest(), false, source);
+ this(entityId, null, instanceToLoad, new LockOptions(), false, source);
}
public LoadEvent(Serializable entityId, String entityClassName, LockMode lockMode, EventSource source) {
this(entityId, entityClassName, null, lockMode, false, source);
}
- public LoadEvent(Serializable entityId, String entityClassName, LockRequest lockRequest, EventSource source) {
- this(entityId, entityClassName, null, lockRequest, false, source);
+ public LoadEvent(Serializable entityId, String entityClassName, LockOptions lockOptions, EventSource source) {
+ this(entityId, entityClassName, null, lockOptions, false, source);
}
public LoadEvent(Serializable entityId, String entityClassName, boolean isAssociationFetch, EventSource source) {
- this(entityId, entityClassName, null, new LockRequest(), isAssociationFetch, source);
+ this(entityId, entityClassName, null, new LockOptions(), isAssociationFetch, source);
}
public boolean isAssociationFetch() {
@@ -72,14 +72,14 @@
LockMode lockMode,
boolean isAssociationFetch,
EventSource source) {
- this(entityId, entityClassName, instanceToLoad, new LockRequest().setLockMode(lockMode), isAssociationFetch, source );
+ this(entityId, entityClassName, instanceToLoad, new LockOptions().setLockMode(lockMode), isAssociationFetch, source );
}
private LoadEvent(
Serializable entityId,
String entityClassName,
Object instanceToLoad,
- LockRequest lockRequest,
+ LockOptions lockOptions,
boolean isAssociationFetch,
EventSource source) {
@@ -89,17 +89,17 @@
throw new IllegalArgumentException("id to load is required for loading");
}
- if ( lockRequest.getLockMode() == LockMode.WRITE ) {
+ if ( lockOptions.getLockMode() == LockMode.WRITE ) {
throw new IllegalArgumentException("Invalid lock mode for loading");
}
- else if ( lockRequest.getLockMode() == null ) {
- lockRequest.setLockMode(DEFAULT_LOCK_MODE);
+ else if ( lockOptions.getLockMode() == null ) {
+ lockOptions.setLockMode(DEFAULT_LOCK_MODE);
}
this.entityId = entityId;
this.entityClassName = entityClassName;
this.instanceToLoad = instanceToLoad;
- this.lockRequest = lockRequest;
+ this.lockOptions = lockOptions;
this.isAssociationFetch = isAssociationFetch;
}
@@ -127,32 +127,32 @@
this.instanceToLoad = instanceToLoad;
}
- public LockRequest getLockRequest() {
- return lockRequest;
+ public LockOptions getLockOptions() {
+ return lockOptions;
}
public LockMode getLockMode() {
- return lockRequest.getLockMode();
+ return lockOptions.getLockMode();
}
public void setLockMode(LockMode lockMode) {
- this.lockRequest.setLockMode(lockMode);
+ this.lockOptions.setLockMode(lockMode);
}
public void setLockTimeout(int timeout) {
- this.lockRequest.setTimeOut(timeout);
+ this.lockOptions.setTimeOut(timeout);
}
public int getLockTimeout() {
- return this.lockRequest.getTimeOut();
+ return this.lockOptions.getTimeOut();
}
public void setLockScope(boolean cascade) {
- this.lockRequest.setScope(cascade);
+ this.lockOptions.setScope(cascade);
}
public boolean getLockScope() {
- return this.lockRequest.getScope();
+ return this.lockOptions.getScope();
}
public Object getResult() {
Modified: core/trunk/core/src/main/java/org/hibernate/event/LockEvent.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/event/LockEvent.java 2009-11-24 22:28:05 UTC (rev 18052)
+++ core/trunk/core/src/main/java/org/hibernate/event/LockEvent.java 2009-11-24 23:59:50 UTC (rev 18053)
@@ -25,7 +25,7 @@
package org.hibernate.event;
import org.hibernate.LockMode;
-import org.hibernate.LockRequest;
+import org.hibernate.LockOptions;
/**
* Defines an event class for the locking of an entity.
@@ -35,7 +35,7 @@
public class LockEvent extends AbstractEvent {
private Object object;
- private LockRequest lockRequest;
+ private LockOptions lockOptions;
private String entityName;
public LockEvent(String entityName, Object original, LockMode lockMode, EventSource source) {
@@ -43,21 +43,21 @@
this.entityName = entityName;
}
- public LockEvent(String entityName, Object original, LockRequest lockRequest, EventSource source) {
- this(original, lockRequest, source);
+ public LockEvent(String entityName, Object original, LockOptions lockOptions, EventSource source) {
+ this(original, lockOptions, source);
this.entityName = entityName;
}
public LockEvent(Object object, LockMode lockMode, EventSource source) {
super(source);
this.object = object;
- this.lockRequest = new LockRequest().setLockMode(lockMode);
+ this.lockOptions = new LockOptions().setLockMode(lockMode);
}
- public LockEvent(Object object, LockRequest lockRequest, EventSource source) {
+ public LockEvent(Object object, LockOptions lockOptions, EventSource source) {
super(source);
this.object = object;
- this.lockRequest = lockRequest;
+ this.lockOptions = lockOptions;
}
public Object getObject() {
@@ -68,32 +68,32 @@
this.object = object;
}
- public LockRequest getLockRequest() {
- return lockRequest;
+ public LockOptions getLockOptions() {
+ return lockOptions;
}
public LockMode getLockMode() {
- return lockRequest.getLockMode();
+ return lockOptions.getLockMode();
}
public void setLockMode(LockMode lockMode) {
- this.lockRequest.setLockMode(lockMode);
+ this.lockOptions.setLockMode(lockMode);
}
public void setLockTimeout(int timeout) {
- this.lockRequest.setTimeOut(timeout);
+ this.lockOptions.setTimeOut(timeout);
}
public int getLockTimeout() {
- return this.lockRequest.getTimeOut();
+ return this.lockOptions.getTimeOut();
}
public void setLockScope(boolean cascade) {
- this.lockRequest.setScope(cascade);
+ this.lockOptions.setScope(cascade);
}
public boolean getLockScope() {
- return this.lockRequest.getScope();
+ return this.lockOptions.getScope();
}
public String getEntityName() {
Modified: core/trunk/core/src/main/java/org/hibernate/event/RefreshEvent.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/event/RefreshEvent.java 2009-11-24 22:28:05 UTC (rev 18052)
+++ core/trunk/core/src/main/java/org/hibernate/event/RefreshEvent.java 2009-11-24 23:59:50 UTC (rev 18053)
@@ -25,7 +25,7 @@
package org.hibernate.event;
import org.hibernate.LockMode;
-import org.hibernate.LockRequest;
+import org.hibernate.LockOptions;
/**
* Defines an event class for the refreshing of an object.
@@ -35,7 +35,7 @@
public class RefreshEvent extends AbstractEvent {
private Object object;
- private LockRequest lockRequest = new LockRequest().setLockMode(LockMode.READ);
+ private LockOptions lockOptions = new LockOptions().setLockMode(LockMode.READ);
public RefreshEvent(Object object, EventSource source) {
super(source);
@@ -50,34 +50,34 @@
if (lockMode == null) {
throw new IllegalArgumentException("Attempt to generate refresh event with null lock mode");
}
- this.lockRequest.setLockMode(lockMode);
+ this.lockOptions.setLockMode(lockMode);
}
- public RefreshEvent(Object object, LockRequest lockRequest, EventSource source) {
+ public RefreshEvent(Object object, LockOptions lockOptions, EventSource source) {
this(object, source);
- if (lockRequest == null) {
+ if (lockOptions == null) {
throw new IllegalArgumentException("Attempt to generate refresh event with null lock request");
}
- this.lockRequest = lockRequest;
+ this.lockOptions = lockOptions;
}
public Object getObject() {
return object;
}
- public LockRequest getLockRequest() {
- return lockRequest;
+ public LockOptions getLockOptions() {
+ return lockOptions;
}
public LockMode getLockMode() {
- return lockRequest.getLockMode();
+ return lockOptions.getLockMode();
}
public int getLockTimeout() {
- return this.lockRequest.getTimeOut();
+ return this.lockOptions.getTimeOut();
}
public boolean getLockScope() {
- return this.lockRequest.getScope();
+ return this.lockOptions.getScope();
}
}
Modified: core/trunk/core/src/main/java/org/hibernate/event/def/AbstractLockUpgradeEventListener.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/event/def/AbstractLockUpgradeEventListener.java 2009-11-24 22:28:05 UTC (rev 18052)
+++ core/trunk/core/src/main/java/org/hibernate/event/def/AbstractLockUpgradeEventListener.java 2009-11-24 23:59:50 UTC (rev 18053)
@@ -29,11 +29,8 @@
import org.hibernate.LockMode;
import org.hibernate.ObjectDeletedException;
-import org.hibernate.OptimisticLockException;
-import org.hibernate.LockRequest;
+import org.hibernate.LockOptions;
import org.hibernate.event.EventSource;
-import org.hibernate.action.EntityIncrementVersionProcess;
-import org.hibernate.action.EntityVerifyVersionProcess;
import org.hibernate.cache.CacheKey;
import org.hibernate.cache.access.SoftLock;
import org.hibernate.engine.EntityEntry;
@@ -56,12 +53,12 @@
*
* @param object The entity for which to upgrade the lock.
* @param entry The entity's EntityEntry instance.
- * @param lockRequest contains the requested lock mode.
+ * @param lockOptions contains the requested lock mode.
* @param source The session which is the source of the event being processed.
*/
- protected void upgradeLock(Object object, EntityEntry entry, LockRequest lockRequest, EventSource source) {
+ protected void upgradeLock(Object object, EntityEntry entry, LockOptions lockOptions, EventSource source) {
- LockMode requestedLockMode = lockRequest.getLockMode();
+ LockMode requestedLockMode = lockOptions.getLockMode();
if ( requestedLockMode.greaterThan( entry.getLockMode() ) ) {
// The user requested a "greater" (i.e. more restrictive) form of
// pessimistic lock
Modified: core/trunk/core/src/main/java/org/hibernate/event/def/DefaultLoadEventListener.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/event/def/DefaultLoadEventListener.java 2009-11-24 22:28:05 UTC (rev 18052)
+++ core/trunk/core/src/main/java/org/hibernate/event/def/DefaultLoadEventListener.java 2009-11-24 23:59:50 UTC (rev 18053)
@@ -485,7 +485,7 @@
return INCONSISTENT_RTN_CLASS_MARKER;
}
}
- upgradeLock( old, oldEntry, event.getLockRequest(), event.getSession() );
+ upgradeLock( old, oldEntry, event.getLockOptions(), event.getSession() );
}
return old;
Modified: core/trunk/core/src/main/java/org/hibernate/event/def/DefaultLockEventListener.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/event/def/DefaultLockEventListener.java 2009-11-24 22:28:05 UTC (rev 18052)
+++ core/trunk/core/src/main/java/org/hibernate/event/def/DefaultLockEventListener.java 2009-11-24 23:59:50 UTC (rev 18053)
@@ -83,7 +83,7 @@
cascadeOnLock(event, persister, entity);
}
- upgradeLock( entity, entry, event.getLockRequest(), event.getSession() );
+ upgradeLock( entity, entry, event.getLockOptions(), event.getSession() );
}
private void cascadeOnLock(LockEvent event, EntityPersister persister, Object entity) {
@@ -91,7 +91,7 @@
source.getPersistenceContext().incrementCascadeLevel();
try {
new Cascade(CascadingAction.LOCK, Cascade.AFTER_LOCK, source)
- .cascade( persister, entity, event.getLockRequest() );
+ .cascade( persister, entity, event.getLockOptions() );
}
finally {
source.getPersistenceContext().decrementCascadeLevel();
Modified: core/trunk/core/src/main/java/org/hibernate/event/def/DefaultRefreshEventListener.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/event/def/DefaultRefreshEventListener.java 2009-11-24 22:28:05 UTC (rev 18052)
+++ core/trunk/core/src/main/java/org/hibernate/event/def/DefaultRefreshEventListener.java 2009-11-24 23:59:50 UTC (rev 18053)
@@ -142,7 +142,7 @@
String previousFetchProfile = source.getFetchProfile();
source.setFetchProfile("refresh");
- Object result = persister.load( id, object, event.getLockRequest(), source );
+ Object result = persister.load( id, object, event.getLockOptions(), source );
source.setFetchProfile(previousFetchProfile);
UnresolvableObjectException.throwIfNull( result, id, persister.getEntityName() );
Modified: core/trunk/core/src/main/java/org/hibernate/impl/SessionImpl.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/impl/SessionImpl.java 2009-11-24 22:28:05 UTC (rev 18052)
+++ core/trunk/core/src/main/java/org/hibernate/impl/SessionImpl.java 2009-11-24 23:59:50 UTC (rev 18053)
@@ -69,7 +69,7 @@
import org.hibernate.UnresolvableObjectException;
import org.hibernate.UnknownProfileException;
import org.hibernate.EntityNameResolver;
-import org.hibernate.LockRequest;
+import org.hibernate.LockOptions;
import org.hibernate.collection.PersistentCollection;
import org.hibernate.engine.ActionQueue;
import org.hibernate.engine.CollectionEntry;
@@ -742,21 +742,20 @@
fireLock( new LockEvent(entityName, object, lockMode, this) );
}
- public void lock(String entityName, Object object, LockRequest lockRequest) throws HibernateException {
- fireLock( new LockEvent(entityName, object, lockRequest, this) );
+ public LockRequest buildLockRequest(LockOptions lockOptions) {
+ return new LockRequestImpl(lockOptions);
}
- public LockRequest buildLockRequest() {
- return new LockRequest();
- }
-
public void lock(Object object, LockMode lockMode) throws HibernateException {
fireLock( new LockEvent(object, lockMode, this) );
}
+ private void fireLock(String entityName, Object object, LockOptions options) {
+ fireLock( new LockEvent( entityName, object, options, this) );
+ }
- public void lock(Object object, LockRequest lockRequest) throws HibernateException {
- fireLock( new LockEvent(object, lockRequest, this) );
+ private void fireLock( Object object, LockOptions options) {
+ fireLock( new LockEvent( object, options, this) );
}
private void fireLock(LockEvent lockEvent) {
@@ -1037,8 +1036,8 @@
return load( entityClass.getName(), id, lockMode );
}
- public Object load(Class entityClass, Serializable id, LockRequest lockRequest) throws HibernateException {
- return load( entityClass.getName(), id, lockRequest );
+ public Object load(Class entityClass, Serializable id, LockOptions lockOptions) throws HibernateException {
+ return load( entityClass.getName(), id, lockOptions);
}
public Object load(String entityName, Serializable id, LockMode lockMode) throws HibernateException {
@@ -1047,8 +1046,8 @@
return event.getResult();
}
- public Object load(String entityName, Serializable id, LockRequest lockRequest) throws HibernateException {
- LoadEvent event = new LoadEvent(id, entityName, lockRequest, this);
+ public Object load(String entityName, Serializable id, LockOptions lockOptions) throws HibernateException {
+ LoadEvent event = new LoadEvent(id, entityName, lockOptions, this);
fireLoad( event, LoadEventListener.LOAD );
return event.getResult();
}
@@ -1057,8 +1056,8 @@
return get( entityClass.getName(), id, lockMode );
}
- public Object get(Class entityClass, Serializable id, LockRequest lockRequest) throws HibernateException {
- return get( entityClass.getName(), id, lockRequest );
+ public Object get(Class entityClass, Serializable id, LockOptions lockOptions) throws HibernateException {
+ return get( entityClass.getName(), id, lockOptions);
}
public Object get(String entityName, Serializable id, LockMode lockMode) throws HibernateException {
@@ -1067,8 +1066,8 @@
return event.getResult();
}
- public Object get(String entityName, Serializable id, LockRequest lockRequest) throws HibernateException {
- LoadEvent event = new LoadEvent(id, entityName, lockRequest, this);
+ public Object get(String entityName, Serializable id, LockOptions lockOptions) throws HibernateException {
+ LoadEvent event = new LoadEvent(id, entityName, lockOptions, this);
fireLoad(event, LoadEventListener.GET);
return event.getResult();
}
@@ -1093,8 +1092,8 @@
fireRefresh( new RefreshEvent(object, lockMode, this) );
}
- public void refresh(Object object, LockRequest lockRequest) throws HibernateException {
- fireRefresh( new RefreshEvent(object, lockRequest, this) );
+ public void refresh(Object object, LockOptions lockOptions) throws HibernateException {
+ fireRefresh( new RefreshEvent(object, lockOptions, this) );
}
public void refresh(Object object, Map refreshedAlready) throws HibernateException {
@@ -2217,4 +2216,48 @@
return entity.getClass().getName();
}
}
+
+ private class LockRequestImpl implements LockRequest {
+ private final LockOptions lockOptions;
+ private LockRequestImpl(LockOptions lo) {
+ lockOptions = new LockOptions();
+ lockOptions.setLockMode(lo.getLockMode());
+ lockOptions.setScope(lo.getScope());
+ lockOptions.setTimeOut(lo.getTimeOut());
+ }
+
+ public LockMode getLockMode() {
+ return lockOptions.getLockMode();
+ }
+
+ public LockRequest setLockMode(LockMode lockMode) {
+ lockOptions.setLockMode(lockMode);
+ return this;
+ }
+
+ public int getTimeOut() {
+ return lockOptions.getTimeOut();
+ }
+
+ public LockRequest setTimeOut(int timeout) {
+ lockOptions.setTimeOut(timeout);
+ return this;
+ }
+
+ public boolean getScope() {
+ return lockOptions.getScope();
+ }
+
+ public LockRequest setScope(boolean scope) {
+ lockOptions.setScope(scope);
+ return this;
+ }
+
+ public void lock(String entityName, Object object) throws HibernateException {
+ fireLock( entityName, object, lockOptions );
+ }
+ public void lock(Object object) throws HibernateException {
+ fireLock( object, lockOptions );
+ }
+ }
}
Modified: core/trunk/core/src/main/java/org/hibernate/loader/AbstractEntityJoinWalker.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/loader/AbstractEntityJoinWalker.java 2009-11-24 22:28:05 UTC (rev 18052)
+++ core/trunk/core/src/main/java/org/hibernate/loader/AbstractEntityJoinWalker.java 2009-11-24 23:59:50 UTC (rev 18053)
@@ -31,7 +31,7 @@
import org.hibernate.FetchMode;
import org.hibernate.LockMode;
import org.hibernate.MappingException;
-import org.hibernate.LockRequest;
+import org.hibernate.LockOptions;
import org.hibernate.engine.CascadeStyle;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.engine.LoadQueryInfluencers;
@@ -98,7 +98,7 @@
protected final void initAll(
final String whereString,
final String orderByString,
- final LockRequest lockRequest) throws MappingException {
+ final LockOptions lockOptions) throws MappingException {
walkEntityTree( persister, getAlias() );
List allAssociations = new ArrayList();
allAssociations.addAll(associations);
@@ -114,8 +114,8 @@
CollectionHelper.EMPTY_MAP
)
);
- initPersisters(allAssociations, lockRequest.getLockMode());
- initStatementString( whereString, orderByString, lockRequest.getLockMode());
+ initPersisters(allAssociations, lockOptions.getLockMode());
+ initStatementString( whereString, orderByString, lockOptions.getLockMode());
}
protected final void initProjection(
Modified: core/trunk/core/src/main/java/org/hibernate/loader/entity/BatchingEntityLoader.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/loader/entity/BatchingEntityLoader.java 2009-11-24 22:28:05 UTC (rev 18052)
+++ core/trunk/core/src/main/java/org/hibernate/loader/entity/BatchingEntityLoader.java 2009-11-24 23:59:50 UTC (rev 18053)
@@ -27,13 +27,11 @@
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
-import java.util.Map;
-import java.util.Set;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.MappingException;
-import org.hibernate.LockRequest;
+import org.hibernate.LockOptions;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.engine.LoadQueryInfluencers;
@@ -132,7 +130,7 @@
public static UniqueEntityLoader createBatchingEntityLoader(
final OuterJoinLoadable persister,
final int maxBatchSize,
- final LockRequest lockRequest,
+ final LockOptions lockOptions,
final SessionFactoryImplementor factory,
final LoadQueryInfluencers loadQueryInfluencers) throws MappingException {
@@ -140,12 +138,12 @@
int[] batchSizesToCreate = ArrayHelper.getBatchSizes(maxBatchSize);
Loader[] loadersToCreate = new Loader[ batchSizesToCreate.length ];
for ( int i=0; i<batchSizesToCreate.length; i++ ) {
- loadersToCreate[i] = new EntityLoader(persister, batchSizesToCreate[i], lockRequest, factory, loadQueryInfluencers);
+ loadersToCreate[i] = new EntityLoader(persister, batchSizesToCreate[i], lockOptions, factory, loadQueryInfluencers);
}
return new BatchingEntityLoader(persister, batchSizesToCreate, loadersToCreate);
}
else {
- return new EntityLoader(persister, lockRequest, factory, loadQueryInfluencers);
+ return new EntityLoader(persister, lockOptions, factory, loadQueryInfluencers);
}
}
Modified: core/trunk/core/src/main/java/org/hibernate/loader/entity/EntityJoinWalker.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/loader/entity/EntityJoinWalker.java 2009-11-24 22:28:05 UTC (rev 18052)
+++ core/trunk/core/src/main/java/org/hibernate/loader/entity/EntityJoinWalker.java 2009-11-24 23:59:50 UTC (rev 18053)
@@ -25,17 +25,14 @@
package org.hibernate.loader.entity;
import java.util.Collections;
-import java.util.Iterator;
import org.hibernate.FetchMode;
import org.hibernate.LockMode;
import org.hibernate.MappingException;
-import org.hibernate.LockRequest;
+import org.hibernate.LockOptions;
import org.hibernate.engine.CascadeStyle;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.engine.LoadQueryInfluencers;
-import org.hibernate.engine.profile.FetchProfile;
-import org.hibernate.engine.profile.Fetch;
import org.hibernate.loader.AbstractEntityJoinWalker;
import org.hibernate.persister.entity.OuterJoinLoadable;
import org.hibernate.type.AssociationType;
@@ -48,7 +45,7 @@
*/
public class EntityJoinWalker extends AbstractEntityJoinWalker {
- private final LockRequest lockRequest = new LockRequest();
+ private final LockOptions lockOptions = new LockOptions();
public EntityJoinWalker(
OuterJoinLoadable persister,
@@ -59,33 +56,33 @@
LoadQueryInfluencers loadQueryInfluencers) throws MappingException {
super( persister, factory, loadQueryInfluencers );
- this.lockRequest.setLockMode(lockMode);
+ this.lockOptions.setLockMode(lockMode);
StringBuffer whereCondition = whereString( getAlias(), uniqueKey, batchSize )
//include the discriminator and class-level where, but not filters
.append( persister.filterFragment( getAlias(), Collections.EMPTY_MAP ) );
- initAll( whereCondition.toString(), "", lockRequest );
+ initAll( whereCondition.toString(), "", lockOptions);
}
public EntityJoinWalker(
OuterJoinLoadable persister,
String[] uniqueKey,
int batchSize,
- LockRequest lockRequest,
+ LockOptions lockOptions,
SessionFactoryImplementor factory,
LoadQueryInfluencers loadQueryInfluencers) throws MappingException {
super( persister, factory, loadQueryInfluencers );
- this.lockRequest.setLockMode(lockRequest.getLockMode());
- this.lockRequest.setTimeOut(lockRequest.getTimeOut());
- this.lockRequest.setScope(lockRequest.getScope());
+ this.lockOptions.setLockMode(lockOptions.getLockMode());
+ this.lockOptions.setTimeOut(lockOptions.getTimeOut());
+ this.lockOptions.setScope(lockOptions.getScope());
StringBuffer whereCondition = whereString( getAlias(), uniqueKey, batchSize )
//include the discriminator and class-level where, but not filters
.append( persister.filterFragment( getAlias(), Collections.EMPTY_MAP ) );
- initAll( whereCondition.toString(), "", lockRequest);
+ initAll( whereCondition.toString(), "", lockOptions);
}
protected int getJoinType(
@@ -102,7 +99,7 @@
// NOTE : we override this form here specifically to account for
// fetch profiles.
// TODO : how to best handle criteria queries?
- if ( lockRequest.getLockMode().greaterThan( LockMode.READ ) ) {
+ if ( lockOptions.getLockMode().greaterThan( LockMode.READ ) ) {
return -1;
}
if ( isTooDeep( currentDepth )
Modified: core/trunk/core/src/main/java/org/hibernate/loader/entity/EntityLoader.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/loader/entity/EntityLoader.java 2009-11-24 22:28:05 UTC (rev 18052)
+++ core/trunk/core/src/main/java/org/hibernate/loader/entity/EntityLoader.java 2009-11-24 23:59:50 UTC (rev 18053)
@@ -27,7 +27,7 @@
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.MappingException;
-import org.hibernate.LockRequest;
+import org.hibernate.LockOptions;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.engine.LoadQueryInfluencers;
@@ -57,10 +57,10 @@
public EntityLoader(
OuterJoinLoadable persister,
- LockRequest lockRequest,
+ LockOptions lockOptions,
SessionFactoryImplementor factory,
LoadQueryInfluencers loadQueryInfluencers) throws MappingException {
- this( persister, 1, lockRequest, factory, loadQueryInfluencers );
+ this( persister, 1, lockOptions, factory, loadQueryInfluencers );
}
public EntityLoader(
@@ -83,7 +83,7 @@
public EntityLoader(
OuterJoinLoadable persister,
int batchSize,
- LockRequest lockRequest,
+ LockOptions lockOptions,
SessionFactoryImplementor factory,
LoadQueryInfluencers loadQueryInfluencers) throws MappingException {
this(
@@ -91,7 +91,7 @@
persister.getIdentifierColumnNames(),
persister.getIdentifierType(),
batchSize,
- lockRequest,
+ lockOptions,
factory,
loadQueryInfluencers
);
@@ -130,7 +130,7 @@
String[] uniqueKey,
Type uniqueKeyType,
int batchSize,
- LockRequest lockRequest,
+ LockOptions lockOptions,
SessionFactoryImplementor factory,
LoadQueryInfluencers loadQueryInfluencers) throws MappingException {
super( persister, uniqueKeyType, factory, loadQueryInfluencers );
@@ -139,7 +139,7 @@
persister,
uniqueKey,
batchSize,
- lockRequest,
+ lockOptions,
factory,
loadQueryInfluencers
);
Modified: core/trunk/core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java 2009-11-24 22:28:05 UTC (rev 18052)
+++ core/trunk/core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java 2009-11-24 23:59:50 UTC (rev 18053)
@@ -46,7 +46,7 @@
import org.hibernate.QueryException;
import org.hibernate.StaleObjectStateException;
import org.hibernate.StaleStateException;
-import org.hibernate.LockRequest;
+import org.hibernate.LockOptions;
import org.hibernate.cache.CacheKey;
import org.hibernate.cache.access.EntityRegionAccessStrategy;
import org.hibernate.cache.entry.CacheEntry;
@@ -1413,16 +1413,16 @@
Object object,
LockMode lockMode,
SessionImplementor session) throws HibernateException {
- getLocker( lockMode ).lock( id, version, object, LockRequest.WAIT_FOREVER, session );
+ getLocker( lockMode ).lock( id, version, object, LockOptions.WAIT_FOREVER, session );
}
public void lock(
Serializable id,
Object version,
Object object,
- LockRequest lockRequest,
+ LockOptions lockOptions,
SessionImplementor session) throws HibernateException {
- getLocker( lockRequest.getLockMode() ).lock( id, version, object, lockRequest.getTimeOut(), session );
+ getLocker( lockOptions.getLockMode() ).lock( id, version, object, lockOptions.getTimeOut(), session );
}
public String getRootTableName() {
@@ -1882,13 +1882,13 @@
}
protected UniqueEntityLoader createEntityLoader(
- LockRequest lockRequest,
+ LockOptions lockOptions,
LoadQueryInfluencers loadQueryInfluencers) throws MappingException {
//TODO: disable batch loading if lockMode > READ?
return BatchingEntityLoader.createBatchingEntityLoader(
this,
batchSize,
- lockRequest,
+ lockOptions,
getFactory(),
loadQueryInfluencers
);
@@ -3208,7 +3208,7 @@
);
}
- final UniqueEntityLoader loader = getAppropriateLoader( new LockRequest().setLockMode(lockMode), session );
+ final UniqueEntityLoader loader = getAppropriateLoader( new LockOptions().setLockMode(lockMode), session );
return loader.load( id, optionalObject, session );
}
@@ -3216,7 +3216,7 @@
* Load an instance using either the <tt>forUpdateLoader</tt> or the outer joining <tt>loader</tt>,
* depending upon the value of the <tt>lock</tt> parameter
*/
- public Object load(Serializable id, Object optionalObject, LockRequest lockRequest, SessionImplementor session)
+ public Object load(Serializable id, Object optionalObject, LockOptions lockOptions, SessionImplementor session)
throws HibernateException {
if ( log.isTraceEnabled() ) {
@@ -3226,7 +3226,7 @@
);
}
- final UniqueEntityLoader loader = getAppropriateLoader( lockRequest, session );
+ final UniqueEntityLoader loader = getAppropriateLoader(lockOptions, session );
return loader.load( id, optionalObject, session );
}
@@ -3249,7 +3249,7 @@
&& filterHelper.isAffectedBy( session.getLoadQueryInfluencers().getEnabledFilters() );
}
- private UniqueEntityLoader getAppropriateLoader(LockRequest lockRequest, SessionImplementor session) {
+ private UniqueEntityLoader getAppropriateLoader(LockOptions lockOptions, SessionImplementor session) {
if ( queryLoader != null ) {
// if the user specified a custom query loader we need to that
// regardless of any other consideration
@@ -3258,9 +3258,9 @@
else if ( isAffectedByEnabledFilters( session ) ) {
// because filters affect the rows returned (because they add
// restirctions) these need to be next in precendence
- return createEntityLoader( lockRequest, session.getLoadQueryInfluencers() );
+ return createEntityLoader(lockOptions, session.getLoadQueryInfluencers() );
}
- else if ( session.getLoadQueryInfluencers().getInternalFetchProfile() != null && LockMode.UPGRADE.greaterThan( lockRequest.getLockMode() ) ) {
+ else if ( session.getLoadQueryInfluencers().getInternalFetchProfile() != null && LockMode.UPGRADE.greaterThan( lockOptions.getLockMode() ) ) {
// Next, we consider whether an 'internal' fetch profile has been set.
// This indicates a special fetch profile Hibernate needs applied
// (for its merge loading process e.g.).
@@ -3269,10 +3269,10 @@
else if ( isAffectedByEnabledFetchProfiles( session ) ) {
// If the session has associated influencers we need to adjust the
// SQL query used for loading based on those influencers
- return createEntityLoader( lockRequest, session.getLoadQueryInfluencers() );
+ return createEntityLoader(lockOptions, session.getLoadQueryInfluencers() );
}
else {
- return ( UniqueEntityLoader ) loaders.get( lockRequest.getLockMode() );
+ return ( UniqueEntityLoader ) loaders.get( lockOptions.getLockMode() );
}
}
Modified: core/trunk/core/src/main/java/org/hibernate/persister/entity/EntityPersister.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/persister/entity/EntityPersister.java 2009-11-24 22:28:05 UTC (rev 18052)
+++ core/trunk/core/src/main/java/org/hibernate/persister/entity/EntityPersister.java 2009-11-24 23:59:50 UTC (rev 18053)
@@ -31,7 +31,7 @@
import org.hibernate.LockMode;
import org.hibernate.MappingException;
import org.hibernate.EntityMode;
-import org.hibernate.LockRequest;
+import org.hibernate.LockOptions;
import org.hibernate.tuple.entity.EntityMetamodel;
import org.hibernate.cache.OptimisticCacheSource;
import org.hibernate.cache.access.EntityRegionAccessStrategy;
@@ -330,7 +330,7 @@
/**
* Load an instance of the persistent class.
*/
- public Object load(Serializable id, Object optionalObject, LockRequest lockRequest, SessionImplementor session)
+ public Object load(Serializable id, Object optionalObject, LockOptions lockOptions, SessionImplementor session)
throws HibernateException;
/**
@@ -342,7 +342,7 @@
/**
* Do a version check (optional operation)
*/
- public void lock(Serializable id, Object version, Object object, LockRequest lockRequest, SessionImplementor session)
+ public void lock(Serializable id, Object version, Object object, LockOptions lockOptions, SessionImplementor session)
throws HibernateException;
/**
Modified: core/trunk/core/src/main/java/org/hibernate/util/ArrayHelper.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/util/ArrayHelper.java 2009-11-24 22:28:05 UTC (rev 18052)
+++ core/trunk/core/src/main/java/org/hibernate/util/ArrayHelper.java 2009-11-24 23:59:50 UTC (rev 18053)
@@ -32,7 +32,7 @@
import java.util.List;
import org.hibernate.LockMode;
-import org.hibernate.LockRequest;
+import org.hibernate.LockOptions;
import org.hibernate.type.Type;
public final class ArrayHelper {
@@ -84,9 +84,9 @@
return array;
}
- public static LockMode[] fillArray(LockRequest lockRequest, int length) {
+ public static LockMode[] fillArray(LockOptions lockOptions, int length) {
LockMode[] array = new LockMode[length];
- Arrays.fill(array, lockRequest);
+ Arrays.fill(array, lockOptions);
return array;
}
Modified: core/trunk/entitymanager/src/main/java/org/hibernate/ejb/AbstractEntityManagerImpl.java
===================================================================
--- core/trunk/entitymanager/src/main/java/org/hibernate/ejb/AbstractEntityManagerImpl.java 2009-11-24 22:28:05 UTC (rev 18052)
+++ core/trunk/entitymanager/src/main/java/org/hibernate/ejb/AbstractEntityManagerImpl.java 2009-11-24 23:59:50 UTC (rev 18053)
@@ -29,7 +29,6 @@
import java.io.Serializable;
import java.util.Map;
import java.util.Set;
-import java.util.HashMap;
import javax.persistence.EntityNotFoundException;
import javax.persistence.EntityTransaction;
import javax.persistence.FlushModeType;
@@ -521,7 +520,7 @@
if ( !contains( entity ) ) {
throw new IllegalArgumentException( "entity not in the persistence context" );
}
- getSession().lock( entity, getLockRequest(lockModeType, properties) );
+ getSession().buildLockRequest(getLockRequest(lockModeType, properties)).lock( entity );
}
catch ( HibernateException he ) {
throw convert( he );
@@ -529,31 +528,31 @@
}
- private LockRequest getLockRequest(LockModeType lockModeType, Map<String, Object> properties) {
- LockRequest lockRequest = new LockRequest();
- lockRequest.setLockMode(getLockMode(lockModeType));
+ private LockOptions getLockRequest(LockModeType lockModeType, Map<String, Object> properties) {
+ LockOptions lockOptions = new LockOptions();
+ lockOptions.setLockMode(getLockMode(lockModeType));
if ( properties != null ) {
- // lockRequest scope will default to false (PessimisticLockScope.NORMAL)
+ // lockOptions scope will default to false (PessimisticLockScope.NORMAL)
Object value = properties.get(PESSIMISTICLOCKSCOPE);
if ( value instanceof String && PessimisticLockScope.valueOf((String) value) == PessimisticLockScope.EXTENDED) {
- lockRequest.setScope(true);
+ lockOptions.setScope(true);
}
- // lockRequest timeout will default to LockRequest.FOREVER_WAIT
+ // lockOptions timeout will default to LockOptions.FOREVER_WAIT
value = properties.get(PESSIMISTICLOCKTIMEOUT);
if ( value instanceof String ) {
int timeout = Integer.parseInt((String) value);
if ( timeout < 0 ) {
- lockRequest.setTimeOut(LockRequest.WAIT_FOREVER);
+ lockOptions.setTimeOut(LockOptions.WAIT_FOREVER);
}
else if( timeout == 0 ) {
- lockRequest.setTimeOut(LockRequest.NO_WAIT);
+ lockOptions.setTimeOut(LockOptions.NO_WAIT);
}
else {
- lockRequest.setTimeOut(timeout);
+ lockOptions.setTimeOut(timeout);
}
}
}
- return lockRequest;
+ return lockOptions;
}
private LockModeType getLockModeType(LockMode lockMode) {
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/legacy/CustomPersister.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/legacy/CustomPersister.java 2009-11-24 22:28:05 UTC (rev 18052)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/legacy/CustomPersister.java 2009-11-24 23:59:50 UTC (rev 18053)
@@ -11,9 +11,8 @@
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.MappingException;
-import org.hibernate.LockRequest;
+import org.hibernate.LockOptions;
import org.hibernate.tuple.entity.EntityMetamodel;
-import org.hibernate.cache.CacheConcurrencyStrategy;
import org.hibernate.cache.access.EntityRegionAccessStrategy;
import org.hibernate.cache.entry.CacheEntryStructure;
import org.hibernate.cache.entry.UnstructuredCacheEntry;
@@ -281,15 +280,15 @@
}
/**
- * @see EntityPersister#load(Serializable, Object, LockRequest, SessionImplementor)
+ * @see EntityPersister#load(Serializable, Object, org.hibernate.LockOptions , SessionImplementor)
*/
public Object load(
Serializable id,
Object optionalObject,
- LockRequest lockRequest,
+ LockOptions lockOptions,
SessionImplementor session
) throws HibernateException {
- return load(id, optionalObject, lockRequest.getLockMode(), session);
+ return load(id, optionalObject, lockOptions.getLockMode(), session);
}
/**
@@ -343,7 +342,7 @@
Serializable id,
Object version,
Object object,
- LockRequest lockRequest,
+ LockOptions lockOptions,
SessionImplementor session
) throws HibernateException {
15 years
Hibernate SVN: r18052 - validator/trunk/hibernate-validator-tck-runner.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-11-24 17:28:05 -0500 (Tue, 24 Nov 2009)
New Revision: 18052
Modified:
validator/trunk/hibernate-validator-tck-runner/pom.xml
Log:
upgraded TCK version
Modified: validator/trunk/hibernate-validator-tck-runner/pom.xml
===================================================================
--- validator/trunk/hibernate-validator-tck-runner/pom.xml 2009-11-24 21:14:30 UTC (rev 18051)
+++ validator/trunk/hibernate-validator-tck-runner/pom.xml 2009-11-24 22:28:05 UTC (rev 18052)
@@ -32,7 +32,7 @@
<dependency>
<groupId>org.hibernate.jsr303.tck</groupId>
<artifactId>jsr303-tck</artifactId>
- <version>1.0.2-SNAPSHOT</version>
+ <version>1.0.2.GA</version>
</dependency>
<dependency>
<groupId>org.jboss.test-harness</groupId>
15 years
Hibernate SVN: r18051 - annotations/branches/v3_4_0_GA_CP/src.
by hibernate-commits@lists.jboss.org
Author: stliu
Date: 2009-11-24 16:14:30 -0500 (Tue, 24 Nov 2009)
New Revision: 18051
Removed:
annotations/branches/v3_4_0_GA_CP/src/java/
Log:
JBPAPP-3150 change the build tool of Hibernate Annotations(eap 5 cp branch)
15 years
Hibernate SVN: r18050 - in annotations/branches/v3_4_0_GA_CP/src/main/java: org and 8 other directories.
by hibernate-commits@lists.jboss.org
Author: stliu
Date: 2009-11-24 16:08:28 -0500 (Tue, 24 Nov 2009)
New Revision: 18050
Added:
annotations/branches/v3_4_0_GA_CP/src/main/java/org/
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/AnnotationException.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/AccessType.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Any.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/AnyMetaDef.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/AnyMetaDefs.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/BatchSize.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Cache.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/CacheConcurrencyStrategy.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/CacheModeType.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Cascade.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/CascadeType.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Check.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/CollectionId.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/CollectionOfElements.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Columns.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/DiscriminatorFormula.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Entity.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Fetch.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/FetchMode.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Filter.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/FilterDef.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/FilterDefs.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/FilterJoinTable.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/FilterJoinTables.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Filters.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/FlushModeType.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/ForceDiscriminator.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/ForeignKey.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Formula.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Generated.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/GenerationTime.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/GenericGenerator.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/GenericGenerators.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Immutable.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Index.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/IndexColumn.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/LazyCollection.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/LazyCollectionOption.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/LazyToOne.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/LazyToOneOption.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Loader.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/ManyToAny.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/MapKey.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/MapKeyManyToMany.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/MetaValue.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/NamedNativeQueries.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/NamedNativeQuery.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/NamedQueries.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/NamedQuery.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/NaturalId.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/NotFound.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/NotFoundAction.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/OnDelete.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/OnDeleteAction.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/OptimisticLock.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/OptimisticLockType.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/OrderBy.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/ParamDef.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Parameter.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Parent.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Persister.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/PolymorphismType.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Proxy.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/ResultCheckStyle.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/SQLDelete.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/SQLDeleteAll.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/SQLInsert.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/SQLUpdate.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Sort.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/SortType.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Table.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Tables.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Target.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Tuplizer.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Tuplizers.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Type.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/TypeDef.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/TypeDefs.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Where.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/WhereJoinTable.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/AbstractPropertyHolder.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/AnnotatedClassType.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/AnnotationBinder.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/AnnotationConfiguration.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/BinderHelper.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/ClassPropertyHolder.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/CollectionPropertyHolder.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/ComponentPropertyHolder.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/CreateKeySecondPass.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/DefaultComponentSafeNamingStrategy.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/EJB3DTDEntityResolver.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/EJB3NamingStrategy.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/Ejb3Column.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/Ejb3DiscriminatorColumn.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/Ejb3JoinColumn.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/ExtendedMappings.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/FkSecondPass.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/IndexColumn.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/IndexOrUniqueKeySecondPass.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/InheritanceState.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/JoinedSubclassFkSecondPass.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/NotYetImplementedException.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/OneToOneSecondPass.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/PropertyData.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/PropertyHolder.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/PropertyHolderBuilder.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/PropertyInferredData.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/PropertyPreloadedData.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/RecoverableException.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/SecondaryTableSecondPass.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/ToOneFkSecondPass.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/WrappedInferredData.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/ArrayBinder.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/BagBinder.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/CollectionBinder.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/EntityBinder.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/IdBagBinder.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/ListBinder.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/MapBinder.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/Nullability.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/PrimitiveArrayBinder.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/PropertyBinder.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/QueryBinder.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/ResultsetMappingSecondPass.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/SetBinder.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/SimpleValueBinder.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/TableBinder.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/Version.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/reflection/
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/reflection/EJB3OverridenAnnotationReader.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/reflection/EJB3ReflectionManager.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/reflection/XMLContext.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/search/
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/search/HibernateSearchEventListenerRegister.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/mapping/
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/mapping/IdGenerator.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/type/
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/type/AbstractLobType.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/type/ByteArrayBlobType.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/type/CharacterArrayClobType.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/type/EnumType.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/type/PrimitiveByteArrayBlobType.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/type/PrimitiveCharacterArrayClobType.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/type/SerializableToBlobType.java
annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/type/StringClobType.java
Log:
JBPAPP-3150 change the build tool of Hibernate Annotations(eap 5 cp branch)
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/AnnotationException.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/AnnotationException.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/AnnotationException.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,24 @@
+//$Id: AnnotationException.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate;
+
+/**
+ * Annotation related exception.
+ * The EJB3 EG will probably set a generic exception.
+ * I'll then use this one.
+ *
+ * @author Emmanuel Bernard
+ */
+public class AnnotationException extends MappingException {
+
+ public AnnotationException(String msg, Throwable root) {
+ super( msg, root );
+ }
+
+ public AnnotationException(Throwable root) {
+ super( root );
+ }
+
+ public AnnotationException(String s) {
+ super( s );
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/AccessType.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/AccessType.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/AccessType.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,18 @@
+//$Id: AccessType.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.*;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * Property Access type
+ *
+ * @author Emmanuel Bernard
+ */
+@Target({TYPE, METHOD, FIELD})
+@Retention(RUNTIME)
+public @interface AccessType {
+ String value();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Any.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Any.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Any.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,45 @@
+//$Id: Any.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import javax.persistence.Column;
+import javax.persistence.FetchType;
+import static javax.persistence.FetchType.EAGER;
+
+/**
+ * Define a ToOne association pointing to several entity types.
+ * Matching the according entity type is doe through a metadata discriminator column
+ * This kind of mapping should be only marginal.
+ *
+ * @author Emmanuel Bernard
+ */
+(a)java.lang.annotation.Target({METHOD, FIELD})
+@Retention(RUNTIME)
+public @interface Any {
+ /**
+ * Metadata definition used.
+ * If defined, should point to a @AnyMetaDef name
+ * If not defined, the local (ie in the same field or property) @AnyMetaDef is used
+ */
+ String metaDef() default "";
+
+ /**
+ * Metadata discriminator column description, This column will hold the meta value corresponding to the
+ * targeted entity.
+ */
+ Column metaColumn();
+ /**
+ * Defines whether the value of the field or property should be lazily loaded or must be
+ * eagerly fetched. The EAGER strategy is a requirement on the persistence provider runtime
+ * that the value must be eagerly fetched. The LAZY strategy is applied when bytecode
+ * enhancement is used. If not specified, defaults to EAGER.
+ */
+ FetchType fetch() default EAGER;
+ /**
+ * Whether the association is optional. If set to false then a non-null relationship must always exist.
+ */
+ boolean optional() default true;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/AnyMetaDef.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/AnyMetaDef.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/AnyMetaDef.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,40 @@
+//$Id: AnyMetaDef.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.PACKAGE;
+import static java.lang.annotation.ElementType.TYPE;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+/**
+ * Defines @Any and @manyToAny metadata
+ *
+ * @author Emmanuel Bernard
+ */
+(a)java.lang.annotation.Target( { PACKAGE, TYPE, METHOD, FIELD } )
+@Retention( RUNTIME )
+public @interface AnyMetaDef {
+ /**
+ * If defined, assign a global meta definition name to be used in an @Any or @ManyToAny annotation
+ * If not defined, the metadata applies to the current property or field
+ */
+ String name() default "";
+
+ /**
+ * meta discriminator Hibernate type
+ */
+ String metaType();
+
+ /**
+ * Hibernate type of the id column
+ * @return
+ */
+ String idType();
+
+ /**
+ * Matching discriminator values with their respective entity
+ */
+ MetaValue[] metaValues();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/AnyMetaDefs.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/AnyMetaDefs.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/AnyMetaDefs.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,21 @@
+//$Id: AnyMetaDefs.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.PACKAGE;
+import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.FIELD;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+/**
+ * Defines @Any and @ManyToAny set of metadata.
+ * Can be defined at the entity level or the package level
+ *
+ * @author Emmanuel Bernard
+ */
+(a)java.lang.annotation.Target( { PACKAGE, TYPE } )
+@Retention( RUNTIME )
+public @interface AnyMetaDefs {
+ AnyMetaDef[] value();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/BatchSize.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/BatchSize.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/BatchSize.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,19 @@
+//$Id: BatchSize.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.*;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * Batch size for SQL loading
+ *
+ * @author Emmanuel Bernard
+ */
+@Target({TYPE, METHOD, FIELD})
+@Retention(RUNTIME)
+public @interface BatchSize {
+ /** Strictly positive integer */
+ int size();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Cache.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Cache.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Cache.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,26 @@
+//$Id: Cache.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.*;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * Add caching strategy to a root entity or a collection
+ *
+ * @author Emmanuel Bernard
+ */
+@Target({TYPE, METHOD, FIELD})
+@Retention(RUNTIME)
+public @interface Cache {
+ /** concurrency strategy chosen */
+ CacheConcurrencyStrategy usage();
+ /** cache region name */
+ String region() default "";
+ /**
+ * whether or not lazy-properties are included in the second level cache
+ * default all, other value: non-lazy
+ */
+ String include() default "all";
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/CacheConcurrencyStrategy.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/CacheConcurrencyStrategy.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/CacheConcurrencyStrategy.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,15 @@
+//$Id: CacheConcurrencyStrategy.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+/**
+ * Cache concurrency strategy
+ *
+ * @author Emmanuel Bernard
+ */
+public enum CacheConcurrencyStrategy {
+ NONE,
+ READ_ONLY,
+ NONSTRICT_READ_WRITE,
+ READ_WRITE,
+ TRANSACTIONAL
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/CacheModeType.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/CacheModeType.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/CacheModeType.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,17 @@
+package org.hibernate.annotations;
+
+/**
+ * Enumeration for the different interaction modes between the session and
+ * the Level 2 Cache.
+ *
+ * @author Emmanuel Bernard
+ * @author Carlos Gonz�lez-Cadenas
+ */
+
+public enum CacheModeType {
+ GET,
+ IGNORE,
+ NORMAL,
+ PUT,
+ REFRESH
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Cascade.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Cascade.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Cascade.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,16 @@
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * Apply a cascade strategy on an association
+ */
+@Target({METHOD, FIELD})
+@Retention(RUNTIME)
+public @interface Cascade {
+ CascadeType[] value();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/CascadeType.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/CascadeType.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/CascadeType.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,18 @@
+package org.hibernate.annotations;
+
+/**
+ * Cascade types (can override default EJB3 cascades
+ */
+public enum CascadeType {
+ ALL,
+ PERSIST,
+ MERGE,
+ REMOVE,
+ REFRESH,
+ DELETE,
+ SAVE_UPDATE,
+ REPLICATE,
+ DELETE_ORPHAN,
+ LOCK,
+ EVICT
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Check.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Check.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Check.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,19 @@
+//$Id: Check.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.*;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * Arbitrary SQL check constraints which can be defined at the class,
+ * property or collection level
+ *
+ * @author Emmanuel Bernard
+ */
+@Target({TYPE, METHOD, FIELD})
+@Retention(RUNTIME)
+public @interface Check {
+ String constraints();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/CollectionId.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/CollectionId.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/CollectionId.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,26 @@
+//$Id: CollectionId.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import java.lang.annotation.Target;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.FIELD;
+import javax.persistence.Column;
+
+/**
+ * Describe an identifier column for a bag (ie an idbag)
+ * EXPERIMENTAL: the structure of this annotation might slightly change (generator() mix strategy and generator
+ *
+ * @author Emmanuel Bernard
+ */
+@Target({METHOD, FIELD})
+@Retention(RUNTIME)
+public @interface CollectionId {
+ /** Collection id column(s) */
+ Column[] columns();
+ /** id type, type.type() must be set */
+ Type type();
+ /** generator name: 'identity' or a defined generator name */
+ String generator();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/CollectionOfElements.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/CollectionOfElements.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/CollectionOfElements.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,28 @@
+//$Id: CollectionOfElements.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+import javax.persistence.FetchType;
+import static javax.persistence.FetchType.LAZY;
+
+/**
+ * Annotation used to mark a collection as a collection of elements or
+ * a collection of embedded objects
+ *
+ * @author Emmanuel Bernard
+ */
+@Target({METHOD, FIELD})
+@Retention(RUNTIME)
+public @interface CollectionOfElements {
+ /**
+ * Represent the element class in the collection
+ * Only useful if the collection does not use generics
+ */
+ Class targetElement() default void.class;
+
+ FetchType fetch() default LAZY;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Columns.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Columns.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Columns.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,20 @@
+//$Id: Columns.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+import javax.persistence.Column;
+
+/**
+ * Support an array of columns. Useful for component user types mappings
+ *
+ * @author Emmanuel Bernard
+ */
+@Target({METHOD, FIELD})
+@Retention(RUNTIME)
+public @interface Columns {
+ Column[] columns();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/DiscriminatorFormula.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/DiscriminatorFormula.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/DiscriminatorFormula.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,20 @@
+//$Id: DiscriminatorFormula.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.TYPE;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * Discriminator formula
+ * To be placed at the root entity.
+ *
+ * @author Emmanuel Bernard
+ * @see Formula
+ */
+@Target({TYPE})
+@Retention(RUNTIME)
+public @interface DiscriminatorFormula {
+ String value();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Entity.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Entity.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Entity.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,31 @@
+//$Id: Entity.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.TYPE;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * Extends {@link javax.persistence.Entity} with Hibernate features
+ *
+ * @author Emmanuel Bernard
+ */
+@Target(TYPE)
+@Retention(RUNTIME)
+public @interface Entity {
+ /** Is this entity mutable (read only) or not */
+ boolean mutable() default true;
+ /** Needed column only in SQL on insert */
+ boolean dynamicInsert() default false;
+ /** Needed column only in SQL on update */
+ boolean dynamicUpdate() default false;
+ /** Do a select to retrieve the entity before any potential update */
+ boolean selectBeforeUpdate() default false;
+ /** polymorphism strategy for this entity */
+ PolymorphismType polymorphism() default PolymorphismType.IMPLICIT;
+ /** persister of this entity, default is hibernate internal one */
+ String persister() default "";
+ /** optimistic locking strategy */
+ OptimisticLockType optimisticLock() default OptimisticLockType.VERSION;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Fetch.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Fetch.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Fetch.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,18 @@
+//$Id: Fetch.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import java.lang.annotation.Target;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+/**
+ * Define the fetching strategy used for the given association
+ *
+ * @author Emmanuel Bernard
+ */
+(a)Target({ElementType.METHOD, ElementType.FIELD})
+(a)Retention(RetentionPolicy.RUNTIME)
+public @interface Fetch {
+ FetchMode value();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/FetchMode.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/FetchMode.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/FetchMode.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,22 @@
+//$Id: FetchMode.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+/**
+ * Fetch options on associations
+ *
+ * @author Emmanuel Bernard
+ */
+public enum FetchMode {
+ /**
+ * use a select for each individual entity, collection, or join load
+ */
+ SELECT,
+ /**
+ * use an outer join to load the related entities, collections or joins
+ */
+ JOIN,
+ /**
+ * use a subselect query to load the additional collections
+ */
+ SUBSELECT
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Filter.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Filter.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Filter.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,22 @@
+//$Id: Filter.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.*;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * Add filters to an entity or a target entity of a collection
+ *
+ * @author Emmanuel Bernard
+ * @author Matthew Inger
+ * @author Magnus Sandberg
+ */
+@Target({TYPE, METHOD, FIELD})
+@Retention(RUNTIME)
+public @interface Filter {
+ String name();
+
+ String condition() default "";
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/FilterDef.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/FilterDef.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/FilterDef.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,24 @@
+//$Id: FilterDef.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.PACKAGE;
+import static java.lang.annotation.ElementType.TYPE;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * Filter definition
+ *
+ * @author Matthew Inger
+ * @author Emmanuel Bernard
+ */
+@Target({TYPE, PACKAGE})
+@Retention(RUNTIME)
+public @interface FilterDef {
+ String name();
+
+ String defaultCondition() default "";
+
+ ParamDef[] parameters() default {};
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/FilterDefs.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/FilterDefs.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/FilterDefs.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,20 @@
+//$Id: FilterDefs.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.PACKAGE;
+import static java.lang.annotation.ElementType.TYPE;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * Array of filter definitions
+ *
+ * @author Matthew Inger
+ * @author Emmanuel Bernard
+ */
+@Target({PACKAGE, TYPE})
+@Retention(RUNTIME)
+public @interface FilterDefs {
+ FilterDef[] value();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/FilterJoinTable.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/FilterJoinTable.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/FilterJoinTable.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,20 @@
+//$Id: FilterJoinTable.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import java.lang.annotation.Target;
+import java.lang.annotation.Retention;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.RetentionPolicy;
+
+/**
+ * Add filters to a join table collection
+ *
+ * @author Emmanuel Bernard
+ */
+(a)Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
+(a)Retention(RetentionPolicy.RUNTIME)
+public @interface FilterJoinTable {
+ String name();
+
+ String condition() default "";
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/FilterJoinTables.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/FilterJoinTables.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/FilterJoinTables.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,18 @@
+//$Id: FilterJoinTables.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import java.lang.annotation.Target;
+import java.lang.annotation.Retention;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.RetentionPolicy;
+
+/**
+ * Add multiple @FilterJoinTable to a collection
+ *
+ * @author Emmanuel Bernard
+ */
+(a)Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
+(a)Retention(RetentionPolicy.RUNTIME)
+public @interface FilterJoinTables {
+ FilterJoinTable[] value();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Filters.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Filters.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Filters.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,20 @@
+//$Id: Filters.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.*;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * Add multiple @Filters
+ *
+ * @author Emmanuel Bernard
+ * @author Matthew Inger
+ * @author Magnus Sandberg
+ */
+@Target({TYPE, METHOD, FIELD})
+@Retention(RUNTIME)
+public @interface Filters {
+ Filter[] value();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/FlushModeType.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/FlushModeType.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/FlushModeType.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,36 @@
+package org.hibernate.annotations;
+
+/**
+ * Enumeration extending javax.persistence flush modes.
+ *
+ * @author Carlos Gonz�lez-Cadenas
+ */
+
+public enum FlushModeType {
+ /**
+ * see {@link org.hibernate.FlushMode.ALWAYS}
+ */
+ ALWAYS,
+ /**
+ * see {@link org.hibernate.FlushMode.AUTO}
+ */
+ AUTO,
+ /**
+ * see {@link org.hibernate.FlushMode.COMMIT}
+ */
+ COMMIT,
+ /**
+ * see {@link org.hibernate.FlushMode.NEVER}
+ * @deprecated use MANUAL, will be removed in a subsequent release
+ */
+ NEVER,
+ /**
+ * see {@link org.hibernate.FlushMode.MANUAL}
+ */
+ MANUAL,
+
+ /**
+ * Current flush mode of the persistence context at the time the query is executed
+ */
+ PERSISTENCE_CONTEXT
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/ForceDiscriminator.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/ForceDiscriminator.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/ForceDiscriminator.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,16 @@
+//$Id: ForceDiscriminator.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import java.lang.annotation.Target;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+/**
+ * ForceDiscriminator flag
+ * To be placed at the root entity near @DiscriminatorColumn or @DiscriminatorFormula
+ *
+ * @author Serg Prasolov
+ */
+(a)Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME)
+public @interface ForceDiscriminator {}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/ForeignKey.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/ForeignKey.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/ForeignKey.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,29 @@
+//$Id: ForeignKey.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.TYPE;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+@Target({FIELD, METHOD, TYPE})
+@Retention(RUNTIME)
+
+/**
+ * Define the foreign key name
+ */
+public @interface ForeignKey {
+ /**
+ * Name of the foreign key. Used in OneToMany, ManyToOne, and OneToOne
+ * relationships. Used for the owning side in ManyToMany relationships
+ */
+ String name();
+
+ /**
+ * Used for the non-owning side of a ManyToMany relationship. Ignored
+ * in other relationships
+ */
+ String inverseName() default "";
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Formula.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Formula.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Formula.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,19 @@
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * Formula. To be used as a replacement for @Column in most places
+ * The formula has to be a valid SQL fragment
+ *
+ * @author Emmanuel Bernard
+ */
+@Target({METHOD, FIELD})
+@Retention(RUNTIME)
+public @interface Formula {
+ String value();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Generated.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Generated.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Generated.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,18 @@
+//$Id: Generated.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import java.lang.annotation.Target;
+import java.lang.annotation.Retention;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.RetentionPolicy;
+
+/**
+ * The annotated property is generated by the database
+ *
+ * @author Emmanuel Bernard
+ */
+(a)Target({ElementType.FIELD, ElementType.METHOD})
+(a)Retention(RetentionPolicy.RUNTIME)
+public @interface Generated {
+ GenerationTime value();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/GenerationTime.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/GenerationTime.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/GenerationTime.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,13 @@
+//$Id: GenerationTime.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+/**
+ * When should the generation occurs
+ *
+ * @author Emmanuel Bernard
+ */
+public enum GenerationTime {
+ NEVER,
+ INSERT,
+ ALWAYS
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/GenericGenerator.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/GenericGenerator.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/GenericGenerator.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,31 @@
+//$Id: GenericGenerator.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.*;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * Generator annotation describing any kind of Hibernate
+ * generator in a detyped manner
+ *
+ * @author Emmanuel Bernard
+ */
+@Target({PACKAGE, TYPE, METHOD, FIELD})
+@Retention(RUNTIME)
+public @interface GenericGenerator {
+ /**
+ * unique generator name
+ */
+ String name();
+ /**
+ * Generator strategy either a predefined Hibernate
+ * strategy or a fully qualified class name.
+ */
+ String strategy();
+ /**
+ * Optional generator parameters
+ */
+ Parameter[] parameters() default {};
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/GenericGenerators.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/GenericGenerators.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/GenericGenerators.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,21 @@
+//$
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.PACKAGE;
+import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+/**
+ * Array of generic generator definitions
+ *
+ * @author Paul Cowan
+ */
+@Target({PACKAGE, TYPE})
+@Retention(RUNTIME)
+public @interface GenericGenerators {
+ GenericGenerator[] value();
+}
+
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Immutable.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Immutable.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Immutable.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,22 @@
+//$Id: Immutable.java 14801 2008-06-24 19:03:32Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import java.lang.annotation.*;
+
+/**
+ * Mark an Entity or a Collection as immutable. No annotation means the element is mutable.
+ * <p>
+ * An immutable entity may not be updated by the application. Updates to an immutable
+ * entity will be ignored, but no exception is thrown. @Immutable must be used on root entities only.
+ * </p>
+ * <p>
+ * @Immutable placed on a collection makes the collection immutable, meaning additions and
+ * deletions to and from the collection are not allowed. A <i>HibernateException</i> is thrown in this case.
+ * </p>
+ *
+ * @author Emmanuel Bernard
+ */
+(a)java.lang.annotation.Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
+@Retention( RetentionPolicy.RUNTIME )
+public @interface Immutable {
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Index.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Index.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Index.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,20 @@
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * Define a DB index
+ *
+ * @author Emmanuel Bernard
+ */
+@Target({FIELD, METHOD})
+@Retention(RUNTIME)
+public @interface Index {
+ String name();
+
+ String[] columnNames() default {};
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/IndexColumn.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/IndexColumn.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/IndexColumn.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,25 @@
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * Describe an index column of a List
+ *
+ * @author Matthew Inger
+ */
+@Target({METHOD, FIELD})
+@Retention(RUNTIME)
+public @interface IndexColumn {
+ /** column name */
+ String name();
+ /** index in DB start from base */
+ int base() default 0;
+ /** is the index nullable */
+ boolean nullable() default true;
+ /** column definition, default to an appropriate integer */
+ String columnDefinition() default "";
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/LazyCollection.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/LazyCollection.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/LazyCollection.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,18 @@
+//$Id: LazyCollection.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import java.lang.annotation.Target;
+import java.lang.annotation.Retention;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.RetentionPolicy;
+
+/**
+ * Define the lazy status of a collection
+ *
+ * @author Emmanuel Bernard
+ */
+(a)Target({ElementType.METHOD, ElementType.FIELD})
+(a)Retention(RetentionPolicy.RUNTIME)
+public @interface LazyCollection {
+ LazyCollectionOption value();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/LazyCollectionOption.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/LazyCollectionOption.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/LazyCollectionOption.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,16 @@
+//$Id: LazyCollectionOption.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+/**
+ * Lazy options available for a collection
+ *
+ * @author Emmanuel Bernard
+ */
+public enum LazyCollectionOption {
+ /** eagerly load it */
+ FALSE,
+ /** load it when the state is requested */
+ TRUE,
+ /** prefer extra queries over fill collection loading */
+ EXTRA
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/LazyToOne.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/LazyToOne.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/LazyToOne.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,19 @@
+//$Id: LazyToOne.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import java.lang.annotation.Target;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+/**
+ * Define the lazy status of a ToOne association
+ * (ie OneToOne or ManyToOne)
+ *
+ * @author Emmanuel Bernard
+ */
+(a)Target({ElementType.METHOD, ElementType.FIELD})
+(a)Retention(RetentionPolicy.RUNTIME)
+public @interface LazyToOne {
+ LazyToOneOption value();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/LazyToOneOption.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/LazyToOneOption.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/LazyToOneOption.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,23 @@
+//$Id: LazyToOneOption.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+/**
+ * Lazy options available for a ToOne association
+ *
+ * @author Emmanuel Bernard
+ */
+public enum LazyToOneOption {
+ /** eagerly load the association */
+ FALSE,
+ /**
+ * Lazy, give back a proxy which will be loaded when the state is requested
+ * This should be the prefered option
+ */
+ PROXY,
+ /** Lazy, give back the real object loaded when a reference is requested
+ * (Bytecode enhancement is mandatory for this option, fall back to PROXY
+ * if the class is not enhanced)
+ * This option should be avoided unless you can't afford the use of proxies
+ */
+ NO_PROXY
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Loader.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Loader.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Loader.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,22 @@
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * Loader Annotation for overwriting Hibernate default FIND method
+ *
+ * @author L�szl� Benke
+ */
+@Target( {TYPE, FIELD, METHOD} )
+@Retention( RUNTIME )
+public @interface Loader {
+ /**
+ * namedQuery to use for loading
+ */
+ String namedQuery() default "";
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/ManyToAny.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/ManyToAny.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/ManyToAny.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,41 @@
+//$Id: ManyToAny.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.FIELD;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import javax.persistence.Column;
+import javax.persistence.FetchType;
+import static javax.persistence.FetchType.EAGER;
+
+/**
+ * Defined a ToMany association pointing to different entity types.
+ * Matching the according entity type is doe through a metadata discriminator column
+ * This kind of mapping should be only marginal.
+ *
+ * @author Emmanuel Bernard
+ */
+(a)java.lang.annotation.Target({METHOD, FIELD})
+@Retention(RUNTIME)
+public @interface ManyToAny {
+ /**
+ * Metadata definition used.
+ * If defined, should point to a @AnyMetaDef name
+ * If not defined, the local (ie in the same field or property) @AnyMetaDef is used
+ */
+ String metaDef() default "";
+
+ /**
+ * Metadata dicriminator column description, This column will hold the meta value corresponding to the
+ * targeted entity.
+ */
+ Column metaColumn();
+ /**
+ * Defines whether the value of the field or property should be lazily loaded or must be
+ * eagerly fetched. The EAGER strategy is a requirement on the persistence provider runtime
+ * that the value must be eagerly fetched. The LAZY strategy is applied when bytecode
+ * enhancement is used. If not specified, defaults to EAGER.
+ */
+ FetchType fetch() default EAGER;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/MapKey.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/MapKey.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/MapKey.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,32 @@
+//$Id: MapKey.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import java.lang.annotation.Target;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.FIELD;
+import javax.persistence.Column;
+
+/**
+ * Define the map key columns as an explicit column holding the map key
+ * This is completly different from {@link javax.persistence.MapKey} which use an existing column
+ * This annotation and {@link javax.persistence.MapKey} are mutually exclusive
+ *
+ * @author Emmanuel Bernard
+ */
+@Target({METHOD, FIELD})
+@Retention(RUNTIME)
+public @interface MapKey {
+ Column[] columns() default {};
+ /**
+ * Represent the key class in a Map
+ * Only useful if the collection does not use generics
+ */
+ Class targetElement() default void.class;
+
+ /**
+ * The optional map key type. Guessed if default
+ */
+ Type type() default @Type(type = "");
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/MapKeyManyToMany.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/MapKeyManyToMany.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/MapKeyManyToMany.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,26 @@
+//$Id: MapKeyManyToMany.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import javax.persistence.JoinColumn;
+
+/**
+ * Define the map key columns as an explicit column holding the map key
+ * This is completly different from {@link javax.persistence.MapKey} which use an existing column
+ * This annotation and {@link javax.persistence.MapKey} are mutually exclusive
+ *
+ * @author Emmanuel Bernard
+ */
+(a)Target({ElementType.METHOD, ElementType.FIELD})
+(a)Retention(RetentionPolicy.RUNTIME)
+public @interface MapKeyManyToMany {
+ JoinColumn[] joinColumns() default {};
+ /**
+ * Represent the key class in a Map
+ * Only useful if the collection does not use generics
+ */
+ Class targetEntity() default void.class;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/MetaValue.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/MetaValue.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/MetaValue.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,18 @@
+//$Id: MetaValue.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+/**
+ * Represent a discriminator value associated to a given entity type
+ * @author Emmanuel Bernard
+ */
+public @interface MetaValue {
+ /**
+ * entity type
+ */
+ Class targetEntity();
+
+ /**
+ * discriminator value stored in database
+ */
+ String value();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/NamedNativeQueries.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/NamedNativeQueries.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/NamedNativeQueries.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,19 @@
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.PACKAGE;
+import static java.lang.annotation.ElementType.TYPE;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * Extends {@link javax.persistence.NamedNativeQueries} to hold hibernate NamedNativeQuery
+ * objects
+ *
+ * @author Emmanuel Bernard
+ */
+@Target({TYPE, PACKAGE})
+@Retention(RUNTIME)
+public @interface NamedNativeQueries {
+ NamedNativeQuery[] value();
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/NamedNativeQuery.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/NamedNativeQuery.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/NamedNativeQuery.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,42 @@
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.PACKAGE;
+import static java.lang.annotation.ElementType.TYPE;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * Extends {@link javax.persistence.NamedNativeQuery} with Hibernate features
+ *
+ * @author Emmanuel Bernard
+ */
+@Target({TYPE, PACKAGE})
+@Retention(RUNTIME)
+public @interface NamedNativeQuery {
+ String name();
+
+ String query();
+
+ Class resultClass() default void.class;
+
+ String resultSetMapping() default ""; // name of SQLResultSetMapping
+ /** the flush mode for the query */
+ FlushModeType flushMode() default FlushModeType.PERSISTENCE_CONTEXT;
+ /** mark the query as cacheable or not */
+ boolean cacheable() default false;
+ /** the cache region to use */
+ String cacheRegion() default "";
+ /** the number of rows fetched by the JDBC Driver per roundtrip */
+ int fetchSize() default -1;
+ /**the query timeout in seconds*/
+ int timeout() default -1;
+
+ boolean callable() default false;
+ /**comment added to the SQL query, useful for the DBA */
+ String comment() default "";
+ /**the cache mode used for this query*/
+ CacheModeType cacheMode() default CacheModeType.NORMAL;
+ /**marks whether the results are fetched in read-only mode or not*/
+ boolean readOnly() default false;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/NamedQueries.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/NamedQueries.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/NamedQueries.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,20 @@
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.PACKAGE;
+import static java.lang.annotation.ElementType.TYPE;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * Extends {@link javax.persistence.NamedQueries} to hold hibernate NamedQuery
+ * objects
+ *
+ * @author Emmanuel Bernard
+ * @author Carlos Gonz�lez-Cadenas
+ */
+@Target({TYPE, PACKAGE})
+@Retention(RUNTIME)
+public @interface NamedQueries {
+ NamedQuery[] value();
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/NamedQuery.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/NamedQuery.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/NamedQuery.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,40 @@
+//$Id: NamedQuery.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.PACKAGE;
+import static java.lang.annotation.ElementType.TYPE;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * Extends {@link javax.persistence.NamedQuery} with Hibernate features
+ *
+ * @author Carlos Gonz�lez-Cadenas
+ */
+@Target({TYPE, PACKAGE})
+@Retention(RUNTIME)
+public @interface NamedQuery {
+
+ /** the name of the NamedQuery */
+ String name();
+ /** the Query String for the NamedQuery */
+ String query();
+ /** the flush mode for the query */
+ FlushModeType flushMode() default FlushModeType.PERSISTENCE_CONTEXT;
+ /** mark the query as cacheable or not */
+ boolean cacheable() default false;
+ /** the cache region to use */
+ String cacheRegion() default "";
+ /** the number of rows fetched by the JDBC Driver per roundtrip */
+ int fetchSize() default -1;
+ /**the query timeout in seconds*/
+ int timeout() default -1;
+ /**comment added to the SQL query, useful for the DBA */
+ String comment() default "";
+ /**the cache mode used for this query*/
+ CacheModeType cacheMode() default CacheModeType.NORMAL;
+ /**marks whether the results are fetched in read-only mode or not*/
+ boolean readOnly() default false;
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/NaturalId.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/NaturalId.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/NaturalId.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,22 @@
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+
+/**
+ * This specifies that a property is part of the natural id of the entity.
+ *
+ * @author Nicol�s Lichtmaier
+ */
+@Target( { METHOD, FIELD } )
+@Retention( RUNTIME )
+public @interface NaturalId {
+ /**
+ * If this natural id component is mutable or not.
+ */
+ boolean mutable() default false;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/NotFound.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/NotFound.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/NotFound.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,18 @@
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * Action to do when an element is not found on a association whiel beeing expected
+ *
+ * @author Emmanuel Bernard
+ */
+@Target({METHOD, FIELD})
+@Retention(RUNTIME)
+public @interface NotFound {
+ NotFoundAction action() default NotFoundAction.EXCEPTION;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/NotFoundAction.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/NotFoundAction.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/NotFoundAction.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,17 @@
+package org.hibernate.annotations;
+
+/**
+ * Actoin to use when an element is not found in DB while beeing expected
+ *
+ * @author Emmanuel Bernard
+ */
+public enum NotFoundAction {
+ /**
+ * raise an exception when an element is not found (default and recommended)
+ */
+ EXCEPTION,
+ /**
+ * ignore the element when not found in DB
+ */
+ IGNORE
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/OnDelete.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/OnDelete.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/OnDelete.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,19 @@
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.*;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+
+/**
+ * Strategy to use on collections, arrays and on joined subclasses delete
+ * OnDelete of secondary tables currently not supported.
+ *
+ * @author Emmanuel Bernard
+ */
+@Target({METHOD, FIELD, TYPE})
+@Retention(RUNTIME)
+public @interface OnDelete {
+ OnDeleteAction action();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/OnDeleteAction.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/OnDeleteAction.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/OnDeleteAction.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,17 @@
+package org.hibernate.annotations;
+
+/**
+ * Possible actions on deletes
+ *
+ * @author Emmanuel Bernard
+ */
+public enum OnDeleteAction {
+ /**
+ * the default
+ */
+ NO_ACTION,
+ /**
+ * use cascade delete capabilities of the DD
+ */
+ CASCADE
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/OptimisticLock.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/OptimisticLock.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/OptimisticLock.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,24 @@
+//$Id: OptimisticLock.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Whether or not update entity's version on property's change
+ * If the annotation is not present, the property is involved in the optimistic lock srategy (default)
+ *
+ * @author Logi Ragnarsson
+ */
+@Target( {ElementType.METHOD, ElementType.FIELD} )
+@Retention( RetentionPolicy.RUNTIME )
+public @interface OptimisticLock {
+
+ /**
+ * If true, the annotated property change will not trigger a version upgrade
+ */
+ boolean excluded();
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/OptimisticLockType.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/OptimisticLockType.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/OptimisticLockType.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,27 @@
+//$Id: OptimisticLockType.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+/**
+ * Optimistic locking strategy
+ * VERSION is the default and recommanded one
+ *
+ * @author Emmanuel Bernard
+ */
+public enum OptimisticLockType {
+ /**
+ * no optimistic locking
+ */
+ NONE,
+ /**
+ * use a column version
+ */
+ VERSION,
+ /**
+ * dirty columns are compared
+ */
+ DIRTY,
+ /**
+ * all columns are compared
+ */
+ ALL
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/OrderBy.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/OrderBy.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/OrderBy.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,19 @@
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * Order a collection using SQL ordering (not HQL ordering)
+ *
+ * @author Emmanuel Bernard
+ */
+@Target({METHOD, FIELD})
+@Retention(RUNTIME)
+public @interface OrderBy {
+ /** SQL orderby clause */
+ String clause();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/ParamDef.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/ParamDef.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/ParamDef.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,19 @@
+//$Id: ParamDef.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * A parameter definition
+ *
+ * @author Emmanuel Bernard
+ */
+@Target({})
+@Retention(RUNTIME)
+public @interface ParamDef {
+ String name();
+
+ String type();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Parameter.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Parameter.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Parameter.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,19 @@
+//$Id: Parameter.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * Parameter (basically key/value pattern)
+ *
+ * @author Emmanuel Bernard
+ */
+@Target({})
+@Retention(RUNTIME)
+public @interface Parameter {
+ String name();
+
+ String value();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Parent.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Parent.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Parent.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,18 @@
+//$Id: Parent.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * Reference the property as a pointer back to the owner (generally the owning entity)
+ *
+ * @author Emmanuel Bernard
+ */
+@Target({METHOD, FIELD})
+@Retention(RUNTIME)
+public @interface Parent {
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Persister.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Persister.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Persister.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,16 @@
+//$Id: Persister.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import java.lang.annotation.*;
+
+/**
+ * Specify a custom persister.
+ *
+ * @author Shawn Clowater
+ */
+(a)java.lang.annotation.Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
+@Retention( RetentionPolicy.RUNTIME )
+public @interface Persister {
+ /** Custom persister */
+ Class impl();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/PolymorphismType.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/PolymorphismType.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/PolymorphismType.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,18 @@
+//$Id: PolymorphismType.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+/**
+ * Type of avaliable polymorphism for a particular entity
+ *
+ * @author Emmanuel Bernard
+ */
+public enum PolymorphismType {
+ /**
+ * default, this entity is retrieved if any of its super entity is asked
+ */
+ IMPLICIT,
+ /**
+ * this entity is retrived only if explicitly asked
+ */
+ EXPLICIT
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Proxy.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Proxy.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Proxy.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,26 @@
+//$Id: Proxy.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.TYPE;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * Lazy and proxy configuration of a particular class
+ *
+ * @author Emmanuel Bernard
+ */
+@Target(TYPE)
+@Retention(RUNTIME)
+public @interface Proxy {
+ /**
+ * Whether this class is lazy or not (default to true)
+ */
+ boolean lazy() default true;
+
+ /**
+ * Proxy class or interface used. Default entity class name.
+ */
+ Class proxyClass() default void.class;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/ResultCheckStyle.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/ResultCheckStyle.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/ResultCheckStyle.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,31 @@
+//$Id:
+package org.hibernate.annotations;
+
+/**
+ * Possible checks on Sql Insert, Delete, Update
+ *
+ * @author L�szl� Benke
+ */
+public enum ResultCheckStyle {
+ /**
+ * Do not perform checking. Either user simply does not want checking, or is
+ * indicating a {@link java.sql.CallableStatement} execution in which the
+ * checks are being performed explicitly and failures are handled through
+ * propogation of {@link java.sql.SQLException}s.
+ */
+ NONE,
+ /**
+ * Perform row-count checking. Row counts are the int values returned by both
+ * {@link java.sql.PreparedStatement#executeUpdate()} and
+ * {@link java.sql.Statement#executeBatch()}. These values are checked
+ * against some expected count.
+ */
+ COUNT,
+ /**
+ * Essentially the same as {@link #COUNT} except that the row count actually
+ * comes from an output parameter registered as part of a
+ * {@link java.sql.CallableStatement}. This style explicitly prohibits
+ * statement batching from being used...
+ */
+ PARAM
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/SQLDelete.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/SQLDelete.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/SQLDelete.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,33 @@
+//$Id: SQLDelete.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * SqlDelete Annotation for overwriting Hibernate default DELETE method
+ *
+ * @author L�szl� Benke
+ */
+@Target( {TYPE, FIELD, METHOD} )
+@Retention( RUNTIME )
+public @interface SQLDelete {
+ /**
+ * Procedure name or DELETE STATEMENT
+ */
+ String sql();
+
+ /**
+ * Is the statement using stored procedure or not
+ */
+ boolean callable() default false;
+
+ /**
+ * For persistence operation what style of determining results (success/failure) is to be used.
+ */
+ ResultCheckStyle check() default ResultCheckStyle.NONE;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/SQLDeleteAll.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/SQLDeleteAll.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/SQLDeleteAll.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,34 @@
+//$Id: SQLDeleteAll.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.TYPE;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * SqlDelete Annotation for overwriting Hibernate default DELETE ALL method
+ *
+ * @author L�szl� Benke
+ */
+@Target( {TYPE, FIELD, METHOD} )
+@Retention( RetentionPolicy.RUNTIME )
+public @interface SQLDeleteAll {
+ /**
+ * Procedure name or DELETE STATEMENT
+ */
+ String sql();
+
+ /**
+ * Is the statement using stored procedure or not
+ */
+ boolean callable() default false;
+
+ /**
+ * For persistence operation what style of determining results (success/failure) is to be used.
+ */
+ ResultCheckStyle check() default ResultCheckStyle.NONE;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/SQLInsert.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/SQLInsert.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/SQLInsert.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,33 @@
+//$Id: SQLInsert.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * SqlInsert Annotation for overwriting Hibernate default INSERT INTO method
+ *
+ * @author L�szl� Benke
+ */
+@Target( {TYPE, FIELD, METHOD} )
+@Retention( RUNTIME )
+public @interface SQLInsert {
+ /**
+ * Procedure name or INSERT STATEMENT
+ */
+ String sql();
+
+ /**
+ * Is the statement using stored procedure or not
+ */
+ boolean callable() default false;
+
+ /**
+ * For persistence operation what style of determining results (success/failure) is to be used.
+ */
+ ResultCheckStyle check() default ResultCheckStyle.NONE;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/SQLUpdate.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/SQLUpdate.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/SQLUpdate.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,34 @@
+//$Id: SQLUpdate.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * SqlUpdate Annotation for overwriting Hibernate default UPDATE method
+ *
+ * @author L�szl� Benke
+ */
+@Target( {TYPE, FIELD, METHOD} )
+@Retention( RUNTIME )
+public @interface SQLUpdate {
+
+ /**
+ * Procedure name or UPDATE STATEMENT
+ */
+ String sql();
+
+ /**
+ * Is the statement using stored procedure or not
+ */
+ boolean callable() default false;
+
+ /**
+ * For persistence operation what style of determining results (success/failure) is to be used.
+ */
+ ResultCheckStyle check() default ResultCheckStyle.NONE;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Sort.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Sort.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Sort.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,29 @@
+//$Id: Sort.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * Collection sort
+ * (Java level sorting)
+ *
+ * @author Emmanuel Bernard
+ */
+@Target({METHOD, FIELD})
+@Retention(RUNTIME)
+public @interface Sort {
+ /**
+ * sort type
+ */
+ SortType type() default SortType.UNSORTED;
+ /**
+ * Sort comparator implementation
+ */
+ //TODO find a way to use Class<Comparator>
+
+ Class comparator() default void.class;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/SortType.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/SortType.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/SortType.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,13 @@
+//$Id: SortType.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+/**
+ * Sort strategies
+ *
+ * @author Emmanuel Bernard
+ */
+public enum SortType {
+ UNSORTED,
+ NATURAL,
+ COMPARATOR
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Table.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Table.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Table.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,86 @@
+//$Id: Table.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.TYPE;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * Complementary information to a table either primary or secondary
+ *
+ * @author Emmanuel Bernard
+ */
+@Target({TYPE})
+@Retention(RUNTIME)
+public @interface Table {
+ /**
+ * name of the targeted table
+ */
+ String appliesTo();
+
+ /**
+ * Indexes
+ */
+ Index[] indexes() default {};
+
+ /**
+ * define a table comment
+ */
+ String comment() default "";
+
+ /**
+ * Defines the Foreign Key name of a secondary table
+ * pointing back to the primary table
+ */
+ ForeignKey foreignKey() default @ForeignKey( name="" );
+
+ /**
+ * If set to JOIN, the default, Hibernate will use an inner join to retrieve a
+ * secondary table defined by a class or its superclasses and an outer join for a
+ * secondary table defined by a subclass.
+ * If set to select then Hibernate will use a
+ * sequential select for a secondary table defined on a subclass, which will be issued only if a row
+ * turns out to represent an instance of the subclass. Inner joins will still be used to retrieve a
+ * secondary defined by the class and its superclasses.
+ *
+ * <b>Only applies to secondary tables</b>
+ */
+ FetchMode fetch() default FetchMode.JOIN;
+
+ /**
+ * If true, Hibernate will not try to insert or update the properties defined by this join.
+ *
+ * <b>Only applies to secondary tables</b>
+ */
+ boolean inverse() default false;
+
+ /**
+ * If enabled, Hibernate will insert a row only if the properties defined by this join are non-null
+ * and will always use an outer join to retrieve the properties.
+ *
+ * <b>Only applies to secondary tables</b>
+ */
+ boolean optional() default true;
+
+ /**
+ * Defines a custom SQL insert statement
+ *
+ * <b>Only applies to secondary tables</b>
+ */
+ SQLInsert sqlInsert() default @SQLInsert(sql="");
+
+ /**
+ * Defines a custom SQL update statement
+ *
+ * <b>Only applies to secondary tables</b>
+ */
+ SQLUpdate sqlUpdate() default @SQLUpdate(sql="");
+
+ /**
+ * Defines a custom SQL delete statement
+ *
+ * <b>Only applies to secondary tables</b>
+ */
+ SQLDelete sqlDelete() default @SQLDelete(sql="");
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Tables.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Tables.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Tables.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,18 @@
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.TYPE;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * Plural of Table
+ *
+ * @author Emmanuel Bernard
+ * @see Table
+ */
+@Target({TYPE})
+@Retention(RUNTIME)
+public @interface Tables {
+ Table[] value();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Target.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Target.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Target.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,17 @@
+//$Id: Target.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.RetentionPolicy;
+
+/**
+ * Define an explicit target,a voiding reflection and generics resolving
+ *
+ * @author Emmanuel Bernard
+ */
+(a)java.lang.annotation.Target({ElementType.FIELD, ElementType.METHOD})
+@Retention( RetentionPolicy.RUNTIME )
+public @interface Target {
+ Class value();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Tuplizer.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Tuplizer.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Tuplizer.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,21 @@
+//$Id: Tuplizer.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import java.lang.annotation.*;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+
+/**
+ * Define a tuplizer for an entity or a component
+ * @author Emmanuel Bernard
+ */
+(a)java.lang.annotation.Target( {TYPE, FIELD, METHOD} )
+@Retention( RUNTIME )
+public @interface Tuplizer {
+ /** tuplizer implementation */
+ Class impl();
+ /** either pojo, dynamic-map or dom4j� */
+ String entityMode() default "pojo";
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Tuplizers.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Tuplizers.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Tuplizers.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,16 @@
+//$Id: Tuplizers.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.RetentionPolicy;
+
+/**
+ * Define a set of tuplizer for an entity or a component
+ * @author Emmanuel Bernard
+ */
+(a)java.lang.annotation.Target( {ElementType.TYPE, ElementType.FIELD, ElementType.METHOD} )
+@Retention( RetentionPolicy.RUNTIME )
+public @interface Tuplizers {
+ Tuplizer[] value();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Type.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Type.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Type.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,21 @@
+//$Id: Type.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * hibernate type
+ *
+ * @author Emmanuel Bernard
+ */
+@Target({FIELD, METHOD})
+@Retention(RUNTIME)
+public @interface Type {
+ String type();
+
+ Parameter[] parameters() default {};
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/TypeDef.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/TypeDef.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/TypeDef.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,23 @@
+//$Id: TypeDef.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.PACKAGE;
+import static java.lang.annotation.ElementType.TYPE;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * Type definition
+ *
+ * @author Emmanuel Bernard
+ */
+@Target({TYPE, PACKAGE})
+@Retention(RUNTIME)
+public @interface TypeDef {
+ String name();
+
+ Class typeClass();
+
+ Parameter[] parameters() default {};
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/TypeDefs.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/TypeDefs.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/TypeDefs.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,19 @@
+//$Id: TypeDefs.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.PACKAGE;
+import static java.lang.annotation.ElementType.TYPE;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * Type definition array
+ *
+ * @author Emmanuel Bernard
+ */
+@Target({TYPE, PACKAGE})
+@Retention(RUNTIME)
+public @interface TypeDefs {
+ TypeDef[] value();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Where.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Where.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/Where.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,18 @@
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.*;
+import java.lang.annotation.Retention;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Target;
+
+/**
+ * Where clause to add to the element Entity or target entity of a collection
+ * The clause is written in SQL
+ *
+ * @author Emmanuel Bernard
+ */
+@Target({TYPE, METHOD, FIELD})
+@Retention(RUNTIME)
+public @interface Where {
+ String clause();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/WhereJoinTable.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/WhereJoinTable.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/annotations/WhereJoinTable.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,19 @@
+//$Id: WhereJoinTable.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.annotations;
+
+import java.lang.annotation.Target;
+import java.lang.annotation.Retention;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.RetentionPolicy;
+
+/**
+ * Where clause to add to the colleciton join table
+ * The clause is written in SQL
+ *
+ * @author Emmanuel Bernard
+ */
+(a)Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
+(a)Retention(RetentionPolicy.RUNTIME)
+public @interface WhereJoinTable {
+ String clause();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/AbstractPropertyHolder.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/AbstractPropertyHolder.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/AbstractPropertyHolder.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,188 @@
+//$Id: AbstractPropertyHolder.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.cfg;
+
+import java.util.HashMap;
+import java.util.Map;
+import javax.persistence.AssociationOverride;
+import javax.persistence.AssociationOverrides;
+import javax.persistence.AttributeOverride;
+import javax.persistence.AttributeOverrides;
+import javax.persistence.Column;
+import javax.persistence.Embeddable;
+import javax.persistence.Entity;
+import javax.persistence.JoinColumn;
+import javax.persistence.MappedSuperclass;
+
+import org.hibernate.AssertionFailure;
+import org.hibernate.annotations.common.reflection.XAnnotatedElement;
+import org.hibernate.annotations.common.reflection.XClass;
+import org.hibernate.annotations.common.reflection.XProperty;
+import org.hibernate.util.StringHelper;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public abstract class AbstractPropertyHolder implements PropertyHolder {
+ protected PropertyHolder parent;
+ private Map<String, Column[]> holderColumnOverride;
+ private Map<String, Column[]> currentPropertyColumnOverride;
+ private Map<String, JoinColumn[]> holderJoinColumnOverride;
+ private Map<String, JoinColumn[]> currentPropertyJoinColumnOverride;
+ private String path;
+ private ExtendedMappings mappings;
+
+ public AbstractPropertyHolder(
+ String path, PropertyHolder parent, XClass clazzToProcess, ExtendedMappings mappings
+ ) {
+ this.path = path;
+ this.parent = parent;
+ this.mappings = mappings;
+ buildHierarchyColumnOverride( clazzToProcess );
+ }
+
+ public String getPath() {
+ return path;
+ }
+
+ /**
+ * property can be null
+ */
+ protected void setCurrentProperty(XProperty property) {
+ if ( property == null ) {
+ this.currentPropertyColumnOverride = null;
+ this.currentPropertyJoinColumnOverride = null;
+ }
+ else {
+ this.currentPropertyColumnOverride = buildColumnOverride(
+ property,
+ getPath()
+ );
+ if ( this.currentPropertyColumnOverride.size() == 0 ) {
+ this.currentPropertyColumnOverride = null;
+ }
+ this.currentPropertyJoinColumnOverride = buildJoinColumnOverride(
+ property,
+ getPath()
+ );
+ if ( this.currentPropertyJoinColumnOverride.size() == 0 ) {
+ this.currentPropertyJoinColumnOverride = null;
+ }
+ }
+ }
+
+ /**
+ * Get column overriding, property first, then parent, then holder
+ */
+ public Column[] getOverriddenColumn(String propertyName) {
+ Column[] override = null;
+ if ( parent != null ) {
+ override = parent.getOverriddenColumn( propertyName );
+ }
+ if ( override == null && currentPropertyColumnOverride != null ) {
+ override = currentPropertyColumnOverride.get( propertyName );
+ }
+ if ( override == null && holderColumnOverride != null ) {
+ override = holderColumnOverride.get( propertyName );
+ }
+ return override;
+ }
+
+ /**
+ * Get column overriding, property first, then parent, then holder
+ */
+ public JoinColumn[] getOverriddenJoinColumn(String propertyName) {
+ JoinColumn[] override = null;
+ if ( parent != null ) {
+ override = parent.getOverriddenJoinColumn( propertyName );
+ }
+ if ( override == null && currentPropertyJoinColumnOverride != null ) {
+ override = currentPropertyJoinColumnOverride.get( propertyName );
+ }
+ if ( override == null && holderJoinColumnOverride != null ) {
+ override = holderJoinColumnOverride.get( propertyName );
+ }
+ return override;
+ }
+
+ private void buildHierarchyColumnOverride(XClass element) {
+ XClass current = element;
+ Map<String, Column[]> columnOverride = new HashMap<String, Column[]>();
+ Map<String, JoinColumn[]> joinColumnOverride = new HashMap<String, JoinColumn[]>();
+ while ( current != null && !mappings.getReflectionManager().toXClass( Object.class ).equals( current ) ) {
+ if ( current.isAnnotationPresent( Entity.class ) || current.isAnnotationPresent( MappedSuperclass.class )
+ || current.isAnnotationPresent( Embeddable.class ) ) {
+ //FIXME is embeddable override?
+ Map<String, Column[]> currentOverride = buildColumnOverride( current, getPath() );
+ Map<String, JoinColumn[]> currentJoinOverride = buildJoinColumnOverride( current, getPath() );
+ currentOverride.putAll( columnOverride ); //subclasses have precedence over superclasses
+ currentJoinOverride.putAll( joinColumnOverride ); //subclasses have precedence over superclasses
+ columnOverride = currentOverride;
+ joinColumnOverride = currentJoinOverride;
+ }
+ current = current.getSuperclass();
+ }
+
+ holderColumnOverride = columnOverride.size() > 0 ? columnOverride : null;
+ holderJoinColumnOverride = joinColumnOverride.size() > 0 ? joinColumnOverride : null;
+ }
+
+ private static Map<String, Column[]> buildColumnOverride(XAnnotatedElement element, String path) {
+ Map<String, Column[]> columnOverride = new HashMap<String, Column[]>();
+ if ( element == null ) return columnOverride;
+ AttributeOverride singleOverride = element.getAnnotation( AttributeOverride.class );
+ AttributeOverrides multipleOverrides = element.getAnnotation( AttributeOverrides.class );
+ AttributeOverride[] overrides;
+ if ( singleOverride != null ) {
+ overrides = new AttributeOverride[] { singleOverride };
+ }
+ else if ( multipleOverrides != null ) {
+ overrides = multipleOverrides.value();
+ }
+ else {
+ overrides = null;
+ }
+
+ //fill overriden columns
+ if ( overrides != null ) {
+ for (AttributeOverride depAttr : overrides) {
+ columnOverride.put(
+ StringHelper.qualify( path, depAttr.name() ),
+ new Column[] { depAttr.column() }
+ );
+ }
+ }
+ return columnOverride;
+ }
+
+ private static Map<String, JoinColumn[]> buildJoinColumnOverride(XAnnotatedElement element, String path) {
+ Map<String, JoinColumn[]> columnOverride = new HashMap<String, JoinColumn[]>();
+ if ( element == null ) return columnOverride;
+ AssociationOverride singleOverride = element.getAnnotation( AssociationOverride.class );
+ AssociationOverrides multipleOverrides = element.getAnnotation( AssociationOverrides.class );
+ AssociationOverride[] overrides;
+ if ( singleOverride != null ) {
+ overrides = new AssociationOverride[] { singleOverride };
+ }
+ else if ( multipleOverrides != null ) {
+ overrides = multipleOverrides.value();
+ }
+ else {
+ overrides = null;
+ }
+
+ //fill overriden columns
+ if ( overrides != null ) {
+ for (AssociationOverride depAttr : overrides) {
+ columnOverride.put(
+ StringHelper.qualify( path, depAttr.name() ),
+ depAttr.joinColumns()
+ );
+ }
+ }
+ return columnOverride;
+ }
+
+ public void setParentProperty(String parentProperty) {
+ throw new AssertionFailure( "Setting the parent property to a non component" );
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/AnnotatedClassType.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/AnnotatedClassType.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/AnnotatedClassType.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,25 @@
+package org.hibernate.cfg;
+
+/**
+ * Type of annotation of a class will give its type
+ *
+ * @author Emmanuel Bernard
+ */
+public enum AnnotatedClassType {
+ /**
+ * has no revelent top level annotation
+ */
+ NONE,
+ /**
+ * has @Entity annotation
+ */
+ ENTITY,
+ /**
+ * has a @Embeddable annotation
+ */
+ EMBEDDABLE,
+ /**
+ * has @EmbeddedSuperclass annotation
+ */
+ EMBEDDABLE_SUPERCLASS
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/AnnotationBinder.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/AnnotationBinder.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/AnnotationBinder.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,2321 @@
+//$Id: AnnotationBinder.java 14786 2008-06-19 14:59:11Z hardy.ferentschik $
+package org.hibernate.cfg;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import javax.persistence.Basic;
+import javax.persistence.Column;
+import javax.persistence.DiscriminatorType;
+import javax.persistence.DiscriminatorValue;
+import javax.persistence.Embeddable;
+import javax.persistence.Embedded;
+import javax.persistence.EmbeddedId;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.IdClass;
+import javax.persistence.InheritanceType;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinColumns;
+import javax.persistence.JoinTable;
+import javax.persistence.ManyToMany;
+import javax.persistence.ManyToOne;
+import javax.persistence.MapKey;
+import javax.persistence.MappedSuperclass;
+import javax.persistence.NamedNativeQueries;
+import javax.persistence.NamedNativeQuery;
+import javax.persistence.NamedQueries;
+import javax.persistence.NamedQuery;
+import javax.persistence.OneToMany;
+import javax.persistence.OneToOne;
+import javax.persistence.PrimaryKeyJoinColumn;
+import javax.persistence.PrimaryKeyJoinColumns;
+import javax.persistence.SequenceGenerator;
+import javax.persistence.SqlResultSetMapping;
+import javax.persistence.SqlResultSetMappings;
+import javax.persistence.Table;
+import javax.persistence.TableGenerator;
+import javax.persistence.Transient;
+import javax.persistence.Version;
+
+import org.hibernate.AnnotationException;
+import org.hibernate.AssertionFailure;
+import org.hibernate.EntityMode;
+import org.hibernate.FetchMode;
+import org.hibernate.MappingException;
+import org.hibernate.annotations.AccessType;
+import org.hibernate.annotations.BatchSize;
+import org.hibernate.annotations.Cache;
+import org.hibernate.annotations.Cascade;
+import org.hibernate.annotations.CascadeType;
+import org.hibernate.annotations.Check;
+import org.hibernate.annotations.CollectionId;
+import org.hibernate.annotations.CollectionOfElements;
+import org.hibernate.annotations.Columns;
+import org.hibernate.annotations.Fetch;
+import org.hibernate.annotations.Filter;
+import org.hibernate.annotations.FilterDef;
+import org.hibernate.annotations.FilterDefs;
+import org.hibernate.annotations.Filters;
+import org.hibernate.annotations.ForeignKey;
+import org.hibernate.annotations.Formula;
+import org.hibernate.annotations.GenericGenerator;
+import org.hibernate.annotations.Index;
+import org.hibernate.annotations.LazyToOne;
+import org.hibernate.annotations.LazyToOneOption;
+import org.hibernate.annotations.ManyToAny;
+import org.hibernate.annotations.MapKeyManyToMany;
+import org.hibernate.annotations.NaturalId;
+import org.hibernate.annotations.NotFound;
+import org.hibernate.annotations.NotFoundAction;
+import org.hibernate.annotations.OnDelete;
+import org.hibernate.annotations.OnDeleteAction;
+import org.hibernate.annotations.OrderBy;
+import org.hibernate.annotations.ParamDef;
+import org.hibernate.annotations.Parameter;
+import org.hibernate.annotations.Parent;
+import org.hibernate.annotations.Proxy;
+import org.hibernate.annotations.Sort;
+import org.hibernate.annotations.Target;
+import org.hibernate.annotations.Tuplizer;
+import org.hibernate.annotations.Tuplizers;
+import org.hibernate.annotations.Type;
+import org.hibernate.annotations.TypeDef;
+import org.hibernate.annotations.TypeDefs;
+import org.hibernate.annotations.Where;
+import org.hibernate.annotations.GenericGenerators;
+import org.hibernate.annotations.common.reflection.ReflectionManager;
+import org.hibernate.annotations.common.reflection.XAnnotatedElement;
+import org.hibernate.annotations.common.reflection.XClass;
+import org.hibernate.annotations.common.reflection.XPackage;
+import org.hibernate.annotations.common.reflection.XProperty;
+import org.hibernate.cfg.annotations.CollectionBinder;
+import org.hibernate.cfg.annotations.EntityBinder;
+import org.hibernate.cfg.annotations.Nullability;
+import org.hibernate.cfg.annotations.PropertyBinder;
+import org.hibernate.cfg.annotations.QueryBinder;
+import org.hibernate.cfg.annotations.SimpleValueBinder;
+import org.hibernate.cfg.annotations.TableBinder;
+import org.hibernate.engine.FilterDefinition;
+import org.hibernate.engine.Versioning;
+import org.hibernate.id.MultipleHiLoPerTableGenerator;
+import org.hibernate.id.PersistentIdentifierGenerator;
+import org.hibernate.id.SequenceHiLoGenerator;
+import org.hibernate.id.TableHiLoGenerator;
+import org.hibernate.mapping.Any;
+import org.hibernate.mapping.Component;
+import org.hibernate.mapping.DependantValue;
+import org.hibernate.mapping.IdGenerator;
+import org.hibernate.mapping.Join;
+import org.hibernate.mapping.JoinedSubclass;
+import org.hibernate.mapping.KeyValue;
+import org.hibernate.mapping.PersistentClass;
+import org.hibernate.mapping.Property;
+import org.hibernate.mapping.RootClass;
+import org.hibernate.mapping.SimpleValue;
+import org.hibernate.mapping.SingleTableSubclass;
+import org.hibernate.mapping.Subclass;
+import org.hibernate.mapping.ToOne;
+import org.hibernate.mapping.UnionSubclass;
+import org.hibernate.persister.entity.JoinedSubclassEntityPersister;
+import org.hibernate.persister.entity.SingleTableEntityPersister;
+import org.hibernate.persister.entity.UnionSubclassEntityPersister;
+import org.hibernate.type.TypeFactory;
+import org.hibernate.util.StringHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * JSR 175 annotation binder
+ * Will read the annotation from classes, apply the
+ * principles of the EJB3 spec and produces the Hibernate
+ * configuration-time metamodel (the classes in the <tt>mapping</tt>
+ * package)
+ *
+ * @author Emmanuel Bernard
+ */
+@SuppressWarnings("unchecked")
+public final class AnnotationBinder {
+
+ /*
+ * Some design description
+ * I tried to remove any link to annotation except from the 2 first level of
+ * method call.
+ * It'll enable to:
+ * - facilitate annotation overriding
+ * - mutualize one day xml and annotation binder (probably a dream though)
+ * - split this huge class in smaller mapping oriented classes
+ *
+ * bindSomething usually create the mapping container and is accessed by one of the 2 first level method
+ * makeSomething usually create the mapping container and is accessed by bindSomething[else]
+ * fillSomething take the container into parameter and fill it.
+ *
+ *
+ */
+ private AnnotationBinder() {
+ }
+
+ private static final Logger log = LoggerFactory.getLogger( AnnotationBinder.class );
+
+ public static void bindDefaults(ExtendedMappings mappings) {
+ Map defaults = mappings.getReflectionManager().getDefaults();
+ {
+ List<SequenceGenerator> anns = (List<SequenceGenerator>) defaults.get( SequenceGenerator.class );
+ if ( anns != null ) {
+ for (SequenceGenerator ann : anns) {
+ IdGenerator idGen = buildIdGenerator( ann, mappings );
+ if ( idGen != null ) mappings.addDefaultGenerator( idGen );
+ }
+ }
+ }
+ {
+ List<TableGenerator> anns = (List<TableGenerator>) defaults.get( TableGenerator.class );
+ if ( anns != null ) {
+ for (TableGenerator ann : anns) {
+ IdGenerator idGen = buildIdGenerator( ann, mappings );
+ if ( idGen != null ) mappings.addDefaultGenerator( idGen );
+ }
+ }
+ }
+ {
+ List<NamedQuery> anns = (List<NamedQuery>) defaults.get( NamedQuery.class );
+ if ( anns != null ) {
+ for (NamedQuery ann : anns) {
+ QueryBinder.bindQuery( ann, mappings, true );
+ }
+ }
+ }
+ {
+ List<NamedNativeQuery> anns = (List<NamedNativeQuery>) defaults.get( NamedNativeQuery.class );
+ if ( anns != null ) {
+ for (NamedNativeQuery ann : anns) {
+ QueryBinder.bindNativeQuery( ann, mappings, true );
+ }
+ }
+ }
+ {
+ List<SqlResultSetMapping> anns = (List<SqlResultSetMapping>) defaults.get( SqlResultSetMapping.class );
+ if ( anns != null ) {
+ for (SqlResultSetMapping ann : anns) {
+ QueryBinder.bindSqlResultsetMapping( ann, mappings, true );
+ }
+ }
+ }
+ }
+
+ public static void bindPackage(String packageName, ExtendedMappings mappings) {
+ XPackage pckg = null;
+ try {
+ pckg = mappings.getReflectionManager().packageForName( packageName );
+ }
+ catch (ClassNotFoundException cnf) {
+ log.warn( "Package not found or wo package-info.java: {}", packageName );
+ return;
+ }
+ if ( pckg.isAnnotationPresent( SequenceGenerator.class ) ) {
+ SequenceGenerator ann = pckg.getAnnotation( SequenceGenerator.class );
+ IdGenerator idGen = buildIdGenerator( ann, mappings );
+ mappings.addGenerator( idGen );
+ log.debug( "Add sequence generator with name: {}", idGen.getName() );
+ }
+ if ( pckg.isAnnotationPresent( TableGenerator.class ) ) {
+ TableGenerator ann = pckg.getAnnotation( TableGenerator.class );
+ IdGenerator idGen = buildIdGenerator( ann, mappings );
+ mappings.addGenerator( idGen );
+
+ }
+ bindGenericGenerators(pckg, mappings);
+ bindQueries( pckg, mappings );
+ bindFilterDefs( pckg, mappings );
+ bindTypeDefs( pckg, mappings );
+ BinderHelper.bindAnyMetaDefs( pckg, mappings );
+ }
+
+ private static void bindGenericGenerators(XAnnotatedElement annotatedElement, ExtendedMappings mappings) {
+ GenericGenerator defAnn = annotatedElement.getAnnotation( GenericGenerator.class );
+ GenericGenerators defsAnn = annotatedElement.getAnnotation( GenericGenerators.class );
+ if ( defAnn != null ) {
+ bindGenericGenerator( defAnn, mappings );
+ }
+ if ( defsAnn != null ) {
+ for (GenericGenerator def : defsAnn.value() ) {
+ bindGenericGenerator( def, mappings );
+ }
+ }
+ }
+
+ private static void bindGenericGenerator(GenericGenerator def, ExtendedMappings mappings) {
+ IdGenerator idGen = buildIdGenerator( def, mappings );
+ mappings.addGenerator( idGen );
+ }
+
+ private static void bindQueries(XAnnotatedElement annotatedElement, ExtendedMappings mappings) {
+ {
+ SqlResultSetMapping ann = annotatedElement.getAnnotation( SqlResultSetMapping.class );
+ QueryBinder.bindSqlResultsetMapping( ann, mappings, false );
+ }
+ {
+ SqlResultSetMappings ann = annotatedElement.getAnnotation( SqlResultSetMappings.class );
+ if ( ann != null ) {
+ for (SqlResultSetMapping current : ann.value()) {
+ QueryBinder.bindSqlResultsetMapping( current, mappings, false );
+ }
+ }
+ }
+ {
+ NamedQuery ann = annotatedElement.getAnnotation( NamedQuery.class );
+ QueryBinder.bindQuery( ann, mappings, false );
+ }
+ {
+ org.hibernate.annotations.NamedQuery ann = annotatedElement.getAnnotation(
+ org.hibernate.annotations.NamedQuery.class
+ );
+ QueryBinder.bindQuery( ann, mappings );
+ }
+ {
+ NamedQueries ann = annotatedElement.getAnnotation( NamedQueries.class );
+ QueryBinder.bindQueries( ann, mappings, false );
+ }
+ {
+ org.hibernate.annotations.NamedQueries ann = annotatedElement.getAnnotation(
+ org.hibernate.annotations.NamedQueries.class
+ );
+ QueryBinder.bindQueries( ann, mappings );
+ }
+ {
+ NamedNativeQuery ann = annotatedElement.getAnnotation( NamedNativeQuery.class );
+ QueryBinder.bindNativeQuery( ann, mappings, false );
+ }
+ {
+ org.hibernate.annotations.NamedNativeQuery ann = annotatedElement.getAnnotation(
+ org.hibernate.annotations.NamedNativeQuery.class
+ );
+ QueryBinder.bindNativeQuery( ann, mappings );
+ }
+ {
+ NamedNativeQueries ann = annotatedElement.getAnnotation( NamedNativeQueries.class );
+ QueryBinder.bindNativeQueries( ann, mappings, false );
+ }
+ {
+ org.hibernate.annotations.NamedNativeQueries ann = annotatedElement.getAnnotation(
+ org.hibernate.annotations.NamedNativeQueries.class
+ );
+ QueryBinder.bindNativeQueries( ann, mappings );
+ }
+ }
+
+ private static IdGenerator buildIdGenerator(java.lang.annotation.Annotation ann, Mappings mappings) {
+ IdGenerator idGen = new IdGenerator();
+ if ( mappings.getSchemaName() != null ) {
+ idGen.addParam( PersistentIdentifierGenerator.SCHEMA, mappings.getSchemaName() );
+ }
+ if ( mappings.getCatalogName() != null ) {
+ idGen.addParam( PersistentIdentifierGenerator.CATALOG, mappings.getCatalogName() );
+ }
+ if ( ann == null ) {
+ idGen = null;
+ }
+ else if ( ann instanceof TableGenerator ) {
+ TableGenerator tabGen = (TableGenerator) ann;
+ idGen.setName( tabGen.name() );
+ idGen.setIdentifierGeneratorStrategy( MultipleHiLoPerTableGenerator.class.getName() );
+
+ if ( !BinderHelper.isDefault( tabGen.table() ) ) {
+ idGen.addParam( MultipleHiLoPerTableGenerator.ID_TABLE, tabGen.table() );
+ }
+ if ( !BinderHelper.isDefault( tabGen.catalog() ) ) {
+ idGen.addParam( MultipleHiLoPerTableGenerator.CATALOG, tabGen.catalog() );
+ }
+ if ( !BinderHelper.isDefault( tabGen.schema() ) ) {
+ idGen.addParam( MultipleHiLoPerTableGenerator.SCHEMA, tabGen.schema() );
+ }
+ //FIXME implements uniqueconstrains
+
+ if ( !BinderHelper.isDefault( tabGen.pkColumnName() ) ) {
+ idGen.addParam( MultipleHiLoPerTableGenerator.PK_COLUMN_NAME, tabGen.pkColumnName() );
+ }
+ if ( !BinderHelper.isDefault( tabGen.valueColumnName() ) ) {
+ idGen.addParam( MultipleHiLoPerTableGenerator.VALUE_COLUMN_NAME, tabGen.valueColumnName() );
+ }
+ if ( !BinderHelper.isDefault( tabGen.pkColumnValue() ) ) {
+ idGen.addParam( MultipleHiLoPerTableGenerator.PK_VALUE_NAME, tabGen.pkColumnValue() );
+ }
+ idGen.addParam( TableHiLoGenerator.MAX_LO, String.valueOf( tabGen.allocationSize() - 1 ) );
+ log.debug( "Add table generator with name: {}", idGen.getName() );
+ }
+ else if ( ann instanceof SequenceGenerator ) {
+ SequenceGenerator seqGen = (SequenceGenerator) ann;
+ idGen.setName( seqGen.name() );
+ idGen.setIdentifierGeneratorStrategy( "seqhilo" );
+
+ if ( !BinderHelper.isDefault( seqGen.sequenceName() ) ) {
+ idGen.addParam( org.hibernate.id.SequenceGenerator.SEQUENCE, seqGen.sequenceName() );
+ }
+ //FIXME: work on initialValue() through SequenceGenerator.PARAMETERS
+ if ( seqGen.initialValue() != 1 ) {
+ log.warn(
+ "Hibernate does not support SequenceGenerator.initialValue()"
+ );
+ }
+ idGen.addParam( SequenceHiLoGenerator.MAX_LO, String.valueOf( seqGen.allocationSize() - 1 ) );
+ log.debug( "Add sequence generator with name: {}", idGen.getName() );
+ }
+ else if ( ann instanceof GenericGenerator ) {
+ GenericGenerator genGen = (GenericGenerator) ann;
+ idGen.setName( genGen.name() );
+ idGen.setIdentifierGeneratorStrategy( genGen.strategy() );
+ Parameter[] params = genGen.parameters();
+ for (Parameter parameter : params) {
+ idGen.addParam( parameter.name(), parameter.value() );
+ }
+ log.debug( "Add generic generator with name: {}", idGen.getName() );
+ }
+ else {
+ throw new AssertionFailure( "Unknown Generator annotation: " + ann );
+ }
+ return idGen;
+ }
+
+ /**
+ * Bind a class having JSR175 annotations
+ * The subclasses <b>have to</b> be binded after its mother class
+ */
+ public static void bindClass(
+ XClass clazzToProcess, Map<XClass, InheritanceState> inheritanceStatePerClass, ExtendedMappings mappings
+ ) throws MappingException {
+ //TODO: be more strict with secondarytable allowance (not for ids, not for secondary table join columns etc)
+ InheritanceState inheritanceState = inheritanceStatePerClass.get( clazzToProcess );
+ AnnotatedClassType classType = mappings.getClassType( clazzToProcess );
+ if ( AnnotatedClassType.EMBEDDABLE_SUPERCLASS.equals( classType ) //will be processed by their subentities
+ || AnnotatedClassType.NONE.equals( classType ) //to be ignored
+ || AnnotatedClassType.EMBEDDABLE.equals( classType ) //allow embeddable element declaration
+ ) {
+ if ( AnnotatedClassType.NONE.equals( classType )
+ && clazzToProcess.isAnnotationPresent( org.hibernate.annotations.Entity.class ) ) {
+ log.warn( "Class annotated @org.hibernate.annotations.Entity but not javax.persistence.Entity "
+ + "(most likely a user error): {}", clazzToProcess.getName() );
+ }
+ return;
+ }
+ if ( !classType.equals( AnnotatedClassType.ENTITY ) ) {
+ //TODO make this test accurate by removing the none elements artifically added
+ throw new AnnotationException(
+ "Annotated class should have a @javax.persistence.Entity, @javax.persistence.Embeddable or @javax.persistence.EmbeddedSuperclass annotation: " + clazzToProcess
+ .getName()
+ );
+ }
+ XAnnotatedElement annotatedClass = clazzToProcess;
+ log.info( "Binding entity from annotated class: {}", clazzToProcess.getName() );
+ InheritanceState superEntityState =
+ InheritanceState.getSuperEntityInheritanceState(
+ clazzToProcess, inheritanceStatePerClass, mappings.getReflectionManager()
+ );
+ PersistentClass superEntity = superEntityState != null ?
+ mappings.getClass(
+ superEntityState.clazz.getName()
+ ) :
+ null;
+ if ( superEntity == null ) {
+ //check if superclass is not a potential persistent class
+ if ( inheritanceState.hasParents ) {
+ throw new AssertionFailure(
+ "Subclass has to be binded after it's mother class: "
+ + superEntityState.clazz.getName()
+ );
+ }
+ }
+ bindQueries( annotatedClass, mappings );
+ bindFilterDefs( annotatedClass, mappings );
+ bindTypeDefs( annotatedClass, mappings );
+ BinderHelper.bindAnyMetaDefs( annotatedClass, mappings );
+
+ String schema = "";
+ String table = ""; //might be no @Table annotation on the annotated class
+ String catalog = "";
+ String discrimValue = null;
+ List<String[]> uniqueConstraints = new ArrayList<String[]>();
+ Ejb3DiscriminatorColumn discriminatorColumn = null;
+ Ejb3JoinColumn[] inheritanceJoinedColumns = null;
+
+ if ( annotatedClass.isAnnotationPresent( javax.persistence.Table.class ) ) {
+ javax.persistence.Table tabAnn = annotatedClass.getAnnotation( javax.persistence.Table.class );
+ table = tabAnn.name();
+ schema = tabAnn.schema();
+ catalog = tabAnn.catalog();
+ uniqueConstraints = TableBinder.buildUniqueConstraints( tabAnn.uniqueConstraints() );
+ }
+ final boolean hasJoinedColumns = inheritanceState.hasParents
+ && InheritanceType.JOINED.equals( inheritanceState.type );
+ if ( hasJoinedColumns ) {
+ //@Inheritance(JOINED) subclass need to link back to the super entity
+ PrimaryKeyJoinColumns jcsAnn = annotatedClass.getAnnotation( PrimaryKeyJoinColumns.class );
+ boolean explicitInheritanceJoinedColumns = jcsAnn != null && jcsAnn.value().length != 0;
+ if ( explicitInheritanceJoinedColumns ) {
+ int nbrOfInhJoinedColumns = jcsAnn.value().length;
+ PrimaryKeyJoinColumn jcAnn;
+ inheritanceJoinedColumns = new Ejb3JoinColumn[nbrOfInhJoinedColumns];
+ for (int colIndex = 0; colIndex < nbrOfInhJoinedColumns; colIndex++) {
+ jcAnn = jcsAnn.value()[colIndex];
+ inheritanceJoinedColumns[colIndex] = Ejb3JoinColumn.buildJoinColumn(
+ jcAnn, null, superEntity.getIdentifier(),
+ (Map<String, Join>) null, (PropertyHolder) null, mappings
+ );
+ }
+ }
+ else {
+ PrimaryKeyJoinColumn jcAnn = annotatedClass.getAnnotation( PrimaryKeyJoinColumn.class );
+ inheritanceJoinedColumns = new Ejb3JoinColumn[1];
+ inheritanceJoinedColumns[0] = Ejb3JoinColumn.buildJoinColumn(
+ jcAnn, null, superEntity.getIdentifier(),
+ (Map<String, Join>) null, (PropertyHolder) null, mappings
+ );
+ }
+ log.debug( "Subclass joined column(s) created" );
+ }
+ else {
+ if ( annotatedClass.isAnnotationPresent( javax.persistence.PrimaryKeyJoinColumns.class )
+ || annotatedClass.isAnnotationPresent( javax.persistence.PrimaryKeyJoinColumn.class ) ) {
+ log.warn( "Root entity should not hold an PrimaryKeyJoinColum(s), will be ignored" );
+ }
+ }
+
+ if ( InheritanceType.SINGLE_TABLE.equals( inheritanceState.type ) ) {
+ javax.persistence.DiscriminatorColumn discAnn = annotatedClass.getAnnotation(
+ javax.persistence.DiscriminatorColumn.class
+ );
+ DiscriminatorType discriminatorType = discAnn != null ?
+ discAnn.discriminatorType() :
+ DiscriminatorType.STRING;
+
+ org.hibernate.annotations.DiscriminatorFormula discFormulaAnn = annotatedClass.getAnnotation(
+ org.hibernate.annotations.DiscriminatorFormula.class
+ );
+ if ( !inheritanceState.hasParents ) {
+ discriminatorColumn = Ejb3DiscriminatorColumn.buildDiscriminatorColumn(
+ discriminatorType, discAnn, discFormulaAnn, mappings
+ );
+ }
+ if ( discAnn != null && inheritanceState.hasParents ) {
+ log.warn(
+ "Discriminator column has to be defined in the root entity, it will be ignored in subclass: {}",
+ clazzToProcess.getName()
+ );
+ }
+ discrimValue = annotatedClass.isAnnotationPresent( DiscriminatorValue.class ) ?
+ annotatedClass.getAnnotation( DiscriminatorValue.class ).value() :
+ null;
+ }
+
+ //we now know what kind of persistent entity it is
+ PersistentClass persistentClass;
+ //create persistent class
+ if ( !inheritanceState.hasParents ) {
+ persistentClass = new RootClass();
+ }
+ else if ( InheritanceType.SINGLE_TABLE.equals( inheritanceState.type ) ) {
+ persistentClass = new SingleTableSubclass( superEntity );
+ }
+ else if ( InheritanceType.JOINED.equals( inheritanceState.type ) ) {
+ persistentClass = new JoinedSubclass( superEntity );
+ }
+ else if ( InheritanceType.TABLE_PER_CLASS.equals( inheritanceState.type ) ) {
+ persistentClass = new UnionSubclass( superEntity );
+ }
+ else {
+ throw new AssertionFailure( "Unknown inheritance type: " + inheritanceState.type );
+ }
+ Proxy proxyAnn = annotatedClass.getAnnotation( Proxy.class );
+ BatchSize sizeAnn = annotatedClass.getAnnotation( BatchSize.class );
+ Where whereAnn = annotatedClass.getAnnotation( Where.class );
+ Entity entityAnn = annotatedClass.getAnnotation( Entity.class );
+ org.hibernate.annotations.Entity hibEntityAnn = annotatedClass.getAnnotation(
+ org.hibernate.annotations.Entity.class
+ );
+ org.hibernate.annotations.Cache cacheAnn = annotatedClass.getAnnotation(
+ org.hibernate.annotations.Cache.class
+ );
+ EntityBinder entityBinder = new EntityBinder(
+ entityAnn, hibEntityAnn, clazzToProcess, persistentClass, mappings
+ );
+ entityBinder.setDiscriminatorValue( discrimValue );
+ entityBinder.setBatchSize( sizeAnn );
+ entityBinder.setProxy( proxyAnn );
+ entityBinder.setWhere( whereAnn );
+ entityBinder.setCache( cacheAnn );
+ entityBinder.setInheritanceState( inheritanceState );
+ Filter filterAnn = annotatedClass.getAnnotation( Filter.class );
+ if ( filterAnn != null ) {
+ entityBinder.addFilter( filterAnn.name(), filterAnn.condition() );
+ }
+ Filters filtersAnn = annotatedClass.getAnnotation( Filters.class );
+ if ( filtersAnn != null ) {
+ for (Filter filter : filtersAnn.value()) {
+ entityBinder.addFilter( filter.name(), filter.condition() );
+ }
+ }
+ entityBinder.bindEntity();
+
+ if ( inheritanceState.hasTable() ) {
+ Check checkAnn = annotatedClass.getAnnotation( Check.class );
+ String constraints = checkAnn == null ?
+ null :
+ checkAnn.constraints();
+ entityBinder.bindTable(
+ schema, catalog, table, uniqueConstraints,
+ constraints, inheritanceState.hasDenormalizedTable() ?
+ superEntity.getTable() :
+ null
+ );
+ }
+ else {
+ if ( annotatedClass.isAnnotationPresent( Table.class ) ) {
+ log.warn( "Illegal use of @Table in a subclass of a SINGLE_TABLE hierarchy: " + clazzToProcess
+ .getName() );
+ }
+ }
+// Map<String, Column[]> columnOverride = PropertyHolderBuilder.buildHierarchyColumnOverride(
+// clazzToProcess,
+// persistentClass.getClassName()
+// );
+ PropertyHolder propertyHolder = PropertyHolderBuilder.buildPropertyHolder(
+ clazzToProcess,
+ persistentClass,
+ entityBinder, mappings
+ );
+
+ javax.persistence.SecondaryTable secTabAnn = annotatedClass.getAnnotation(
+ javax.persistence.SecondaryTable.class
+ );
+ javax.persistence.SecondaryTables secTabsAnn = annotatedClass.getAnnotation(
+ javax.persistence.SecondaryTables.class
+ );
+ entityBinder.firstLevelSecondaryTablesBinding( secTabAnn, secTabsAnn );
+
+ OnDelete onDeleteAnn = annotatedClass.getAnnotation( OnDelete.class );
+ boolean onDeleteAppropriate = false;
+ if ( InheritanceType.JOINED.equals( inheritanceState.type ) && inheritanceState.hasParents ) {
+ onDeleteAppropriate = true;
+ final JoinedSubclass jsc = (JoinedSubclass) persistentClass;
+ if ( persistentClass.getEntityPersisterClass() == null ) {
+ persistentClass.getRootClass().setEntityPersisterClass( JoinedSubclassEntityPersister.class );
+ }
+ SimpleValue key = new DependantValue( jsc.getTable(), jsc.getIdentifier() );
+ jsc.setKey( key );
+ ForeignKey fk = annotatedClass.getAnnotation( ForeignKey.class );
+ if ( fk != null && !BinderHelper.isDefault( fk.name() ) ) {
+ key.setForeignKeyName( fk.name() );
+ }
+ if ( onDeleteAnn != null ) {
+ key.setCascadeDeleteEnabled( OnDeleteAction.CASCADE.equals( onDeleteAnn.action() ) );
+ }
+ else {
+ key.setCascadeDeleteEnabled( false );
+ }
+ //we are never in a second pass at that stage, so queue it
+ SecondPass sp = new JoinedSubclassFkSecondPass( jsc, inheritanceJoinedColumns, key, mappings );
+ mappings.addSecondPass( sp );
+ mappings.addSecondPass( new CreateKeySecondPass( jsc ) );
+
+ }
+ else if ( InheritanceType.SINGLE_TABLE.equals( inheritanceState.type ) ) {
+ if ( inheritanceState.hasParents ) {
+ if ( persistentClass.getEntityPersisterClass() == null ) {
+ persistentClass.getRootClass().setEntityPersisterClass( SingleTableEntityPersister.class );
+ }
+ }
+ else {
+ if ( inheritanceState.hasSons || !discriminatorColumn.isImplicit() ) {
+ //need a discriminator column
+ bindDiscriminatorToPersistentClass(
+ (RootClass) persistentClass,
+ discriminatorColumn,
+ entityBinder.getSecondaryTables(),
+ propertyHolder
+ );
+ entityBinder.bindDiscriminatorValue();//bind it again since the type might have changed
+ }
+ }
+ }
+ else if ( InheritanceType.TABLE_PER_CLASS.equals( inheritanceState.type ) ) {
+ if ( inheritanceState.hasParents ) {
+ if ( persistentClass.getEntityPersisterClass() == null ) {
+ persistentClass.getRootClass().setEntityPersisterClass( UnionSubclassEntityPersister.class );
+ }
+ }
+ }
+ if ( onDeleteAnn != null && !onDeleteAppropriate ) {
+ log.warn(
+ "Inapropriate use of @OnDelete on entity, annotation ignored: {}", propertyHolder.getEntityName()
+ );
+ }
+
+ //try to find class level generators
+ HashMap<String, IdGenerator> classGenerators = buildLocalGenerators( annotatedClass, mappings );
+
+ // check properties
+ List<PropertyData> elements =
+ getElementsToProcess(
+ clazzToProcess, inheritanceStatePerClass, propertyHolder, entityBinder, mappings
+ );
+ if ( elements == null ) {
+ throw new AnnotationException( "No identifier specified for entity: " + propertyHolder.getEntityName() );
+ }
+ final boolean subclassAndSingleTableStrategy = inheritanceState.type == InheritanceType.SINGLE_TABLE
+ && inheritanceState.hasParents;
+ //process idclass if any
+ Set<String> idProperties = new HashSet<String>();
+ IdClass idClass = null;
+ if ( !inheritanceState.hasParents ) {
+ //look for idClass
+ XClass current = inheritanceState.clazz;
+ InheritanceState state = inheritanceState;
+ do {
+ current = state.clazz;
+ if ( current.isAnnotationPresent( IdClass.class ) ) {
+ idClass = current.getAnnotation( IdClass.class );
+ break;
+ }
+ state = InheritanceState.getSuperclassInheritanceState(
+ current, inheritanceStatePerClass, mappings.getReflectionManager()
+ );
+ }
+ while ( state != null );
+ }
+ if ( idClass != null ) {
+ XClass compositeClass = mappings.getReflectionManager().toXClass( idClass.value() );
+ boolean isComponent = true;
+ boolean propertyAnnotated = entityBinder.isPropertyAnnotated( compositeClass );
+ String propertyAccessor = entityBinder.getPropertyAccessor( compositeClass );
+ String generatorType = "assigned";
+ String generator = BinderHelper.ANNOTATION_STRING_DEFAULT;
+ PropertyData inferredData = new PropertyPreloadedData(
+ entityBinder.getPropertyAccessor(), "id", compositeClass
+ );
+ HashMap<String, IdGenerator> localGenerators = new HashMap<String, IdGenerator>();
+ boolean ignoreIdAnnotations = entityBinder.isIgnoreIdAnnotations();
+ entityBinder.setIgnoreIdAnnotations( true );
+ bindId(
+ generatorType,
+ generator,
+ inferredData,
+ null,
+ propertyHolder,
+ localGenerators,
+ isComponent,
+ propertyAnnotated,
+ propertyAccessor, entityBinder,
+ true,
+ false, mappings
+ );
+ inferredData = new PropertyPreloadedData(
+ propertyAccessor, "_identifierMapper", compositeClass
+ );
+ Component mapper = fillComponent(
+ propertyHolder,
+ inferredData,
+ propertyAnnotated,
+ propertyAccessor, false,
+ entityBinder,
+ true, true,
+ false, mappings
+ );
+ entityBinder.setIgnoreIdAnnotations( ignoreIdAnnotations );
+ persistentClass.setIdentifierMapper( mapper );
+ Property property = new Property();
+ property.setName( "_identifierMapper" );
+ property.setNodeName( "id" );
+ property.setUpdateable( false );
+ property.setInsertable( false );
+ property.setValue( mapper );
+ property.setPropertyAccessorName( "embedded" );
+ persistentClass.addProperty( property );
+ entityBinder.setIgnoreIdAnnotations( true );
+
+ Iterator properties = mapper.getPropertyIterator();
+ while ( properties.hasNext() ) {
+ idProperties.add( ( (Property) properties.next() ).getName() );
+ }
+ }
+ Set<String> missingIdProperties = new HashSet<String>( idProperties );
+ for (PropertyData propertyAnnotatedElement : elements) {
+ String propertyName = propertyAnnotatedElement.getPropertyName();
+ if ( !idProperties.contains( propertyName ) ) {
+ processElementAnnotations(
+ propertyHolder,
+ subclassAndSingleTableStrategy ?
+ Nullability.FORCED_NULL :
+ Nullability.NO_CONSTRAINT,
+ propertyAnnotatedElement.getProperty(),
+ propertyAnnotatedElement, classGenerators, entityBinder,
+ false, false, false, mappings
+ );
+ }
+ else {
+ missingIdProperties.remove( propertyName );
+ }
+ }
+
+ if ( missingIdProperties.size() != 0 ) {
+ StringBuilder missings = new StringBuilder();
+ for (String property : missingIdProperties) {
+ missings.append( property ).append( ", " );
+ }
+ throw new AnnotationException(
+ "Unable to find properties ("
+ + missings.substring( 0, missings.length() - 2 )
+ + ") in entity annotated with @IdClass:" + persistentClass.getEntityName()
+ );
+ }
+
+ if ( !inheritanceState.hasParents ) {
+ final RootClass rootClass = (RootClass) persistentClass;
+ mappings.addSecondPass( new CreateKeySecondPass( rootClass ) );
+ }
+ else {
+ superEntity.addSubclass( (Subclass) persistentClass );
+ }
+
+ mappings.addClass( persistentClass );
+
+ //Process secondary tables and complementary definitions (ie o.h.a.Table)
+ mappings.addSecondPass( new SecondaryTableSecondPass( entityBinder, propertyHolder, annotatedClass ) );
+
+ //add process complementary Table definition (index & all)
+ entityBinder.processComplementaryTableDefinitions( annotatedClass.getAnnotation( org.hibernate.annotations.Table.class ) );
+ entityBinder.processComplementaryTableDefinitions( annotatedClass.getAnnotation( org.hibernate.annotations.Tables.class ) );
+
+ }
+
+ /**
+ * Get the annotated elements
+ * Guess the annotated element from @Id or @EmbeddedId presence
+ * Change EntityBinder by side effect
+ */
+ private static List<PropertyData> getElementsToProcess(
+ XClass clazzToProcess, Map<XClass, InheritanceState> inheritanceStatePerClass,
+ PropertyHolder propertyHolder, EntityBinder entityBinder, ExtendedMappings mappings
+ ) {
+ InheritanceState inheritanceState = inheritanceStatePerClass.get( clazzToProcess );
+ List<XClass> classesToProcess = orderClassesToBeProcessed(
+ clazzToProcess, inheritanceStatePerClass, inheritanceState, mappings
+ );
+ List<PropertyData> elements = new ArrayList<PropertyData>();
+ int deep = classesToProcess.size();
+ boolean hasIdentifier = false;
+
+ assert !inheritanceState.isEmbeddableSuperclass;
+ Boolean isExplicitPropertyAnnotated = null;
+ String explicitAccessType = null;
+ if ( inheritanceState.hasParents ) {
+ InheritanceState superEntityState =
+ InheritanceState.getSuperEntityInheritanceState(
+ clazzToProcess, inheritanceStatePerClass, mappings.getReflectionManager()
+ );
+ isExplicitPropertyAnnotated = superEntityState != null ?
+ superEntityState.isPropertyAnnotated :
+ null;
+ explicitAccessType = superEntityState != null ?
+ superEntityState.accessType :
+ null;
+ }
+ else {
+ AccessType access = clazzToProcess.getAnnotation( AccessType.class );
+ explicitAccessType = access != null ?
+ access.value() :
+ null;
+ if ( "property".equals( explicitAccessType ) ) {
+ isExplicitPropertyAnnotated = Boolean.TRUE;
+ }
+ else if ( "field".equals( explicitAccessType ) ) {
+ isExplicitPropertyAnnotated = Boolean.FALSE;
+ }
+ }
+ Boolean isPropertyAnnotated = isExplicitPropertyAnnotated == null ?
+ Boolean.TRUE :
+ //default to property and fallback if needed
+ isExplicitPropertyAnnotated;
+ String accessType = explicitAccessType != null ?
+ explicitAccessType :
+ "property";
+ /*
+ * delay the exception in case field access is used
+ */
+ AnnotationException exceptionWhileWalkingElements = null;
+ try {
+ for (int index = 0; index < deep; index++) {
+ XClass clazz = classesToProcess.get( index );
+
+ boolean currentHasIdentifier = addElementsOfAClass(
+ elements, propertyHolder, isPropertyAnnotated,
+ accessType, clazz, mappings
+ );
+ hasIdentifier = hasIdentifier || currentHasIdentifier;
+ }
+ }
+ catch ( AnnotationException e ) {
+ exceptionWhileWalkingElements = e;
+ }
+
+ //TODO remember why it should be !inheritanceState.hasParents
+ if ( !hasIdentifier && !inheritanceState.hasParents ) {
+ if ( isExplicitPropertyAnnotated != null ) {
+ //the original exception is legitimate
+ if ( exceptionWhileWalkingElements != null) throw exceptionWhileWalkingElements;
+ return null; //explicit but no @Id: the upper layer will raise an exception
+ }
+ isPropertyAnnotated = !isPropertyAnnotated;
+ accessType = "field";
+ elements.clear();
+ for (int index = 0; index < deep; index++) {
+ XClass clazz = classesToProcess.get( index );
+ boolean currentHasIdentifier = addElementsOfAClass(
+ elements, propertyHolder, isPropertyAnnotated,
+ accessType, clazz, mappings
+ );
+ hasIdentifier = hasIdentifier || currentHasIdentifier;
+ }
+ }
+
+ //the field show no id, fallback tot he original exception
+ if (!hasIdentifier && exceptionWhileWalkingElements != null) throw exceptionWhileWalkingElements;
+
+ //TODO set the access type here?
+ entityBinder.setPropertyAnnotated( isPropertyAnnotated );
+ entityBinder.setPropertyAccessor( accessType );
+ inheritanceState.isPropertyAnnotated = isPropertyAnnotated;
+ inheritanceState.accessType = accessType;
+ return hasIdentifier || inheritanceState.hasParents ?
+ elements :
+ null;
+ }
+
+ private static List<XClass> orderClassesToBeProcessed(
+ XClass annotatedClass, Map<XClass, InheritanceState> inheritanceStatePerClass,
+ InheritanceState inheritanceState, ExtendedMappings mappings
+ ) {
+ //ordered to allow proper messages on properties subclassing
+ List<XClass> classesToProcess = new ArrayList<XClass>();
+ XClass currentClassInHierarchy = annotatedClass;
+ InheritanceState superclassState;
+ do {
+ classesToProcess.add( 0, currentClassInHierarchy );
+ XClass superClass = currentClassInHierarchy;
+ do {
+ superClass = superClass.getSuperclass();
+ superclassState = inheritanceStatePerClass.get( superClass );
+ }
+ while ( superClass != null && !mappings.getReflectionManager()
+ .equals( superClass, Object.class ) && superclassState == null );
+
+ currentClassInHierarchy = superClass;
+ }
+ while ( superclassState != null && superclassState.isEmbeddableSuperclass );
+
+ return classesToProcess;
+ }
+
+ private static void bindFilterDefs(XAnnotatedElement annotatedElement, ExtendedMappings mappings) {
+ FilterDef defAnn = annotatedElement.getAnnotation( FilterDef.class );
+ FilterDefs defsAnn = annotatedElement.getAnnotation( FilterDefs.class );
+ if ( defAnn != null ) {
+ bindFilterDef( defAnn, mappings );
+ }
+ if ( defsAnn != null ) {
+ for (FilterDef def : defsAnn.value()) {
+ bindFilterDef( def, mappings );
+ }
+ }
+ }
+
+ private static void bindFilterDef(FilterDef defAnn, ExtendedMappings mappings) {
+ Map<String, org.hibernate.type.Type> params = new HashMap<String, org.hibernate.type.Type>();
+ for (ParamDef param : defAnn.parameters()) {
+ params.put( param.name(), TypeFactory.heuristicType( param.type() ) );
+ }
+ FilterDefinition def = new FilterDefinition( defAnn.name(), defAnn.defaultCondition(), params );
+ log.info( "Binding filter definition: {}", def.getFilterName() );
+ mappings.addFilterDefinition( def );
+ }
+
+ private static void bindTypeDefs(XAnnotatedElement annotatedElement, ExtendedMappings mappings) {
+ TypeDef defAnn = annotatedElement.getAnnotation( TypeDef.class );
+ TypeDefs defsAnn = annotatedElement.getAnnotation( TypeDefs.class );
+ if ( defAnn != null ) {
+ bindTypeDef( defAnn, mappings );
+ }
+ if ( defsAnn != null ) {
+ for (TypeDef def : defsAnn.value()) {
+ bindTypeDef( def, mappings );
+ }
+ }
+ }
+
+ private static void bindTypeDef(TypeDef defAnn, ExtendedMappings mappings) {
+ Properties params = new Properties();
+ for (Parameter param : defAnn.parameters()) {
+ params.setProperty( param.name(), param.value() );
+ }
+ log.info( "Binding type definition: {}", defAnn.name() );
+ mappings.addTypeDef( defAnn.name(), defAnn.typeClass().getName(), params );
+ }
+
+ private static void bindDiscriminatorToPersistentClass(
+ RootClass rootClass,
+ Ejb3DiscriminatorColumn discriminatorColumn, Map<String, Join> secondaryTables,
+ PropertyHolder propertyHolder
+ ) {
+ if ( rootClass.getDiscriminator() == null ) {
+ if ( discriminatorColumn == null ) {
+ throw new AssertionFailure( "discriminator column should have been built" );
+ }
+ discriminatorColumn.setJoins( secondaryTables );
+ discriminatorColumn.setPropertyHolder( propertyHolder );
+ SimpleValue discrim = new SimpleValue( rootClass.getTable() );
+ rootClass.setDiscriminator( discrim );
+ discriminatorColumn.linkWithValue( discrim );
+ discrim.setTypeName( discriminatorColumn.getDiscriminatorTypeName() );
+ rootClass.setPolymorphic( true );
+ log.debug( "Setting discriminator for entity {}", rootClass.getEntityName() );
+ }
+ }
+
+ /**
+ * Add elements of a class
+ */
+ private static boolean addElementsOfAClass(
+ List<PropertyData> elements, PropertyHolder propertyHolder, boolean isPropertyAnnotated,
+ String propertyAccessor, final XClass annotatedClass, ExtendedMappings mappings
+ ) {
+ boolean hasIdentifier = false;
+ AccessType access = annotatedClass.getAnnotation( AccessType.class );
+ String localPropertyAccessor = access != null ?
+ access.value() :
+ null;
+ String accessType = null;
+ if ( "property".equals( localPropertyAccessor ) || "field".equals( localPropertyAccessor ) ) {
+ accessType = localPropertyAccessor;
+ }
+ else {
+ if ( localPropertyAccessor == null ) {
+ localPropertyAccessor = propertyAccessor;
+ }
+
+ if ( isPropertyAnnotated ) {
+ accessType = "property";
+ }
+ else {
+ accessType = "field";
+ }
+ }
+
+ log.debug( "Processing {} {} annotation", propertyHolder.getEntityName(), accessType );
+ List<XProperty> properties = annotatedClass.getDeclaredProperties( accessType );
+ //order so that property are used in the same order when binding native query
+ Collections.sort( properties, new Comparator<XProperty>() {
+ public int compare(XProperty property1, XProperty property2) {
+ return property1.getName().compareTo( property2.getName() );
+ }
+ } );
+ for (XProperty p : properties) {
+ if ( !p.isTypeResolved() && !discoverTypeWithoutReflection( p ) && !mustBeSkipped( p, mappings ) ) {
+ throw new AnnotationException(
+ "Property " + StringHelper.qualify( propertyHolder.getEntityName(), p.getName() ) +
+ " has an unbound type and no explicit target entity. Resolve this Generic usage issue" +
+ " or set an explicit target attribute (eg @OneToMany(target=) or use an explicit @Type"
+ );
+ }
+ final boolean currentHasIdentifier = addProperty( p, elements, localPropertyAccessor, mappings );
+ hasIdentifier = hasIdentifier || currentHasIdentifier;
+ }
+ return hasIdentifier;
+ }
+
+ private static boolean discoverTypeWithoutReflection(XProperty p) {
+ if ( p.isAnnotationPresent( OneToOne.class ) && !p.getAnnotation( OneToOne.class )
+ .targetEntity()
+ .equals( void.class ) ) {
+ return true;
+ }
+ else if ( p.isAnnotationPresent( OneToMany.class ) && !p.getAnnotation( OneToMany.class )
+ .targetEntity()
+ .equals( void.class ) ) {
+ return true;
+ }
+ else if ( p.isAnnotationPresent( ManyToOne.class ) && !p.getAnnotation( ManyToOne.class )
+ .targetEntity()
+ .equals( void.class ) ) {
+ return true;
+ }
+ else if ( p.isAnnotationPresent( ManyToMany.class ) && !p.getAnnotation( ManyToMany.class )
+ .targetEntity()
+ .equals( void.class ) ) {
+ return true;
+ }
+ else if ( p.isAnnotationPresent( org.hibernate.annotations.Any.class ) ) {
+ return true;
+ }
+ else if ( p.isAnnotationPresent( ManyToAny.class ) ) {
+ if ( !p.isCollection() && !p.isArray() ) {
+ throw new AnnotationException( "@ManyToAny used on a non collection non array property: " + p.getName() );
+ }
+ return true;
+ }
+ else if ( p.isAnnotationPresent( Type.class ) ) {
+ return true;
+ }
+ else if ( p.isAnnotationPresent( Target.class ) ) {
+ return true;
+ }
+ return false;
+ }
+
+ private static boolean addProperty(
+ XProperty property, List<PropertyData> annElts,
+ String propertyAccessor, ExtendedMappings mappings
+ ) {
+ boolean hasIdentifier = false;
+ PropertyData propertyAnnotatedElement = new PropertyInferredData(
+ property, propertyAccessor,
+ mappings.getReflectionManager() );
+ if ( !mustBeSkipped( propertyAnnotatedElement.getProperty(), mappings ) ) {
+ /*
+ * put element annotated by @Id in front
+ * since it has to be parsed before any assoctation by Hibernate
+ */
+ final XAnnotatedElement element = propertyAnnotatedElement.getProperty();
+ if ( element.isAnnotationPresent( Id.class ) || element.isAnnotationPresent( EmbeddedId.class ) ) {
+ annElts.add( 0, propertyAnnotatedElement );
+ hasIdentifier = true;
+ }
+ else {
+ annElts.add( propertyAnnotatedElement );
+ hasIdentifier = false;
+ }
+ }
+ return hasIdentifier;
+ }
+
+ private static boolean mustBeSkipped(XProperty property, ExtendedMappings mappings) {
+ //TODO make those hardcoded tests more portable (through the bytecode provider?)
+ return property.isAnnotationPresent( Transient.class )
+ || "net.sf.cglib.transform.impl.InterceptFieldCallback".equals( property.getType().getName() )
+ || "org.hibernate.bytecode.javassist.FieldHandler".equals( property.getType().getName() );
+ }
+
+ /**
+ * Process annotation of a particular property
+ */
+ private static void processElementAnnotations(
+ PropertyHolder propertyHolder, Nullability nullability, XProperty property,
+ PropertyData inferredData, HashMap<String, IdGenerator> classGenerators,
+ EntityBinder entityBinder, boolean isIdentifierMapper,
+ boolean isComponentEmbedded, boolean inSecondPass, ExtendedMappings mappings
+ )
+ throws MappingException {
+ /**
+ * inSecondPass can only be used to apply right away the second pass of a composite-element
+ * Because it's a value type, there is no bidirectional association, hence second pass
+ * ordering does not matter
+ */
+ Ejb3Column[] columns = null;
+ Ejb3JoinColumn[] joinColumns = null;
+ log.debug(
+ "Processing annotations of {}.{}", propertyHolder.getEntityName(), inferredData.getPropertyName()
+ );
+
+ if ( property.isAnnotationPresent( Parent.class ) ) {
+ if ( propertyHolder.isComponent() ) {
+ propertyHolder.setParentProperty( property.getName() );
+ }
+ else {
+ throw new AnnotationException(
+ "@Parent cannot be applied outside an embeddable object: "
+ + StringHelper.qualify( propertyHolder.getPath(), property.getName() )
+ );
+ }
+ return;
+ }
+
+ //process @JoinColumn(s) before @Column(s) to handle collection of elements properly
+ {
+ JoinColumn[] anns = null;
+ if ( property.isAnnotationPresent( JoinColumn.class ) ) {
+ anns = new JoinColumn[] { property.getAnnotation( JoinColumn.class ) };
+ }
+ else if ( property.isAnnotationPresent( JoinColumns.class ) ) {
+ JoinColumns ann = property.getAnnotation( JoinColumns.class );
+ anns = ann.value();
+ int length = anns.length;
+ if ( length == 0 ) {
+ throw new AnnotationException( "Cannot bind an empty @JoinColumns" );
+ }
+ }
+ if ( anns != null ) {
+ joinColumns = Ejb3JoinColumn.buildJoinColumns(
+ anns, null, entityBinder.getSecondaryTables(),
+ propertyHolder, inferredData.getPropertyName(), mappings
+ );
+ }
+ }
+ if ( property.isAnnotationPresent( Column.class ) || property.isAnnotationPresent( Formula.class ) ) {
+ Column ann = property.getAnnotation( Column.class );
+ Formula formulaAnn = property.getAnnotation( Formula.class );
+ columns = Ejb3Column.buildColumnFromAnnotation(
+ new Column[] { ann }, formulaAnn, nullability, propertyHolder, inferredData,
+ entityBinder.getSecondaryTables(), mappings
+ );
+ }
+ else if ( property.isAnnotationPresent( Columns.class ) ) {
+ Columns anns = property.getAnnotation( Columns.class );
+ columns = Ejb3Column.buildColumnFromAnnotation(
+ anns.columns(), null, nullability, propertyHolder, inferredData, entityBinder.getSecondaryTables(),
+ mappings
+ );
+ }
+
+ //set default values if needed
+ if ( joinColumns == null &&
+ ( property.isAnnotationPresent( ManyToOne.class )
+ || property.isAnnotationPresent( OneToOne.class ) )
+ ) {
+ if ( property.isAnnotationPresent( JoinTable.class ) ) {
+ JoinTable joinTableAnn = property.getAnnotation( JoinTable.class );
+ joinColumns = Ejb3JoinColumn.buildJoinColumns(
+ joinTableAnn.inverseJoinColumns(), null, entityBinder.getSecondaryTables(),
+ propertyHolder, inferredData.getPropertyName(), mappings
+ );
+ if ( StringHelper.isEmpty( joinTableAnn.name() ) ) {
+ throw new AnnotationException(
+ "JoinTable.name() on a @ToOne association has to be explicit: "
+ + StringHelper.qualify( propertyHolder.getPath(), inferredData.getPropertyName() )
+ );
+ }
+ }
+ else {
+ OneToOne oneToOneAnn = property.getAnnotation( OneToOne.class );
+ String mappedBy = oneToOneAnn != null ?
+ oneToOneAnn.mappedBy() :
+ null;
+ joinColumns = Ejb3JoinColumn.buildJoinColumns(
+ (JoinColumn[]) null,
+ mappedBy, entityBinder.getSecondaryTables(),
+ propertyHolder, inferredData.getPropertyName(), mappings
+ );
+ }
+ }
+ else if ( joinColumns == null &&
+ ( property.isAnnotationPresent( OneToMany.class )
+ || property.isAnnotationPresent( CollectionOfElements.class ) ) ) {
+ OneToMany oneToMany = property.getAnnotation( OneToMany.class );
+ String mappedBy = oneToMany != null ?
+ oneToMany.mappedBy() :
+ "";
+ joinColumns = Ejb3JoinColumn.buildJoinColumns(
+ (JoinColumn[]) null,
+ mappedBy, entityBinder.getSecondaryTables(),
+ propertyHolder, inferredData.getPropertyName(), mappings
+ );
+ }
+ else if ( joinColumns == null && property.isAnnotationPresent( org.hibernate.annotations.Any.class ) ) {
+ throw new AnnotationException( "@Any requires an explicit @JoinColumn(s): "
+ + StringHelper.qualify( propertyHolder.getPath(), property.getName() ) );
+ }
+ if ( columns == null && !property.isAnnotationPresent( ManyToMany.class ) ) {
+ //useful for collection of embedded elements
+ columns = Ejb3Column.buildColumnFromAnnotation(
+ null, null, nullability, propertyHolder, inferredData, entityBinder.getSecondaryTables(), mappings
+ );
+ }
+
+ if ( nullability == Nullability.FORCED_NOT_NULL ) {
+ //force columns to not null
+ for (Ejb3Column col : columns) {
+ col.forceNotNull();
+ }
+ }
+
+ final XClass returnedClass = inferredData.getClassOrElement();
+ if ( !entityBinder.isIgnoreIdAnnotations() &&
+ ( property.isAnnotationPresent( Id.class )
+ || property.isAnnotationPresent( EmbeddedId.class ) ) ) {
+ if ( isIdentifierMapper ) {
+ throw new AnnotationException(
+ "@IdClass class should not have @Id nor @EmbeddedId properties"
+ );
+ }
+ log.debug( "{} is an id", inferredData.getPropertyName() );
+ //clone classGenerator and override with local values
+ HashMap<String, IdGenerator> localGenerators = (HashMap<String, IdGenerator>) classGenerators.clone();
+ localGenerators.putAll( buildLocalGenerators( property, mappings ) );
+
+ //manage composite related metadata
+ //guess if its a component and find id data access (property, field etc)
+ final boolean isComponent = returnedClass.isAnnotationPresent( Embeddable.class )
+ || property.isAnnotationPresent( EmbeddedId.class );
+ boolean propertyAnnotated = entityBinder.isPropertyAnnotated( returnedClass );
+ String propertyAccessor = entityBinder.getPropertyAccessor( returnedClass );
+ //if ( isComponent && embeddableAnn != null && embeddableAnn.access() == AccessType.FIELD ) propertyAccess = false;
+
+ GeneratedValue generatedValue = property.getAnnotation( GeneratedValue.class );
+ String generatorType = generatedValue != null ?
+ generatorType( generatedValue.strategy() ) :
+ "assigned";
+ String generator = generatedValue != null ?
+ generatedValue.generator() :
+ BinderHelper.ANNOTATION_STRING_DEFAULT;
+ if ( isComponent ) generatorType = "assigned"; //a component must not have any generator
+
+ bindId(
+ generatorType,
+ generator,
+ inferredData,
+ columns,
+ propertyHolder,
+ localGenerators,
+ isComponent,
+ propertyAnnotated,
+ propertyAccessor, entityBinder,
+ false,
+ isIdentifierMapper, mappings
+ );
+
+ log.debug(
+ "Bind {} on {}", ( isComponent ? "@EmbeddedId" : "@Id" ), inferredData.getPropertyName()
+ );
+ }
+ else if ( property.isAnnotationPresent( Version.class ) ) {
+ if ( isIdentifierMapper ) {
+ throw new AnnotationException(
+ "@IdClass class should not have @Version property"
+ );
+ }
+ if ( !( propertyHolder.getPersistentClass() instanceof RootClass ) ) {
+ throw new AnnotationException(
+ "Unable to define/override @Version on a subclass: "
+ + propertyHolder.getEntityName()
+ );
+ }
+ if ( ! propertyHolder.isEntity() ) {
+ throw new AnnotationException(
+ "Unable to define @Version on an embedded class: "
+ + propertyHolder.getEntityName()
+ );
+ }
+ log.debug( "{} is a version property", inferredData.getPropertyName() );
+ RootClass rootClass = (RootClass) propertyHolder.getPersistentClass();
+ PropertyBinder propBinder = new PropertyBinder();
+ propBinder.setName( inferredData.getPropertyName() );
+ propBinder.setReturnedClassName( inferredData.getTypeName() );
+ propBinder.setLazy( false );
+ propBinder.setPropertyAccessorName( inferredData.getDefaultAccess() );
+ propBinder.setColumns( columns );
+ propBinder.setHolder( propertyHolder ); //PropertyHolderBuilder.buildPropertyHolder(rootClass)
+ propBinder.setProperty( property );
+ propBinder.setReturnedClass( inferredData.getPropertyClass() );
+
+ propBinder.setMappings( mappings );
+ Property prop = propBinder.bind();
+ rootClass.setVersion( prop );
+ SimpleValue simpleValue = (SimpleValue) prop.getValue();
+ if ( !simpleValue.isTypeSpecified() ) simpleValue.setTypeName( "integer" );
+ simpleValue.setNullValue( "undefined" );
+ rootClass.setOptimisticLockMode( Versioning.OPTIMISTIC_LOCK_VERSION );
+ log.debug(
+ "Version name: {}, unsavedValue: {}", rootClass.getVersion().getName(),
+ ( (SimpleValue) rootClass.getVersion().getValue() ).getNullValue()
+ );
+ }
+ else if ( property.isAnnotationPresent( ManyToOne.class ) ) {
+ ManyToOne ann = property.getAnnotation( ManyToOne.class );
+
+ //check validity
+ if ( property.isAnnotationPresent( Column.class )
+ || property.isAnnotationPresent( Columns.class ) ) {
+ throw new AnnotationException( "@Column(s) not allowed on a @ManyToOne property: "
+ + StringHelper.qualify( propertyHolder.getPath(), inferredData.getPropertyName() ) );
+ }
+
+ Cascade hibernateCascade = property.getAnnotation( Cascade.class );
+ NotFound notFound = property.getAnnotation( NotFound.class );
+ boolean ignoreNotFound = notFound != null && notFound.action().equals( NotFoundAction.IGNORE );
+ OnDelete onDeleteAnn = property.getAnnotation( OnDelete.class );
+ boolean onDeleteCascade = onDeleteAnn != null && OnDeleteAction.CASCADE.equals( onDeleteAnn.action() );
+ JoinTable assocTable = property.getAnnotation( JoinTable.class );
+ if ( assocTable != null ) {
+ Join join = propertyHolder.addJoin( assocTable, false );
+ for (Ejb3JoinColumn joinColumn : joinColumns) {
+ joinColumn.setSecondaryTableName( join.getTable().getName() );
+ }
+ }
+ bindManyToOne(
+ getCascadeStrategy( ann.cascade(), hibernateCascade ),
+ joinColumns,
+ ann.optional(),
+ ignoreNotFound, onDeleteCascade,
+ mappings.getReflectionManager().toXClass( ann.targetEntity() ),
+ propertyHolder,
+ inferredData, false, isIdentifierMapper, inSecondPass, mappings
+ );
+ }
+ else if ( property.isAnnotationPresent( OneToOne.class ) ) {
+ OneToOne ann = property.getAnnotation( OneToOne.class );
+
+ //check validity
+ if ( property.isAnnotationPresent( Column.class )
+ || property.isAnnotationPresent( Columns.class ) ) {
+ throw new AnnotationException( "@Column(s) not allowed on a @OneToOne property: "
+ + StringHelper.qualify( propertyHolder.getPath(), inferredData.getPropertyName() ) );
+ }
+
+ //FIXME support a proper PKJCs
+ boolean trueOneToOne = property.isAnnotationPresent( PrimaryKeyJoinColumn.class )
+ || property.isAnnotationPresent( PrimaryKeyJoinColumns.class );
+ Cascade hibernateCascade = property.getAnnotation( Cascade.class );
+ NotFound notFound = property.getAnnotation( NotFound.class );
+ boolean ignoreNotFound = notFound != null && notFound.action().equals( NotFoundAction.IGNORE );
+ OnDelete onDeleteAnn = property.getAnnotation( OnDelete.class );
+ boolean onDeleteCascade = onDeleteAnn != null && OnDeleteAction.CASCADE.equals( onDeleteAnn.action() );
+ JoinTable assocTable = property.getAnnotation( JoinTable.class );
+ if ( assocTable != null ) {
+ Join join = propertyHolder.addJoin( assocTable, false );
+ for (Ejb3JoinColumn joinColumn : joinColumns) {
+ joinColumn.setSecondaryTableName( join.getTable().getName() );
+ }
+ }
+ bindOneToOne(
+ getCascadeStrategy( ann.cascade(), hibernateCascade ),
+ joinColumns,
+ ann.optional(),
+ getFetchMode( ann.fetch() ),
+ ignoreNotFound, onDeleteCascade,
+ mappings.getReflectionManager().toXClass( ann.targetEntity() ),
+ propertyHolder,
+ inferredData, ann.mappedBy(), trueOneToOne, isIdentifierMapper, inSecondPass, mappings
+ );
+ }
+ else if ( property.isAnnotationPresent( org.hibernate.annotations.Any.class ) ) {
+
+ //check validity
+ if ( property.isAnnotationPresent( Column.class )
+ || property.isAnnotationPresent( Columns.class ) ) {
+ throw new AnnotationException( "@Column(s) not allowed on a @Any property: "
+ + StringHelper.qualify( propertyHolder.getPath(), inferredData.getPropertyName() ) );
+ }
+
+ Cascade hibernateCascade = property.getAnnotation( Cascade.class );
+ NotFound notFound = property.getAnnotation( NotFound.class );
+ boolean ignoreNotFound = notFound != null && notFound.action().equals( NotFoundAction.IGNORE );
+ OnDelete onDeleteAnn = property.getAnnotation( OnDelete.class );
+ boolean onDeleteCascade = onDeleteAnn != null && OnDeleteAction.CASCADE.equals( onDeleteAnn.action() );
+ JoinTable assocTable = property.getAnnotation( JoinTable.class );
+ if ( assocTable != null ) {
+ Join join = propertyHolder.addJoin( assocTable, false );
+ for (Ejb3JoinColumn joinColumn : joinColumns) {
+ joinColumn.setSecondaryTableName( join.getTable().getName() );
+ }
+ }
+ bindAny( getCascadeStrategy( null, hibernateCascade ), //@Any has not cascade attribute
+ joinColumns, onDeleteCascade, nullability,
+ propertyHolder, inferredData, entityBinder,
+ isIdentifierMapper, mappings );
+ }
+ else if ( property.isAnnotationPresent( OneToMany.class )
+ || property.isAnnotationPresent( ManyToMany.class )
+ || property.isAnnotationPresent( CollectionOfElements.class )
+ || property.isAnnotationPresent( ManyToAny.class ) ) {
+ OneToMany oneToManyAnn = property.getAnnotation( OneToMany.class );
+ ManyToMany manyToManyAnn = property.getAnnotation( ManyToMany.class );
+ CollectionOfElements collectionOfElementsAnn = property.getAnnotation( CollectionOfElements.class );
+ org.hibernate.annotations.IndexColumn indexAnn = property.getAnnotation(
+ org.hibernate.annotations.IndexColumn.class
+ );
+ JoinTable assocTable = property.getAnnotation( JoinTable.class );
+
+ IndexColumn indexColumn = IndexColumn.buildColumnFromAnnotation(
+ indexAnn, propertyHolder, inferredData, mappings
+ );
+ CollectionBinder collectionBinder = CollectionBinder.getCollectionBinder(
+ propertyHolder.getEntityName(),
+ property,
+ !indexColumn.isImplicit()
+ );
+ collectionBinder.setIndexColumn( indexColumn );
+ MapKey mapKeyAnn = property.getAnnotation( MapKey.class );
+ collectionBinder.setMapKey( mapKeyAnn );
+ collectionBinder.setPropertyName( inferredData.getPropertyName() );
+ BatchSize batchAnn = property.getAnnotation( BatchSize.class );
+ collectionBinder.setBatchSize( batchAnn );
+ javax.persistence.OrderBy ejb3OrderByAnn = property.getAnnotation( javax.persistence.OrderBy.class );
+ OrderBy orderByAnn = property.getAnnotation( OrderBy.class );
+ collectionBinder.setEjb3OrderBy( ejb3OrderByAnn );
+ collectionBinder.setSqlOrderBy( orderByAnn );
+ Sort sortAnn = property.getAnnotation( Sort.class );
+ collectionBinder.setSort( sortAnn );
+ Cache cachAnn = property.getAnnotation( Cache.class );
+ collectionBinder.setCache( cachAnn );
+ collectionBinder.setPropertyHolder( propertyHolder );
+ Cascade hibernateCascade = property.getAnnotation( Cascade.class );
+ NotFound notFound = property.getAnnotation( NotFound.class );
+ boolean ignoreNotFound = notFound != null && notFound.action().equals( NotFoundAction.IGNORE );
+ collectionBinder.setIgnoreNotFound( ignoreNotFound );
+ collectionBinder.setCollectionType( inferredData.getProperty().getElementClass() );
+ collectionBinder.setMappings( mappings );
+ collectionBinder.setPropertyAccessorName( inferredData.getDefaultAccess() );
+
+ Ejb3Column[] elementColumns = null;
+ PropertyData virtualProperty = new WrappedInferredData( inferredData, "element" );
+ if ( property.isAnnotationPresent( Column.class ) || property.isAnnotationPresent(
+ Formula.class
+ ) ) {
+ Column ann = property.getAnnotation( Column.class );
+ Formula formulaAnn = property.getAnnotation( Formula.class );
+ elementColumns = Ejb3Column.buildColumnFromAnnotation(
+ new Column[] { ann },
+ formulaAnn,
+ nullability,
+ propertyHolder,
+ virtualProperty,
+ entityBinder.getSecondaryTables(),
+ mappings
+ );
+ }
+ else if ( property.isAnnotationPresent( Columns.class ) ) {
+ Columns anns = property.getAnnotation( Columns.class );
+ elementColumns = Ejb3Column.buildColumnFromAnnotation(
+ anns.columns(), null, nullability, propertyHolder, virtualProperty,
+ entityBinder.getSecondaryTables(), mappings
+ );
+ }
+ else {
+ elementColumns = Ejb3Column.buildColumnFromAnnotation(
+ null,
+ null,
+ nullability,
+ propertyHolder,
+ virtualProperty,
+ entityBinder.getSecondaryTables(),
+ mappings
+ );
+ }
+
+ org.hibernate.annotations.MapKey hibMapKeyAnn = property.getAnnotation(
+ org.hibernate.annotations.MapKey.class
+ );
+ PropertyData mapKeyVirtualProperty = new WrappedInferredData( inferredData, "mapkey" );
+ Ejb3Column[] mapColumns = Ejb3Column.buildColumnFromAnnotation(
+ hibMapKeyAnn != null && hibMapKeyAnn.columns().length > 0 ?
+ hibMapKeyAnn.columns() :
+ null,
+ null,
+ Nullability.FORCED_NOT_NULL,
+ propertyHolder,
+ mapKeyVirtualProperty,
+ entityBinder.getSecondaryTables(),
+ mappings
+ );
+ collectionBinder.setMapKeyColumns( mapColumns );
+
+ MapKeyManyToMany mapKeyManyToMany = property.getAnnotation( MapKeyManyToMany.class );
+ Ejb3JoinColumn[] mapJoinColumns = Ejb3JoinColumn.buildJoinColumns(
+ mapKeyManyToMany != null ?
+ mapKeyManyToMany.joinColumns() :
+ null,
+ null, entityBinder.getSecondaryTables(),
+ propertyHolder, mapKeyVirtualProperty.getPropertyName(), mappings
+ );
+ collectionBinder.setMapKeyManyToManyColumns( mapJoinColumns );
+
+ //potential element
+ collectionBinder.setEmbedded( property.isAnnotationPresent( Embedded.class ) );
+ collectionBinder.setElementColumns( elementColumns );
+ collectionBinder.setProperty( property );
+
+ //TODO enhance exception with @ManyToAny and @CollectionOfElements
+ if ( oneToManyAnn != null && manyToManyAnn != null ) {
+ throw new AnnotationException(
+ "@OneToMany and @ManyToMany on the same property is not allowed: "
+ + propertyHolder.getEntityName() + "." + inferredData.getPropertyName()
+ );
+ }
+ String mappedBy = null;
+ if ( oneToManyAnn != null ) {
+ for (Ejb3JoinColumn column : joinColumns) {
+ if ( column.isSecondary() ) {
+ throw new NotYetImplementedException( "Collections having FK in secondary table" );
+ }
+ }
+ collectionBinder.setFkJoinColumns( joinColumns );
+ mappedBy = oneToManyAnn.mappedBy();
+ collectionBinder.setTargetEntity(
+ mappings.getReflectionManager().toXClass( oneToManyAnn.targetEntity() )
+ );
+ collectionBinder.setCascadeStrategy( getCascadeStrategy( oneToManyAnn.cascade(), hibernateCascade ) );
+ collectionBinder.setOneToMany( true );
+ }
+ else if ( collectionOfElementsAnn != null ) {
+ for (Ejb3JoinColumn column : joinColumns) {
+ if ( column.isSecondary() ) {
+ throw new NotYetImplementedException( "Collections having FK in secondary table" );
+ }
+ }
+ collectionBinder.setFkJoinColumns( joinColumns );
+ mappedBy = "";
+ collectionBinder.setTargetEntity(
+ mappings.getReflectionManager().toXClass( collectionOfElementsAnn.targetElement() )
+ );
+ //collectionBinder.setCascadeStrategy( getCascadeStrategy( embeddedCollectionAnn.cascade(), hibernateCascade ) );
+ collectionBinder.setOneToMany( true );
+ }
+ else if ( manyToManyAnn != null ) {
+ mappedBy = manyToManyAnn.mappedBy();
+ collectionBinder.setTargetEntity(
+ mappings.getReflectionManager().toXClass( manyToManyAnn.targetEntity() )
+ );
+ collectionBinder.setCascadeStrategy( getCascadeStrategy( manyToManyAnn.cascade(), hibernateCascade ) );
+ collectionBinder.setOneToMany( false );
+ }
+ else if ( property.isAnnotationPresent( ManyToAny.class ) ) {
+ mappedBy = "";
+ collectionBinder.setTargetEntity(
+ mappings.getReflectionManager().toXClass( void.class )
+ );
+ collectionBinder.setCascadeStrategy( getCascadeStrategy( null, hibernateCascade ) );
+ collectionBinder.setOneToMany( false );
+ }
+ collectionBinder.setMappedBy( mappedBy );
+ bindJoinedTableAssociation(
+ assocTable, mappings, entityBinder, collectionBinder, propertyHolder, inferredData, mappedBy
+ );
+
+ OnDelete onDeleteAnn = property.getAnnotation( OnDelete.class );
+ boolean onDeleteCascade = onDeleteAnn != null && OnDeleteAction.CASCADE.equals( onDeleteAnn.action() );
+ collectionBinder.setCascadeDeleteEnabled( onDeleteCascade );
+ if ( isIdentifierMapper ) {
+ collectionBinder.setInsertable( false );
+ collectionBinder.setUpdatable( false );
+ }
+ if ( property.isAnnotationPresent( CollectionId.class ) ) { //do not compute the generators unless necessary
+ HashMap<String, IdGenerator> localGenerators = (HashMap<String, IdGenerator>) classGenerators.clone();
+ localGenerators.putAll( buildLocalGenerators( property, mappings ) );
+ collectionBinder.setLocalGenerators( localGenerators );
+
+ }
+ collectionBinder.bind();
+
+ }
+ else {
+ //define whether the type is a component or not
+ boolean isComponent = false;
+ Embeddable embeddableAnn = returnedClass.getAnnotation( Embeddable.class );
+ Embedded embeddedAnn = property.getAnnotation( Embedded.class );
+ isComponent = embeddedAnn != null || embeddableAnn != null;
+
+ if ( isComponent ) {
+ //process component object
+ //boolean propertyAccess = true;
+ //if ( embeddableAnn != null && embeddableAnn.access() == AccessType.FIELD ) propertyAccess = false;
+ boolean propertyAnnotated = entityBinder.isPropertyAnnotated( property );
+ String propertyAccessor = entityBinder.getPropertyAccessor( property );
+ bindComponent(
+ inferredData, propertyHolder, propertyAnnotated, propertyAccessor, entityBinder,
+ isIdentifierMapper,
+ mappings, isComponentEmbedded
+ );
+ }
+ else {
+ //provide the basic property mapping
+ boolean optional = true;
+ boolean lazy = false;
+ if ( property.isAnnotationPresent( Basic.class ) ) {
+ Basic ann = property.getAnnotation( Basic.class );
+ optional = ann.optional();
+ lazy = ann.fetch() == FetchType.LAZY;
+ }
+ //implicit type will check basic types and Serializable classes
+ if ( !optional && nullability != Nullability.FORCED_NULL ) {
+ //force columns to not null
+ for (Ejb3Column col : columns) {
+ col.forceNotNull();
+ }
+ }
+
+ PropertyBinder propBinder = new PropertyBinder();
+ propBinder.setName( inferredData.getPropertyName() );
+ propBinder.setReturnedClassName( inferredData.getTypeName() );
+ propBinder.setLazy( lazy );
+ propBinder.setPropertyAccessorName( inferredData.getDefaultAccess() );
+ propBinder.setColumns( columns );
+ propBinder.setHolder( propertyHolder );
+ propBinder.setProperty( property );
+ propBinder.setReturnedClass( inferredData.getPropertyClass() );
+ propBinder.setMappings( mappings );
+ if ( isIdentifierMapper ) {
+ propBinder.setInsertable( false );
+ propBinder.setUpdatable( false );
+ }
+ propBinder.bind();
+ }
+ }
+ //init index
+ //process indexes after everything: in second pass, many to one has to be done before indexes
+ Index index = property.getAnnotation( Index.class );
+ if ( index != null ) {
+ if ( joinColumns != null ) {
+
+ for (Ejb3Column column : joinColumns) {
+ column.addIndex( index, inSecondPass );
+ }
+ }
+ else {
+ if ( columns != null ) {
+ for (Ejb3Column column : columns) {
+ column.addIndex( index, inSecondPass );
+ }
+ }
+ }
+ }
+
+ NaturalId naturalIdAnn = property.getAnnotation( NaturalId.class );
+ if ( naturalIdAnn != null ) {
+ if ( joinColumns != null ) {
+ for (Ejb3Column column : joinColumns) {
+ column.addUniqueKey( "_UniqueKey", inSecondPass );
+ }
+ }
+ else {
+ for (Ejb3Column column : columns) {
+ column.addUniqueKey( "_UniqueKey", inSecondPass );
+ }
+ }
+ }
+ }
+
+ //TODO move that to collection binder?
+ private static void bindJoinedTableAssociation(
+ JoinTable joinTableAnn, ExtendedMappings mappings, EntityBinder entityBinder,
+ CollectionBinder collectionBinder, PropertyHolder propertyHolder, PropertyData inferredData,
+ String mappedBy
+ ) {
+ TableBinder associationTableBinder = new TableBinder();
+ JoinColumn[] annJoins;
+ JoinColumn[] annInverseJoins;
+ if ( joinTableAnn != null ) {
+ collectionBinder.setExplicitAssociationTable( true );
+ if ( !BinderHelper.isDefault( joinTableAnn.schema() ) )
+ associationTableBinder.setSchema( joinTableAnn.schema() );
+ if ( !BinderHelper.isDefault( joinTableAnn.catalog() ) )
+ associationTableBinder.setCatalog( joinTableAnn.catalog() );
+ if ( !BinderHelper.isDefault( joinTableAnn.name() ) ) associationTableBinder.setName( joinTableAnn.name() );
+ associationTableBinder.setUniqueConstraints( joinTableAnn.uniqueConstraints() );
+
+ //set check constaint in the second pass
+
+ JoinColumn[] joins = joinTableAnn.joinColumns();
+
+ if ( joins.length == 0 ) {
+ annJoins = null;
+ }
+ else {
+ annJoins = joins;
+ }
+
+ JoinColumn[] inverseJoins = joinTableAnn.inverseJoinColumns();
+
+ if ( inverseJoins.length == 0 ) {
+ annInverseJoins = null;
+ }
+ else {
+ annInverseJoins = inverseJoins;
+ }
+ }
+ else {
+ annJoins = null;
+ annInverseJoins = null;
+ }
+ Ejb3JoinColumn[] joinColumns = Ejb3JoinColumn.buildJoinTableJoinColumns(
+ annJoins, entityBinder.getSecondaryTables(), propertyHolder, inferredData.getPropertyName(), mappedBy,
+ mappings
+ );
+ Ejb3JoinColumn[] inverseJoinColumns = Ejb3JoinColumn.buildJoinTableJoinColumns(
+ annInverseJoins, entityBinder.getSecondaryTables(), propertyHolder, inferredData.getPropertyName(),
+ mappedBy, mappings
+ );
+ associationTableBinder.setMappings( mappings );
+ collectionBinder.setTableBinder( associationTableBinder );
+ collectionBinder.setJoinColumns( joinColumns );
+ collectionBinder.setInverseJoinColumns( inverseJoinColumns );
+ }
+
+ private static void bindComponent(
+ PropertyData inferredData,
+ PropertyHolder propertyHolder,
+ boolean propertyAnnotated,
+ String propertyAccessor, EntityBinder entityBinder,
+ boolean isIdentifierMapper,
+ ExtendedMappings mappings, boolean isComponentEmbedded
+ ) {
+ Component comp = fillComponent(
+ propertyHolder, inferredData, propertyAnnotated, propertyAccessor, true, entityBinder,
+ isComponentEmbedded, isIdentifierMapper,
+ false, mappings
+ );
+ XProperty property = inferredData.getProperty();
+ setupComponentTuplizer( property, comp );
+
+ PropertyBinder binder = new PropertyBinder();
+ binder.setName( inferredData.getPropertyName() );
+ binder.setValue( comp );
+ binder.setProperty( inferredData.getProperty() );
+ binder.setPropertyAccessorName( inferredData.getDefaultAccess() );
+ Property prop = binder.make();
+ propertyHolder.addProperty( prop );
+ }
+
+ public static Component fillComponent(
+ PropertyHolder propertyHolder, PropertyData inferredData,
+ boolean propertyAnnotated, String propertyAccessor, boolean isNullable,
+ EntityBinder entityBinder,
+ boolean isComponentEmbedded, boolean isIdentifierMapper, boolean inSecondPass, ExtendedMappings mappings
+ ) {
+ /**
+ * inSecondPass can only be used to apply right away the second pass of a composite-element
+ * Because it's a value type, there is no bidirectional association, hence second pass
+ * ordering does not matter
+ */
+ Component comp = new Component( propertyHolder.getPersistentClass() );
+ comp.setEmbedded( isComponentEmbedded );
+ //yuk
+ comp.setTable( propertyHolder.getTable() );
+ if ( !isIdentifierMapper ) {
+ comp.setComponentClassName( inferredData.getClassOrElementName() );
+ }
+ else {
+ comp.setComponentClassName( comp.getOwner().getClassName() );
+ }
+ comp.setNodeName( inferredData.getPropertyName() );
+ String subpath = StringHelper.qualify( propertyHolder.getPath(), inferredData.getPropertyName() );
+ log.debug( "Binding component with path: {}", subpath );
+ PropertyHolder subHolder = PropertyHolderBuilder.buildPropertyHolder(
+ comp, subpath,
+ inferredData, propertyHolder, mappings
+ );
+ List<PropertyData> classElements = new ArrayList<PropertyData>();
+ XClass returnedClassOrElement = inferredData.getClassOrElement();
+ addElementsOfAClass(
+ classElements,
+ subHolder,
+ propertyAnnotated,
+ propertyAccessor, returnedClassOrElement, mappings
+ );
+ //add elements of the embeddable superclass
+ XClass superClass = inferredData.getPropertyClass().getSuperclass();
+ while ( superClass != null && superClass.isAnnotationPresent( MappedSuperclass.class ) ) {
+ //FIXME: proper support of typevariables incl var resolved at upper levels
+ addElementsOfAClass(
+ classElements,
+ subHolder,
+ entityBinder.isPropertyAnnotated( superClass ),
+ propertyAccessor, superClass, mappings
+ );
+ superClass = superClass.getSuperclass();
+ }
+ for (PropertyData propertyAnnotatedElement : classElements) {
+ processElementAnnotations(
+ subHolder, isNullable ?
+ Nullability.NO_CONSTRAINT :
+ Nullability.FORCED_NOT_NULL,
+ propertyAnnotatedElement.getProperty(), propertyAnnotatedElement,
+ new HashMap<String, IdGenerator>(), entityBinder, isIdentifierMapper, isComponentEmbedded,
+ inSecondPass, mappings
+ );
+ }
+ return comp;
+ }
+
+ private static void bindId(
+ String generatorType, String generatorName,
+ PropertyData inferredData, Ejb3Column[] columns, PropertyHolder propertyHolder,
+ Map<String, IdGenerator> localGenerators,
+ boolean isComposite,
+ boolean isPropertyAnnotated,
+ String propertyAccessor, EntityBinder entityBinder, boolean isEmbedded,
+ boolean isIdentifierMapper, ExtendedMappings mappings
+ ) {
+ /*
+ * Fill simple value and property since and Id is a property
+ */
+ PersistentClass persistentClass = propertyHolder.getPersistentClass();
+ if ( !( persistentClass instanceof RootClass ) ) {
+ throw new AnnotationException(
+ "Unable to define/override @Id(s) on a subclass: "
+ + propertyHolder.getEntityName()
+ );
+ }
+ RootClass rootClass = (RootClass) persistentClass;
+ String persistentClassName = rootClass == null ?
+ null :
+ rootClass.getClassName();
+ SimpleValue id;
+ if ( isComposite ) {
+ id = fillComponent(
+ propertyHolder, inferredData, isPropertyAnnotated, propertyAccessor,
+ false, entityBinder, isEmbedded, isIdentifierMapper, false, mappings
+ );
+ Component componentId = (Component) id;
+ componentId.setKey( true );
+ if ( rootClass.getIdentifier() != null ) {
+ throw new AnnotationException( componentId.getComponentClassName() + " must not have @Id properties when used as an @EmbeddedId" );
+ }
+ if ( componentId.getPropertySpan() == 0 ) {
+ throw new AnnotationException( componentId.getComponentClassName() + " has no persistent id property" );
+ }
+ //tuplizers
+ XProperty property = inferredData.getProperty();
+ setupComponentTuplizer( property, componentId );
+ }
+ else {
+ for (Ejb3Column column : columns) {
+ column.forceNotNull(); //this is an id
+ }
+ SimpleValueBinder value = new SimpleValueBinder();
+ value.setPropertyName( inferredData.getPropertyName() );
+ value.setReturnedClassName( inferredData.getTypeName() );
+ value.setColumns( columns );
+ value.setPersistentClassName( persistentClassName );
+ value.setMappings( mappings );
+ value.setType( inferredData.getProperty(), inferredData.getClassOrElement() );
+ id = value.make();
+ }
+ rootClass.setIdentifier( id );
+ BinderHelper.makeIdGenerator( id, generatorType, generatorName, mappings, localGenerators );
+ if ( isEmbedded ) {
+ rootClass.setEmbeddedIdentifier( inferredData.getPropertyClass() == null );
+ }
+ else {
+ PropertyBinder binder = new PropertyBinder();
+ binder.setName( inferredData.getPropertyName() );
+ binder.setValue( id );
+ binder.setPropertyAccessorName( inferredData.getDefaultAccess() );
+ binder.setProperty( inferredData.getProperty() );
+ Property prop = binder.make();
+ rootClass.setIdentifierProperty( prop );
+ }
+ }
+
+ private static void setupComponentTuplizer(XProperty property, Component component) {
+ if ( property == null ) return;
+ if ( property.isAnnotationPresent( Tuplizers.class ) ) {
+ for (Tuplizer tuplizer : property.getAnnotation( Tuplizers.class ).value()) {
+ EntityMode mode = EntityMode.parse( tuplizer.entityMode() );
+ component.addTuplizer( mode, tuplizer.impl().getName() );
+ }
+ }
+ if ( property.isAnnotationPresent( Tuplizer.class ) ) {
+ Tuplizer tuplizer = property.getAnnotation( Tuplizer.class );
+ EntityMode mode = EntityMode.parse( tuplizer.entityMode() );
+ component.addTuplizer( mode, tuplizer.impl().getName() );
+ }
+ }
+
+ private static void bindManyToOne(
+ String cascadeStrategy, Ejb3JoinColumn[] columns, boolean optional,
+ boolean ignoreNotFound, boolean cascadeOnDelete,
+ XClass targetEntity, PropertyHolder propertyHolder,
+ PropertyData inferredData, boolean unique, boolean isIdentifierMapper, boolean inSecondPass,
+ ExtendedMappings mappings
+ ) {
+ //All FK columns should be in the same table
+ org.hibernate.mapping.ManyToOne value = new org.hibernate.mapping.ManyToOne( columns[0].getTable() );
+ if ( isDefault( targetEntity, mappings ) ) {
+ value.setReferencedEntityName( inferredData.getClassOrElementName() );
+ }
+ else {
+ value.setReferencedEntityName( targetEntity.getName() );
+ }
+ defineFetchingStrategy( value, inferredData.getProperty() );
+ //value.setFetchMode( fetchMode );
+ value.setIgnoreNotFound( ignoreNotFound );
+ value.setCascadeDeleteEnabled( cascadeOnDelete );
+ //value.setLazy( fetchMode != FetchMode.JOIN );
+ if ( !optional ) {
+ for (Ejb3JoinColumn column : columns) {
+ column.setNullable( false );
+ }
+ }
+ value.setTypeName( inferredData.getClassOrElementName() );
+ final String propertyName = inferredData.getPropertyName();
+ value.setTypeUsingReflection( propertyHolder.getClassName(), propertyName );
+
+ ForeignKey fk = inferredData.getProperty().getAnnotation( ForeignKey.class );
+ String fkName = fk != null ?
+ fk.name() :
+ "";
+ if ( !BinderHelper.isDefault( fkName ) ) value.setForeignKeyName( fkName );
+
+ String path = propertyHolder.getPath() + "." + propertyName;
+ FkSecondPass secondPass = new ToOneFkSecondPass(
+ value, columns,
+ !optional && unique, //cannot have nullabe and unique on certain DBs like Derby
+ propertyHolder.getEntityOwnerClassName(),
+ path, mappings
+ );
+ if ( inSecondPass ) {
+ secondPass.doSecondPass( mappings.getClasses() );
+ }
+ else {
+ mappings.addSecondPass(
+ secondPass
+ );
+ }
+ Ejb3Column.checkPropertyConsistency( columns, propertyHolder.getEntityName() + propertyName );
+ PropertyBinder binder = new PropertyBinder();
+ binder.setName( propertyName );
+ binder.setValue( value );
+ //binder.setCascade(cascadeStrategy);
+ if ( isIdentifierMapper ) {
+ binder.setInsertable( false );
+ binder.setUpdatable( false );
+ }
+ else {
+ binder.setInsertable( columns[0].isInsertable() );
+ binder.setUpdatable( columns[0].isUpdatable() );
+ }
+ binder.setPropertyAccessorName( inferredData.getDefaultAccess() );
+ binder.setCascade( cascadeStrategy );
+ binder.setProperty(inferredData.getProperty());
+ Property prop = binder.make();
+ //composite FK columns are in the same table so its OK
+ propertyHolder.addProperty( prop, columns );
+ }
+
+ protected static void defineFetchingStrategy(ToOne toOne, XProperty property) {
+ LazyToOne lazy = property.getAnnotation( LazyToOne.class );
+ Fetch fetch = property.getAnnotation( Fetch.class );
+ ManyToOne manyToOne = property.getAnnotation( ManyToOne.class );
+ OneToOne oneToOne = property.getAnnotation( OneToOne.class );
+ FetchType fetchType;
+ if ( manyToOne != null ) {
+ fetchType = manyToOne.fetch();
+ }
+ else if ( oneToOne != null ) {
+ fetchType = oneToOne.fetch();
+ }
+ else {
+ throw new AssertionFailure(
+ "Define fetch strategy on a property not annotated with @OneToMany nor @OneToOne"
+ );
+ }
+ if ( lazy != null ) {
+ toOne.setLazy( !( lazy.value() == LazyToOneOption.FALSE ) );
+ toOne.setUnwrapProxy( ( lazy.value() == LazyToOneOption.NO_PROXY ) );
+ }
+ else {
+ toOne.setLazy( fetchType == FetchType.LAZY );
+ toOne.setUnwrapProxy( false );
+ }
+ if ( fetch != null ) {
+ if ( fetch.value() == org.hibernate.annotations.FetchMode.JOIN ) {
+ toOne.setFetchMode( FetchMode.JOIN );
+ toOne.setLazy( false );
+ toOne.setUnwrapProxy( false );
+ }
+ else if ( fetch.value() == org.hibernate.annotations.FetchMode.SELECT ) {
+ toOne.setFetchMode( FetchMode.SELECT );
+ }
+ else if ( fetch.value() == org.hibernate.annotations.FetchMode.SUBSELECT ) {
+ throw new AnnotationException( "Use of FetchMode.SUBSELECT not allowed on ToOne associations" );
+ }
+ else {
+ throw new AssertionFailure( "Unknown FetchMode: " + fetch.value() );
+ }
+ }
+ else {
+ toOne.setFetchMode( getFetchMode( fetchType ) );
+ }
+ }
+
+ private static void bindOneToOne(
+ String cascadeStrategy,
+ Ejb3JoinColumn[] joinColumns,
+ boolean optional,
+ FetchMode fetchMode,
+ boolean ignoreNotFound,
+ boolean cascadeOnDelete,
+ XClass targetEntity,
+ PropertyHolder propertyHolder,
+ PropertyData inferredData, String mappedBy,
+ boolean trueOneToOne,
+ boolean isIdentifierMapper, boolean inSecondPass, ExtendedMappings mappings
+ ) {
+ //column.getTable() => persistentClass.getTable()
+ final String propertyName = inferredData.getPropertyName();
+ log.debug( "Fetching {} with {}", propertyName, fetchMode );
+ boolean mapToPK = true;
+ if ( !trueOneToOne ) {
+ //try to find a hidden true one to one (FK == PK columns)
+ KeyValue identifier = propertyHolder.getIdentifier();
+ if ( identifier == null ) {
+ //this is a @OneToOne in a @EmbeddedId (the persistentClass.identifier is not set yet, it's being built)
+ //by definition the PK cannot refers to itself so it cannot map to itself
+ mapToPK = false;
+ }
+ else {
+ Iterator idColumns = identifier.getColumnIterator();
+ List<String> idColumnNames = new ArrayList<String>();
+ org.hibernate.mapping.Column currentColumn;
+ while ( idColumns.hasNext() ) {
+ currentColumn = (org.hibernate.mapping.Column) idColumns.next();
+ idColumnNames.add( currentColumn.getName() );
+ }
+ for (Ejb3JoinColumn col : joinColumns) {
+ if ( !idColumnNames.contains( col.getMappingColumn().getName() ) ) {
+ mapToPK = false;
+ break;
+ }
+ }
+ }
+ }
+ if ( trueOneToOne || mapToPK || !BinderHelper.isDefault( mappedBy ) ) {
+ //is a true one-to-one
+ //FIXME referencedColumnName ignored => ordering may fail.
+ OneToOneSecondPass secondPass = new OneToOneSecondPass(
+ mappedBy,
+ propertyHolder.getEntityName(),
+ propertyName,
+ propertyHolder, inferredData, targetEntity, ignoreNotFound, cascadeOnDelete,
+ optional, cascadeStrategy, joinColumns, mappings
+ );
+ if ( inSecondPass ) {
+ secondPass.doSecondPass( mappings.getClasses() );
+ }
+ else {
+ mappings.addSecondPass(
+ secondPass, BinderHelper.isDefault( mappedBy )
+ );
+ }
+ }
+ else {
+ //has a FK on the table
+ bindManyToOne(
+ cascadeStrategy, joinColumns, optional, ignoreNotFound, cascadeOnDelete,
+ targetEntity,
+ propertyHolder, inferredData, true, isIdentifierMapper, inSecondPass, mappings
+ );
+ }
+ }
+
+ private static void bindAny(
+ String cascadeStrategy, Ejb3JoinColumn[] columns, boolean cascadeOnDelete, Nullability nullability,
+ PropertyHolder propertyHolder, PropertyData inferredData, EntityBinder entityBinder,
+ boolean isIdentifierMapper, ExtendedMappings mappings
+ ) {
+ org.hibernate.annotations.Any anyAnn = inferredData.getProperty().getAnnotation( org.hibernate.annotations.Any.class );
+ if ( anyAnn == null ) {
+ throw new AssertionFailure( "Missing @Any annotation: "
+ + StringHelper.qualify( propertyHolder.getPath(), inferredData.getPropertyName() ) );
+ }
+ Any value = BinderHelper.buildAnyValue( anyAnn.metaDef(), columns, anyAnn.metaColumn(), inferredData,
+ cascadeOnDelete, nullability, propertyHolder, entityBinder, anyAnn.optional(), mappings );
+
+ PropertyBinder binder = new PropertyBinder();
+ binder.setName( inferredData.getPropertyName() );
+ binder.setValue( value );
+
+ binder.setLazy( anyAnn.fetch() == FetchType.LAZY );
+ //binder.setCascade(cascadeStrategy);
+ if ( isIdentifierMapper ) {
+ binder.setInsertable( false );
+ binder.setUpdatable( false );
+ }
+ else {
+ binder.setInsertable( columns[0].isInsertable() );
+ binder.setUpdatable( columns[0].isUpdatable() );
+ }
+ binder.setPropertyAccessorName( inferredData.getDefaultAccess() );
+ binder.setCascade( cascadeStrategy );
+ Property prop = binder.make();
+ //composite FK columns are in the same table so its OK
+ propertyHolder.addProperty( prop, columns );
+ }
+
+ private static String generatorType(GenerationType generatorEnum) {
+ switch ( generatorEnum ) {
+ case IDENTITY:
+ return "identity";
+ case AUTO:
+ return "native";
+ case TABLE:
+ return MultipleHiLoPerTableGenerator.class.getName();
+ case SEQUENCE:
+ return "seqhilo";
+ }
+ throw new AssertionFailure( "Unknown GeneratorType: " + generatorEnum );
+ }
+
+ private static EnumSet<CascadeType> convertToHibernateCascadeType(javax.persistence.CascadeType[] ejbCascades) {
+ EnumSet<CascadeType> hibernateCascadeSet = EnumSet.noneOf( CascadeType.class );
+ if ( ejbCascades != null && ejbCascades.length > 0 ) {
+ for (javax.persistence.CascadeType cascade : ejbCascades) {
+ switch ( cascade ) {
+ case ALL:
+ hibernateCascadeSet.add( CascadeType.ALL );
+ break;
+ case PERSIST:
+ hibernateCascadeSet.add( CascadeType.PERSIST );
+ break;
+ case MERGE:
+ hibernateCascadeSet.add( CascadeType.MERGE );
+ break;
+ case REMOVE:
+ hibernateCascadeSet.add( CascadeType.REMOVE );
+ break;
+ case REFRESH:
+ hibernateCascadeSet.add( CascadeType.REFRESH );
+ break;
+ }
+ }
+ }
+
+ return hibernateCascadeSet;
+ }
+
+ private static String getCascadeStrategy(
+ javax.persistence.CascadeType[] ejbCascades, Cascade hibernateCascadeAnnotation
+ ) {
+ EnumSet<CascadeType> hibernateCascadeSet = convertToHibernateCascadeType( ejbCascades );
+ CascadeType[] hibernateCascades = hibernateCascadeAnnotation == null ?
+ null :
+ hibernateCascadeAnnotation.value();
+
+ if ( hibernateCascades != null && hibernateCascades.length > 0 ) {
+ for (CascadeType cascadeType : hibernateCascades) {
+ hibernateCascadeSet.add( cascadeType );
+ }
+ }
+
+ StringBuilder cascade = new StringBuilder();
+ Iterator<CascadeType> cascadeType = hibernateCascadeSet.iterator();
+ while ( cascadeType.hasNext() ) {
+ switch ( cascadeType.next() ) {
+ case ALL:
+ cascade.append( "," ).append( "all" );
+ break;
+ case SAVE_UPDATE:
+ cascade.append( "," ).append( "save-update" );
+ break;
+ case PERSIST:
+ cascade.append( "," ).append( "persist" );
+ break;
+ case MERGE:
+ cascade.append( "," ).append( "merge" );
+ break;
+ case LOCK:
+ cascade.append( "," ).append( "lock" );
+ break;
+ case REFRESH:
+ cascade.append( "," ).append( "refresh" );
+ break;
+ case REPLICATE:
+ cascade.append( "," ).append( "replicate" );
+ break;
+ case EVICT:
+ cascade.append( "," ).append( "evict" );
+ break;
+ case DELETE:
+ cascade.append( "," ).append( "delete" );
+ break;
+ case DELETE_ORPHAN:
+ cascade.append( "," ).append( "delete-orphan" );
+ break;
+ case REMOVE:
+ cascade.append( "," ).append( "delete" );
+ break;
+ }
+ }
+ return cascade.length() > 0 ?
+ cascade.substring( 1 ) :
+ "none";
+ }
+
+ public static FetchMode getFetchMode(FetchType fetch) {
+ if ( fetch == FetchType.EAGER ) {
+ return FetchMode.JOIN;
+ }
+ else {
+ return FetchMode.SELECT;
+ }
+ }
+
+ private static HashMap<String, IdGenerator> buildLocalGenerators(XAnnotatedElement annElt, Mappings mappings) {
+ HashMap<String, IdGenerator> generators = new HashMap<String, IdGenerator>();
+ TableGenerator tabGen = annElt.getAnnotation( TableGenerator.class );
+ SequenceGenerator seqGen = annElt.getAnnotation( SequenceGenerator.class );
+ GenericGenerator genGen = annElt.getAnnotation( GenericGenerator.class );
+ if ( tabGen != null ) {
+ IdGenerator idGen = buildIdGenerator( tabGen, mappings );
+ generators.put( idGen.getName(), idGen );
+ }
+ if ( seqGen != null ) {
+ IdGenerator idGen = buildIdGenerator( seqGen, mappings );
+ generators.put( idGen.getName(), idGen );
+ }
+ if ( genGen != null ) {
+ IdGenerator idGen = buildIdGenerator( genGen, mappings );
+ generators.put( idGen.getName(), idGen );
+ }
+ return generators;
+ }
+
+ public static boolean isDefault(XClass clazz, ExtendedMappings mappings) {
+ return mappings.getReflectionManager().equals( clazz, void.class );
+ }
+
+ public static Map<XClass, InheritanceState> buildInheritanceStates(
+ List<XClass> orderedClasses, ReflectionManager reflectionManager
+ ) {
+ Map<XClass, InheritanceState> inheritanceStatePerClass = new HashMap<XClass, InheritanceState>(
+ orderedClasses.size()
+ );
+ for (XClass clazz : orderedClasses) {
+ InheritanceState superclassState = InheritanceState.getSuperclassInheritanceState(
+ clazz, inheritanceStatePerClass,
+ reflectionManager
+ );
+ InheritanceState state = new InheritanceState( clazz );
+ if ( superclassState != null ) {
+ //the classes are ordered thus preventing an NPE
+ //FIXME if an entity has subclasses annotated @MappedSperclass wo sub @Entity this is wrong
+ superclassState.hasSons = true;
+ InheritanceState superEntityState = InheritanceState.getSuperEntityInheritanceState(
+ clazz, inheritanceStatePerClass,
+ reflectionManager
+ );
+ state.hasParents = superEntityState != null;
+ final boolean nonDefault = state.type != null && !InheritanceType.SINGLE_TABLE.equals( state.type );
+ if ( superclassState.type != null ) {
+ final boolean mixingStrategy = state.type != null && !state.type.equals( superclassState.type );
+ if ( nonDefault && mixingStrategy ) {
+ log.warn(
+ "Mixing inheritance strategy in a entity hierarchy is not allowed, ignoring sub strategy in: {}",
+ clazz.getName()
+ );
+ }
+ state.type = superclassState.type;
+ }
+ }
+ inheritanceStatePerClass.put( clazz, state );
+ }
+ return inheritanceStatePerClass;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/AnnotationConfiguration.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/AnnotationConfiguration.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/AnnotationConfiguration.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,1073 @@
+// $Id: AnnotationConfiguration.java 14990 2008-07-29 18:14:14Z hardy.ferentschik $
+package org.hibernate.cfg;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.ResourceBundle;
+import java.util.Set;
+import java.util.StringTokenizer;
+
+import javax.persistence.Entity;
+import javax.persistence.MappedSuperclass;
+
+import org.dom4j.Attribute;
+import org.dom4j.Document;
+import org.dom4j.DocumentException;
+import org.dom4j.Element;
+import org.dom4j.io.SAXReader;
+import org.hibernate.AnnotationException;
+import org.hibernate.HibernateException;
+import org.hibernate.Interceptor;
+import org.hibernate.MappingException;
+import org.hibernate.SessionFactory;
+import org.hibernate.annotations.AnyMetaDef;
+import org.hibernate.annotations.common.reflection.ReflectionManager;
+import org.hibernate.annotations.common.reflection.XClass;
+import org.hibernate.cfg.annotations.Version;
+import org.hibernate.cfg.annotations.reflection.EJB3ReflectionManager;
+import org.hibernate.event.EventListeners;
+import org.hibernate.event.PreInsertEventListener;
+import org.hibernate.event.PreUpdateEventListener;
+import org.hibernate.mapping.Column;
+import org.hibernate.mapping.Join;
+import org.hibernate.mapping.PersistentClass;
+import org.hibernate.mapping.Table;
+import org.hibernate.mapping.UniqueKey;
+import org.hibernate.util.JoinedIterator;
+import org.hibernate.util.ReflectHelper;
+import org.hibernate.util.StringHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+
+/**
+ * Similar to the {@link Configuration} object but handles EJB3 and Hibernate
+ * specific annotations as a metadata facility.
+ *
+ * @author Emmanuel Bernard
+ * @author Hardy Ferentschik
+ */
+public class AnnotationConfiguration extends Configuration {
+ private Logger log = LoggerFactory.getLogger( AnnotationConfiguration.class );
+
+ /**
+ * Class name of the class needed to enable Search.
+ */
+ private static final String SEARCH_STARTUP_CLASS = "org.hibernate.search.event.EventListenerRegister";
+
+ /**
+ * Method to call to enable Search.
+ */
+ private static final String SEARCH_STARTUP_METHOD = "enableHibernateSearch";
+
+ static {
+ Version.touch(); //touch version
+ }
+
+ public static final String ARTEFACT = "hibernate.mapping.precedence";
+ public static final String DEFAULT_PRECEDENCE = "hbm, class";
+
+ private Map namedGenerators;
+ private Map<String, Map<String, Join>> joins;
+ private Map<String, AnnotatedClassType> classTypes;
+ private Set<String> defaultNamedQueryNames;
+ private Set<String> defaultNamedNativeQueryNames;
+ private Set<String> defaultSqlResulSetMappingNames;
+ private Set<String> defaultNamedGenerators;
+ private Map<String, Properties> generatorTables;
+ private Map<Table, List<String[]>> tableUniqueConstraints;
+ private Map<String, String> mappedByResolver;
+ private Map<String, String> propertyRefResolver;
+ private Map<String, AnyMetaDef> anyMetaDefs;
+ private List<XClass> annotatedClasses;
+ private Map<String, XClass> annotatedClassEntities;
+ private Map<String, Document> hbmEntities;
+ private List<CacheHolder> caches;
+ private List<Document> hbmDocuments; //user ordering matters, hence the list
+ private String precedence = null;
+ private boolean inSecondPass = false;
+ private transient ReflectionManager reflectionManager;
+ private boolean isDefaultProcessed = false;
+ private boolean isValidatorNotPresentLogged;
+
+ public AnnotationConfiguration() {
+ super();
+ }
+
+ public AnnotationConfiguration(SettingsFactory sf) {
+ super( sf );
+ }
+
+ protected List<XClass> orderAndFillHierarchy(List<XClass> original) {
+ //TODO remove embeddable
+ List<XClass> copy = new ArrayList<XClass>( original );
+ //for each class, copy all the relevant hierarchy
+ for (XClass clazz : original) {
+ XClass superClass = clazz.getSuperclass();
+ while ( superClass != null && !reflectionManager.equals( superClass, Object.class ) && !copy.contains( superClass ) ) {
+ if ( superClass.isAnnotationPresent( Entity.class )
+ || superClass.isAnnotationPresent( MappedSuperclass.class ) ) {
+ copy.add( superClass );
+ }
+ superClass = superClass.getSuperclass();
+ }
+ }
+ List<XClass> workingCopy = new ArrayList<XClass>( copy );
+ List<XClass> newList = new ArrayList<XClass>( copy.size() );
+ while ( workingCopy.size() > 0 ) {
+ XClass clazz = workingCopy.get( 0 );
+ orderHierarchy( workingCopy, newList, copy, clazz );
+ }
+ return newList;
+ }
+
+ private void orderHierarchy(List<XClass> copy, List<XClass> newList, List<XClass> original, XClass clazz) {
+ if ( clazz == null || reflectionManager.equals( clazz, Object.class ) ) return;
+ //process superclass first
+ orderHierarchy( copy, newList, original, clazz.getSuperclass() );
+ if ( original.contains( clazz ) ) {
+ if ( !newList.contains( clazz ) ) {
+ newList.add( clazz );
+ }
+ copy.remove( clazz );
+ }
+ }
+
+ /**
+ * Read a mapping from the class annotation metadata (JSR 175).
+ *
+ * @param persistentClass the mapped class
+ * @return the configuration object
+ */
+ public AnnotationConfiguration addAnnotatedClass(Class persistentClass) throws MappingException {
+ XClass persistentXClass = reflectionManager.toXClass( persistentClass );
+ try {
+ annotatedClasses.add( persistentXClass );
+ return this;
+ }
+ catch (MappingException me) {
+ log.error( "Could not compile the mapping annotations", me );
+ throw me;
+ }
+ }
+
+ /**
+ * Read package level metadata
+ *
+ * @param packageName java package name
+ * @return the configuration object
+ */
+ public AnnotationConfiguration addPackage(String packageName) throws MappingException {
+ log.info( "Mapping package {}", packageName );
+ try {
+ AnnotationBinder.bindPackage( packageName, createExtendedMappings() );
+ return this;
+ }
+ catch (MappingException me) {
+ log.error( "Could not compile the mapping annotations", me );
+ throw me;
+ }
+ }
+
+ public ExtendedMappings createExtendedMappings() {
+ return new ExtendedMappings(
+ classes,
+ collections,
+ tables,
+ namedQueries,
+ namedSqlQueries,
+ sqlResultSetMappings,
+ defaultNamedQueryNames,
+ defaultNamedNativeQueryNames,
+ defaultSqlResulSetMappingNames,
+ defaultNamedGenerators,
+ imports,
+ secondPasses,
+ propertyReferences,
+ namingStrategy,
+ typeDefs,
+ filterDefinitions,
+ namedGenerators,
+ joins,
+ classTypes,
+ extendsQueue,
+ tableNameBinding, columnNameBindingPerTable, auxiliaryDatabaseObjects,
+ generatorTables,
+ tableUniqueConstraints,
+ mappedByResolver,
+ propertyRefResolver,
+ anyMetaDefs,
+ reflectionManager
+ );
+ }
+
+ @Override
+ public void setCacheConcurrencyStrategy(
+ String clazz, String concurrencyStrategy, String region, boolean cacheLazyProperty
+ ) throws MappingException {
+ caches.add( new CacheHolder( clazz, concurrencyStrategy, region, true, cacheLazyProperty ) );
+ }
+
+ @Override
+ public void setCollectionCacheConcurrencyStrategy(String collectionRole, String concurrencyStrategy, String region)
+ throws MappingException {
+ caches.add( new CacheHolder( collectionRole, concurrencyStrategy, region, false, false ) );
+ }
+
+ @Override
+ protected void reset() {
+ super.reset();
+ namedGenerators = new HashMap();
+ joins = new HashMap<String, Map<String, Join>>();
+ classTypes = new HashMap<String, AnnotatedClassType>();
+ generatorTables = new HashMap<String, Properties>();
+ defaultNamedQueryNames = new HashSet<String>();
+ defaultNamedNativeQueryNames = new HashSet<String>();
+ defaultSqlResulSetMappingNames = new HashSet<String>();
+ defaultNamedGenerators = new HashSet<String>();
+ tableUniqueConstraints = new HashMap<Table, List<String[]>>();
+ mappedByResolver = new HashMap<String, String>();
+ propertyRefResolver = new HashMap<String, String>();
+ annotatedClasses = new ArrayList<XClass>();
+ caches = new ArrayList<CacheHolder>();
+ hbmEntities = new HashMap<String, Document>();
+ annotatedClassEntities = new HashMap<String, XClass>();
+ hbmDocuments = new ArrayList<Document>();
+ namingStrategy = EJB3NamingStrategy.INSTANCE;
+ setEntityResolver( new EJB3DTDEntityResolver() );
+ anyMetaDefs = new HashMap<String, AnyMetaDef>();
+ reflectionManager = new EJB3ReflectionManager();
+ }
+
+ @Override
+ protected void secondPassCompile() throws MappingException {
+ log.debug( "Execute first pass mapping processing" );
+ //build annotatedClassEntities
+ {
+ List<XClass> tempAnnotatedClasses = new ArrayList<XClass>( annotatedClasses.size() );
+ for (XClass clazz : annotatedClasses) {
+ if ( clazz.isAnnotationPresent( Entity.class ) ) {
+ annotatedClassEntities.put( clazz.getName(), clazz );
+ tempAnnotatedClasses.add( clazz );
+ }
+ else if ( clazz.isAnnotationPresent( MappedSuperclass.class ) ) {
+ tempAnnotatedClasses.add( clazz );
+ }
+ //only keep MappedSuperclasses and Entity in this list
+ }
+ annotatedClasses = tempAnnotatedClasses;
+ }
+
+ //process default values first
+ if ( !isDefaultProcessed ) {
+ AnnotationBinder.bindDefaults( createExtendedMappings() );
+ isDefaultProcessed = true;
+ }
+
+ //process entities
+ if ( precedence == null ) precedence = getProperties().getProperty( ARTEFACT );
+ if ( precedence == null ) precedence = DEFAULT_PRECEDENCE;
+ StringTokenizer precedences = new StringTokenizer( precedence, ",; ", false );
+ if ( !precedences.hasMoreElements() ) {
+ throw new MappingException( ARTEFACT + " cannot be empty: " + precedence );
+ }
+ while ( precedences.hasMoreElements() ) {
+ String artifact = (String) precedences.nextElement();
+ removeConflictedArtifact( artifact );
+ processArtifactsOfType( artifact );
+ }
+
+ int cacheNbr = caches.size();
+ for (int index = 0; index < cacheNbr; index++) {
+ CacheHolder cacheHolder = caches.get( index );
+ if ( cacheHolder.isClass ) {
+ super.setCacheConcurrencyStrategy(
+ cacheHolder.role, cacheHolder.usage, cacheHolder.region, cacheHolder.cacheLazy
+ );
+ }
+ else {
+ super.setCollectionCacheConcurrencyStrategy( cacheHolder.role, cacheHolder.usage, cacheHolder.region );
+ }
+ }
+ caches.clear();
+ try {
+ inSecondPass = true;
+ processFkSecondPassInOrder();
+ Iterator iter = secondPasses.iterator();
+ while ( iter.hasNext() ) {
+ SecondPass sp = (SecondPass) iter.next();
+ //do the second pass of fk before the others and remove them
+ if ( sp instanceof CreateKeySecondPass ) {
+ sp.doSecondPass( classes );
+ iter.remove();
+ }
+ }
+
+ iter = secondPasses.iterator();
+ while ( iter.hasNext() ) {
+ SecondPass sp = (SecondPass) iter.next();
+ //do the SecondaryTable second pass before any association becasue associations can be built on joins
+ if ( sp instanceof SecondaryTableSecondPass ) {
+ sp.doSecondPass( classes );
+ iter.remove();
+ }
+ }
+ super.secondPassCompile();
+ inSecondPass = false;
+ }
+ catch (RecoverableException e) {
+ //the exception was not recoverable after all
+ throw (RuntimeException) e.getCause();
+ }
+ Iterator tables = tableUniqueConstraints.entrySet().iterator();
+ Table table;
+ Map.Entry entry;
+ String keyName;
+ int uniqueIndexPerTable;
+ while ( tables.hasNext() ) {
+ entry = (Map.Entry) tables.next();
+ table = (Table) entry.getKey();
+ List<String[]> uniqueConstraints = (List<String[]>) entry.getValue();
+ uniqueIndexPerTable = 0;
+ for (String[] columnNames : uniqueConstraints) {
+ keyName = "key" + uniqueIndexPerTable++;
+ buildUniqueKeyFromColumnNames( columnNames, table, keyName );
+ }
+ }
+ boolean applyOnDdl = getProperties().getProperty(
+ "hibernate.validator.apply_to_ddl", //org.hibernate.validator.Environment.APPLY_TO_DDL
+ "true" )
+ .equalsIgnoreCase( "true" );
+
+ //TODO search for the method only once and cache it?
+ Constructor validatorCtr = null;
+ Method applyMethod = null;
+ try {
+ Class classValidator = ReflectHelper.classForName( "org.hibernate.validator.ClassValidator", this.getClass() );
+ Class messageInterpolator = ReflectHelper.classForName( "org.hibernate.validator.MessageInterpolator", this.getClass() );
+ validatorCtr = classValidator.getDeclaredConstructor(
+ Class.class, ResourceBundle.class, messageInterpolator, Map.class, ReflectionManager.class
+ );
+ applyMethod = classValidator.getMethod( "apply", PersistentClass.class );
+ }
+ catch (ClassNotFoundException e) {
+ if ( !isValidatorNotPresentLogged ) {
+ log.info( "Hibernate Validator not found: ignoring" );
+ }
+ isValidatorNotPresentLogged = true;
+ }
+ catch (NoSuchMethodException e) {
+ throw new AnnotationException( e );
+ }
+ if ( applyMethod != null && applyOnDdl ) {
+ for (PersistentClass persistentClazz : (Collection<PersistentClass>) classes.values()) {
+ //integrate the validate framework
+ String className = persistentClazz.getClassName();
+ if ( StringHelper.isNotEmpty( className ) ) {
+ try {
+ Object validator = validatorCtr.newInstance(
+ ReflectHelper.classForName( className ), null, null, null, reflectionManager
+ );
+ applyMethod.invoke( validator, persistentClazz );
+ }
+ catch (Exception e) {
+ log.warn( "Unable to apply constraints on DDL for " + className, e );
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Processes FKSecondPass instances trying to resolve any
+ * graph circularity (ie PK made of a many to one linking to
+ * an entity having a PK made of a ManyToOne ...).
+ */
+ private void processFkSecondPassInOrder() {
+ log.debug( "processing fk mappings (*ToOne and JoinedSubclass)" );
+ List<FkSecondPass> fkSecondPasses = getFKSecondPassesOnly();
+
+ if (fkSecondPasses.size() == 0) {
+ return; // nothing to do here
+ }
+
+ // split FkSecondPass instances into primary key and non primary key FKs.
+ // While doing so build a map of class names to FkSecondPass instances depending on this class.
+ Map<String, Set<FkSecondPass>> isADependencyOf = new HashMap<String, Set<FkSecondPass>>();
+ List endOfQueueFkSecondPasses = new ArrayList( fkSecondPasses.size() );
+ for (FkSecondPass sp : fkSecondPasses) {
+ if ( sp.isInPrimaryKey() ) {
+ String referenceEntityName = sp.getReferencedEntityName();
+ PersistentClass classMapping = getClassMapping( referenceEntityName );
+ String dependentTable = classMapping.getTable().getQuotedName();
+ if ( !isADependencyOf.containsKey( dependentTable ) ) {
+ isADependencyOf.put( dependentTable, new HashSet<FkSecondPass>() );
+ }
+ isADependencyOf.get( dependentTable ).add( sp );
+ }
+ else {
+ endOfQueueFkSecondPasses.add( sp );
+ }
+ }
+
+ // using the isADependencyOf map we order the FkSecondPass recursively instances into the right order for processing
+ List<FkSecondPass> orderedFkSecondPasses = new ArrayList( fkSecondPasses.size() );
+ for (String tableName : isADependencyOf.keySet()) {
+ buildRecursiveOrderedFkSecondPasses(orderedFkSecondPasses, isADependencyOf, tableName, tableName);
+ }
+
+ // process the ordered FkSecondPasses
+ for ( FkSecondPass sp : orderedFkSecondPasses ) {
+ sp.doSecondPass( classes );
+ }
+
+ processEndOfQueue(endOfQueueFkSecondPasses);
+ }
+
+ private void processEndOfQueue(List endOfQueueFkSecondPasses) {
+ /*
+ * If a second pass raises a recoverableException, queue it for next round
+ * stop of no pass has to be processed or if the number of pass to processes
+ * does not diminish between two rounds.
+ * If some failing pass remain, raise the original exception
+ */
+ boolean stopProcess = false;
+ RuntimeException originalException = null;
+ while ( ! stopProcess ) {
+ List failingSecondPasses = new ArrayList();
+ Iterator it = endOfQueueFkSecondPasses.listIterator();
+ while ( it.hasNext() ) {
+ final SecondPass pass = (SecondPass) it.next();
+ try {
+ pass.doSecondPass( classes );
+ }
+ catch (RecoverableException e) {
+ failingSecondPasses.add( pass );
+ if (originalException == null) originalException = (RuntimeException) e.getCause();
+ }
+ }
+ stopProcess = failingSecondPasses.size() == 0 || failingSecondPasses.size() == endOfQueueFkSecondPasses.size();
+ endOfQueueFkSecondPasses = failingSecondPasses;
+ }
+ if (endOfQueueFkSecondPasses.size() > 0) {
+ throw originalException;
+ }
+ }
+
+ /**
+ * @return Returns a list of all <code>secondPasses</code> instances which are a instance of
+ * <code>FkSecondPass</code>.
+ */
+ private List<FkSecondPass> getFKSecondPassesOnly() {
+ Iterator iter = secondPasses.iterator();
+ List<FkSecondPass> fkSecondPasses = new ArrayList<FkSecondPass>(secondPasses.size());
+ while ( iter.hasNext() ) {
+ SecondPass sp = (SecondPass) iter.next();
+ //do the second pass of fk before the others and remove them
+ if ( sp instanceof FkSecondPass ) {
+ fkSecondPasses.add( (FkSecondPass) sp );
+ iter.remove();
+ }
+ }
+ return fkSecondPasses;
+ }
+
+ /**
+ * Recursively builds a list of FkSecondPass instances ready to be processed in this order.
+ * Checking all dependencies recursively seems quite expensive, but the original code just relied
+ * on some sort of table name sorting which failed in certain circumstances.
+ *
+ * @param orderedFkSecondPasses The list containing the <code>FkSecondPass<code> instances ready
+ * for processing.
+ * @param isADependencyOf Our lookup data structure to determine dependencies between tables
+ * @param startTable Table name to start recursive algorithm.
+ * @param currentTable The current table name used to check for 'new' dependencies.
+ *
+ * @see ANN-722 ANN-730
+ */
+ private void buildRecursiveOrderedFkSecondPasses(
+ List orderedFkSecondPasses,
+ Map<String, Set<FkSecondPass>> isADependencyOf, String startTable, String currentTable) {
+
+ Set<FkSecondPass> dependencies = isADependencyOf.get(currentTable);
+
+ // bottom out
+ if (dependencies == null || dependencies.size() == 0) {
+ return;
+ }
+
+ for (FkSecondPass sp : dependencies) {
+ String dependentTable = sp.getValue().getTable().getQuotedName();
+ if (dependentTable.compareTo(startTable) == 0) {
+ StringBuilder sb = new StringBuilder(
+ "Foreign key circularity dependency involving the following tables: ");
+ throw new AnnotationException(sb.toString());
+ }
+ buildRecursiveOrderedFkSecondPasses(orderedFkSecondPasses, isADependencyOf, startTable, dependentTable);
+ if (!orderedFkSecondPasses.contains(sp)) {
+ orderedFkSecondPasses.add(0, sp);
+ }
+ }
+ }
+
+ private void processArtifactsOfType(String artifact) {
+ if ( "hbm".equalsIgnoreCase( artifact ) ) {
+ log.debug( "Process hbm files" );
+ for (Document document : hbmDocuments) {
+ super.add( document );
+ }
+ hbmDocuments.clear();
+ hbmEntities.clear();
+ }
+ else if ( "class".equalsIgnoreCase( artifact ) ) {
+ log.debug( "Process annotated classes" );
+ //bind classes in the correct order calculating some inheritance state
+ List<XClass> orderedClasses = orderAndFillHierarchy( annotatedClasses );
+ Map<XClass, InheritanceState> inheritanceStatePerClass = AnnotationBinder.buildInheritanceStates(
+ orderedClasses, reflectionManager
+ );
+ ExtendedMappings mappings = createExtendedMappings();
+ for (XClass clazz : orderedClasses) {
+ //todo use the same extended mapping
+ AnnotationBinder.bindClass( clazz, inheritanceStatePerClass, mappings );
+ }
+ annotatedClasses.clear();
+ annotatedClassEntities.clear();
+ }
+ else {
+ log.warn( "Unknown artifact: {}", artifact );
+ }
+ }
+
+ private void removeConflictedArtifact(String artifact) {
+ if ( "hbm".equalsIgnoreCase( artifact ) ) {
+ for (String entity : hbmEntities.keySet()) {
+ if ( annotatedClassEntities.containsKey( entity ) ) {
+ annotatedClasses.remove( annotatedClassEntities.get( entity ) );
+ annotatedClassEntities.remove( entity );
+ }
+ }
+ }
+ else if ( "class".equalsIgnoreCase( artifact ) ) {
+ for (String entity : annotatedClassEntities.keySet()) {
+ if ( hbmEntities.containsKey( entity ) ) {
+ hbmDocuments.remove( hbmEntities.get( entity ) );
+ hbmEntities.remove( entity );
+ }
+ }
+ }
+ }
+
+ private void buildUniqueKeyFromColumnNames(String[] columnNames, Table table, String keyName) {
+ UniqueKey uc;
+ int size = columnNames.length;
+ Column[] columns = new Column[size];
+ Set<Column> unbound = new HashSet<Column>();
+ Set<Column> unboundNoLogical = new HashSet<Column>();
+ ExtendedMappings mappings = createExtendedMappings();
+ for (int index = 0; index < size; index++) {
+ String columnName;
+ try {
+ columnName = mappings.getPhysicalColumnName( columnNames[index], table );
+ columns[index] = new Column( columnName );
+ unbound.add( columns[index] );
+ //column equals and hashcode is based on column name
+ }
+ catch (MappingException e) {
+ unboundNoLogical.add( new Column( columnNames[index] ) );
+ }
+ }
+ for (Column column : columns) {
+ if ( table.containsColumn( column ) ) {
+ uc = table.getOrCreateUniqueKey( keyName );
+ uc.addColumn( table.getColumn( column ) );
+ unbound.remove( column );
+ }
+ }
+ if ( unbound.size() > 0 || unboundNoLogical.size() > 0 ) {
+ StringBuilder sb = new StringBuilder( "Unable to create unique key constraint (" );
+ for (String columnName : columnNames) {
+ sb.append( columnName ).append( ", " );
+ }
+ sb.setLength( sb.length() - 2 );
+ sb.append( ") on table " ).append( table.getName() ).append( ": " );
+ for (Column column : unbound) {
+ sb.append( column.getName() ).append( ", " );
+ }
+ for (Column column : unboundNoLogical) {
+ sb.append( column.getName() ).append( ", " );
+ }
+ sb.setLength( sb.length() - 2 );
+ sb.append( " not found" );
+ throw new AnnotationException( sb.toString() );
+ }
+ }
+
+ @Override
+ protected void parseMappingElement(Element subelement, String name) {
+ Attribute rsrc = subelement.attribute( "resource" );
+ Attribute file = subelement.attribute( "file" );
+ Attribute jar = subelement.attribute( "jar" );
+ Attribute pckg = subelement.attribute( "package" );
+ Attribute clazz = subelement.attribute( "class" );
+ if ( rsrc != null ) {
+ log.debug( "{} <- {}", name, rsrc );
+ addResource( rsrc.getValue() );
+ }
+ else if ( jar != null ) {
+ log.debug( "{} <- {}", name, jar );
+ addJar( new File( jar.getValue() ) );
+ }
+ else if ( file != null ) {
+ log.debug( "{} <- {}", name, file );
+ addFile( file.getValue() );
+ }
+ else if ( pckg != null ) {
+ log.debug( "{} <- {}", name, pckg );
+ addPackage( pckg.getValue() );
+ }
+ else if ( clazz != null ) {
+ log.debug( "{} <- {}", name, clazz );
+ Class loadedClass;
+ try {
+ loadedClass = ReflectHelper.classForName( clazz.getValue() );
+ }
+ catch (ClassNotFoundException cnf) {
+ throw new MappingException(
+ "Unable to load class declared as <mapping class=\"" + clazz.getValue() + "\"/> in the configuration:",
+ cnf
+ );
+ }
+ catch (NoClassDefFoundError ncdf) {
+ throw new MappingException(
+ "Unable to load class declared as <mapping class=\"" + clazz.getValue() + "\"/> in the configuration:",
+ ncdf
+ );
+ }
+
+ addAnnotatedClass( loadedClass );
+ }
+ else {
+ throw new MappingException( "<mapping> element in configuration specifies no attributes" );
+ }
+ }
+
+ @Override
+ protected void add(org.dom4j.Document doc) throws MappingException {
+ boolean ejb3Xml = "entity-mappings".equals( doc.getRootElement().getName() );
+ if ( inSecondPass ) {
+ //if in second pass bypass the queueing, getExtendedQueue reuse this method
+ if ( !ejb3Xml ) super.add( doc );
+ }
+ else {
+ if ( !ejb3Xml ) {
+ final Element hmNode = doc.getRootElement();
+ Attribute packNode = hmNode.attribute( "package" );
+ String defaultPackage = packNode != null
+ ? packNode.getValue()
+ : "";
+ Set<String> entityNames = new HashSet<String>();
+ findClassNames( defaultPackage, hmNode, entityNames );
+ for (String entity : entityNames) {
+ hbmEntities.put( entity, doc );
+ }
+ hbmDocuments.add( doc );
+ }
+ else {
+ List<String> classnames = ( (EJB3ReflectionManager) reflectionManager ).getXMLContext().addDocument( doc );
+ for (String classname : classnames) {
+ try {
+ annotatedClasses.add( reflectionManager.classForName( classname, this.getClass() ) );
+ }
+ catch (ClassNotFoundException e) {
+ throw new AnnotationException( "Unable to load class defined in XML: " + classname, e );
+ }
+ }
+ }
+ }
+ }
+
+ private static void findClassNames(
+ String defaultPackage, final Element startNode,
+ final java.util.Set names
+ ) {
+ // if we have some extends we need to check if those classes possibly could be inside the
+ // same hbm.xml file...
+ Iterator[] classes = new Iterator[4];
+ classes[0] = startNode.elementIterator( "class" );
+ classes[1] = startNode.elementIterator( "subclass" );
+ classes[2] = startNode.elementIterator( "joined-subclass" );
+ classes[3] = startNode.elementIterator( "union-subclass" );
+
+ Iterator classIterator = new JoinedIterator( classes );
+ while ( classIterator.hasNext() ) {
+ Element element = (Element) classIterator.next();
+ String entityName = element.attributeValue( "entity-name" );
+ if ( entityName == null ) entityName = getClassName( element.attribute( "name" ), defaultPackage );
+ names.add( entityName );
+ findClassNames( defaultPackage, element, names );
+ }
+ }
+
+ private static String getClassName(Attribute name, String defaultPackage) {
+ if ( name == null ) return null;
+ String unqualifiedName = name.getValue();
+ if ( unqualifiedName == null ) return null;
+ if ( unqualifiedName.indexOf( '.' ) < 0 && defaultPackage != null ) {
+ return defaultPackage + '.' + unqualifiedName;
+ }
+ return unqualifiedName;
+ }
+
+ public void setPrecedence(String precedence) {
+ this.precedence = precedence;
+ }
+
+ private static class CacheHolder {
+ public CacheHolder(String role, String usage, String region, boolean isClass, boolean cacheLazy) {
+ this.role = role;
+ this.usage = usage;
+ this.region = region;
+ this.isClass = isClass;
+ this.cacheLazy = cacheLazy;
+ }
+
+ public String role;
+ public String usage;
+ public String region;
+ public boolean isClass;
+ public boolean cacheLazy;
+ }
+
+ @Override
+ public AnnotationConfiguration addInputStream(InputStream xmlInputStream) throws MappingException {
+ try {
+ List errors = new ArrayList();
+ SAXReader saxReader = xmlHelper.createSAXReader( "XML InputStream", errors, getEntityResolver() );
+ try {
+ saxReader.setFeature( "http://apache.org/xml/features/validation/schema", true );
+ //saxReader.setFeature( "http://apache.org/xml/features/validation/dynamic", true );
+ //set the default schema locators
+ saxReader.setProperty(
+ "http://apache.org/xml/properties/schema/external-schemaLocation",
+ "http://java.sun.com/xml/ns/persistence/orm orm_1_0.xsd"
+ );
+ }
+ catch (SAXException e) {
+ saxReader.setValidation( false );
+ }
+ org.dom4j.Document doc = saxReader
+ .read( new InputSource( xmlInputStream ) );
+
+ if ( errors.size() != 0 ) {
+ throw new MappingException( "invalid mapping", (Throwable) errors.get( 0 ) );
+ }
+ add( doc );
+ return this;
+ }
+ catch (DocumentException e) {
+ throw new MappingException( "Could not parse mapping document in input stream", e );
+ }
+ finally {
+ try {
+ xmlInputStream.close();
+ }
+ catch (IOException ioe) {
+ log.warn( "Could not close input stream", ioe );
+ }
+ }
+ }
+
+ public SessionFactory buildSessionFactory() throws HibernateException {
+ //add validator events if the jar is available
+ boolean enableValidatorListeners = !"false".equalsIgnoreCase( getProperty( "hibernate.validator.autoregister_listeners" ) );
+ Class validateEventListenerClass = null;
+ try {
+ validateEventListenerClass = ReflectHelper.classForName(
+ "org.hibernate.validator.event.ValidateEventListener",
+ AnnotationConfiguration.class );
+ }
+ catch (ClassNotFoundException e) {
+ //validator is not present
+ log.debug( "Validator not present in classpath, ignoring event listener registration" );
+ }
+ if ( enableValidatorListeners && validateEventListenerClass != null ) {
+ //TODO so much duplication
+ Object validateEventListener;
+ try {
+ validateEventListener = validateEventListenerClass.newInstance();
+ }
+ catch (Exception e) {
+ throw new AnnotationException( "Unable to load Validator event listener", e );
+ }
+ {
+ boolean present = false;
+ PreInsertEventListener[] listeners = getEventListeners().getPreInsertEventListeners();
+ if ( listeners != null ) {
+ for (Object eventListener : listeners) {
+ //not isAssignableFrom since the user could subclass
+ present = present || validateEventListenerClass == eventListener.getClass();
+ }
+ if ( !present ) {
+ int length = listeners.length + 1;
+ PreInsertEventListener[] newListeners = new PreInsertEventListener[length];
+ System.arraycopy( listeners, 0, newListeners, 0, length - 1 );
+ newListeners[length - 1] = (PreInsertEventListener) validateEventListener;
+ getEventListeners().setPreInsertEventListeners( newListeners );
+ }
+ }
+ else {
+ getEventListeners().setPreInsertEventListeners(
+ new PreInsertEventListener[] { (PreInsertEventListener) validateEventListener }
+ );
+ }
+ }
+
+ //update event listener
+ {
+ boolean present = false;
+ PreUpdateEventListener[] listeners = getEventListeners().getPreUpdateEventListeners();
+ if ( listeners != null ) {
+ for (Object eventListener : listeners) {
+ //not isAssignableFrom since the user could subclass
+ present = present || validateEventListenerClass == eventListener.getClass();
+ }
+ if ( !present ) {
+ int length = listeners.length + 1;
+ PreUpdateEventListener[] newListeners = new PreUpdateEventListener[length];
+ System.arraycopy( listeners, 0, newListeners, 0, length - 1 );
+ newListeners[length - 1] = (PreUpdateEventListener) validateEventListener;
+ getEventListeners().setPreUpdateEventListeners( newListeners );
+ }
+ }
+ else {
+ getEventListeners().setPreUpdateEventListeners(
+ new PreUpdateEventListener[] { (PreUpdateEventListener) validateEventListener }
+ );
+ }
+ }
+ }
+
+ enableHibernateSearch();
+
+ return super.buildSessionFactory();
+ }
+
+ /**
+ * Tries to automatically register Hibernate Search event listeners by locating the
+ * appropriate bootstrap class and calling the <code>enableHibernateSearch</code> method.
+ */
+ private void enableHibernateSearch() {
+ // load the bootstrap class
+ Class searchStartupClass;
+ try {
+ searchStartupClass = ReflectHelper.classForName(SEARCH_STARTUP_CLASS, AnnotationConfiguration.class);
+ } catch ( ClassNotFoundException e ) {
+ // TODO remove this together with SearchConfiguration after 3.1.0 release of Search
+ // try loading deprecated HibernateSearchEventListenerRegister
+ try {
+ searchStartupClass = ReflectHelper.classForName("org.hibernate.cfg.search.HibernateSearchEventListenerRegister", AnnotationConfiguration.class);
+ } catch ( ClassNotFoundException cnfe ) {
+ log.debug("Search not present in classpath, ignoring event listener registration.");
+ return;
+ }
+ }
+
+ // call the method for registering the listeners
+ try {
+ Object searchStartupInstance = searchStartupClass.newInstance();
+ Method enableSearchMethod = searchStartupClass.getDeclaredMethod(SEARCH_STARTUP_METHOD,
+ EventListeners.class, Properties.class);
+ enableSearchMethod.invoke(searchStartupInstance, getEventListeners(), getProperties());
+ } catch ( InstantiationException e ) {
+ log.debug("Unable to instantiate {}, ignoring event listener registration.", SEARCH_STARTUP_CLASS);
+ } catch ( IllegalAccessException e ) {
+ log.debug("Unable to instantiate {}, ignoring event listener registration.", SEARCH_STARTUP_CLASS);
+ } catch ( NoSuchMethodException e ) {
+ log.debug("Method enableHibernateSearch() not found in {}.", SEARCH_STARTUP_CLASS);
+ } catch ( InvocationTargetException e ) {
+ log.debug("Unable to execute {}, ignoring event listener registration.", SEARCH_STARTUP_METHOD);
+ }
+ }
+
+ @Override
+ public AnnotationConfiguration addFile(String xmlFile) throws MappingException {
+ super.addFile( xmlFile );
+ return this;
+ }
+
+ @Override
+ public AnnotationConfiguration addFile(File xmlFile) throws MappingException {
+ super.addFile( xmlFile );
+ return this;
+ }
+
+ @Override
+ public AnnotationConfiguration addCacheableFile(File xmlFile) throws MappingException {
+ super.addCacheableFile( xmlFile );
+ return this;
+ }
+
+ @Override
+ public AnnotationConfiguration addCacheableFile(String xmlFile) throws MappingException {
+ super.addCacheableFile( xmlFile );
+ return this;
+ }
+
+ @Override
+ public AnnotationConfiguration addXML(String xml) throws MappingException {
+ super.addXML( xml );
+ return this;
+ }
+
+ @Override
+ public AnnotationConfiguration addURL(URL url) throws MappingException {
+ super.addURL( url );
+ return this;
+ }
+
+ @Override
+ public AnnotationConfiguration addResource(String resourceName, ClassLoader classLoader) throws MappingException {
+ super.addResource( resourceName, classLoader );
+ return this;
+ }
+
+ @Override
+ public AnnotationConfiguration addDocument(org.w3c.dom.Document doc) throws MappingException {
+ super.addDocument( doc );
+ return this;
+ }
+
+ @Override
+ public AnnotationConfiguration addResource(String resourceName) throws MappingException {
+ super.addResource( resourceName );
+ return this;
+ }
+
+ @Override
+ public AnnotationConfiguration addClass(Class persistentClass) throws MappingException {
+ super.addClass( persistentClass );
+ return this;
+ }
+
+ @Override
+ public AnnotationConfiguration addJar(File jar) throws MappingException {
+ super.addJar( jar );
+ return this;
+ }
+
+ @Override
+ public AnnotationConfiguration addDirectory(File dir) throws MappingException {
+ super.addDirectory( dir );
+ return this;
+ }
+
+ @Override
+ public AnnotationConfiguration setInterceptor(Interceptor interceptor) {
+ super.setInterceptor( interceptor );
+ return this;
+ }
+
+ @Override
+ public AnnotationConfiguration setProperties(Properties properties) {
+ super.setProperties( properties );
+ return this;
+ }
+
+ @Override
+ public AnnotationConfiguration addProperties(Properties extraProperties) {
+ super.addProperties( extraProperties );
+ return this;
+ }
+
+ @Override
+ public AnnotationConfiguration mergeProperties(Properties properties) {
+ super.mergeProperties( properties );
+ return this;
+ }
+
+ @Override
+ public AnnotationConfiguration setProperty(String propertyName, String value) {
+ super.setProperty( propertyName, value );
+ return this;
+ }
+
+ @Override
+ public AnnotationConfiguration configure() throws HibernateException {
+ super.configure();
+ return this;
+ }
+
+ @Override
+ public AnnotationConfiguration configure(String resource) throws HibernateException {
+ super.configure( resource );
+ return this;
+ }
+
+ @Override
+ public AnnotationConfiguration configure(URL url) throws HibernateException {
+ super.configure( url );
+ return this;
+ }
+
+ @Override
+ public AnnotationConfiguration configure(File configFile) throws HibernateException {
+ super.configure( configFile );
+ return this;
+ }
+
+ @Override
+ protected AnnotationConfiguration doConfigure(InputStream stream, String resourceName) throws HibernateException {
+ super.doConfigure( stream, resourceName );
+ return this;
+ }
+
+ @Override
+ public AnnotationConfiguration configure(org.w3c.dom.Document document) throws HibernateException {
+ super.configure( document );
+ return this;
+ }
+
+ @Override
+ protected AnnotationConfiguration doConfigure(Document doc) throws HibernateException {
+ super.doConfigure( doc );
+ return this;
+ }
+
+ @Override
+ public AnnotationConfiguration setCacheConcurrencyStrategy(String clazz, String concurrencyStrategy) throws MappingException {
+ super.setCacheConcurrencyStrategy( clazz, concurrencyStrategy );
+ return this;
+ }
+
+ @Override
+ public AnnotationConfiguration setCollectionCacheConcurrencyStrategy(String collectionRole, String concurrencyStrategy) throws MappingException {
+ super.setCollectionCacheConcurrencyStrategy( collectionRole, concurrencyStrategy );
+ return this;
+ }
+
+ @Override
+ public AnnotationConfiguration setNamingStrategy(NamingStrategy namingStrategy) {
+ super.setNamingStrategy( namingStrategy );
+ return this;
+ }
+
+ //not a public API
+ public ReflectionManager getReflectionManager() {
+ return reflectionManager;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/BinderHelper.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/BinderHelper.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/BinderHelper.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,556 @@
+//$Id: BinderHelper.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.cfg;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.StringTokenizer;
+
+import org.hibernate.AnnotationException;
+import org.hibernate.AssertionFailure;
+import org.hibernate.MappingException;
+import org.hibernate.annotations.AnyMetaDef;
+import org.hibernate.annotations.AnyMetaDefs;
+import org.hibernate.annotations.MetaValue;
+import org.hibernate.annotations.common.reflection.XAnnotatedElement;
+import org.hibernate.annotations.common.reflection.XClass;
+import org.hibernate.annotations.common.reflection.XPackage;
+import org.hibernate.cfg.annotations.EntityBinder;
+import org.hibernate.cfg.annotations.Nullability;
+import org.hibernate.cfg.annotations.TableBinder;
+import org.hibernate.id.MultipleHiLoPerTableGenerator;
+import org.hibernate.id.PersistentIdentifierGenerator;
+import org.hibernate.mapping.Any;
+import org.hibernate.mapping.Collection;
+import org.hibernate.mapping.Column;
+import org.hibernate.mapping.Component;
+import org.hibernate.mapping.IdGenerator;
+import org.hibernate.mapping.Join;
+import org.hibernate.mapping.PersistentClass;
+import org.hibernate.mapping.Property;
+import org.hibernate.mapping.SimpleValue;
+import org.hibernate.mapping.Table;
+import org.hibernate.mapping.ToOne;
+import org.hibernate.mapping.Value;
+import org.hibernate.type.TypeFactory;
+import org.hibernate.util.StringHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class BinderHelper {
+
+ public static final String ANNOTATION_STRING_DEFAULT = "";
+ private static Logger log = LoggerFactory.getLogger( BinderHelper.class );
+
+ private BinderHelper() {
+ }
+
+ static {
+ Set<String> primitiveNames = new HashSet<String>();
+ primitiveNames.add( byte.class.getName() );
+ primitiveNames.add( short.class.getName() );
+ primitiveNames.add( int.class.getName() );
+ primitiveNames.add( long.class.getName() );
+ primitiveNames.add( float.class.getName() );
+ primitiveNames.add( double.class.getName() );
+ primitiveNames.add( char.class.getName() );
+ primitiveNames.add( boolean.class.getName() );
+ PRIMITIVE_NAMES = Collections.unmodifiableSet( primitiveNames );
+ }
+
+ public static final Set<String> PRIMITIVE_NAMES;
+
+ /**
+ * create a property copy reusing the same value
+ */
+ public static Property shallowCopy(Property property) {
+ Property clone = new Property();
+ clone.setCascade( property.getCascade() );
+ clone.setInsertable( property.isInsertable() );
+ clone.setLazy( property.isLazy() );
+ clone.setName( property.getName() );
+ clone.setNodeName( property.getNodeName() );
+ clone.setNaturalIdentifier( property.isNaturalIdentifier() );
+ clone.setOptimisticLocked( property.isOptimisticLocked() );
+ clone.setOptional( property.isOptional() );
+ clone.setPersistentClass( property.getPersistentClass() );
+ clone.setPropertyAccessorName( property.getPropertyAccessorName() );
+ clone.setSelectable( property.isSelectable() );
+ clone.setUpdateable( property.isUpdateable() );
+ clone.setValue( property.getValue() );
+ return clone;
+ }
+
+ public static void createSyntheticPropertyReference(
+ Ejb3JoinColumn[] columns,
+ PersistentClass ownerEntity,
+ PersistentClass associatedEntity,
+ Value value,
+ boolean inverse, ExtendedMappings mappings
+ ) {
+ //associated entity only used for more precise exception, yuk!
+ if ( columns[0].isImplicit() || StringHelper.isNotEmpty( columns[0].getMappedBy() ) ) return;
+ int fkEnum = Ejb3JoinColumn.checkReferencedColumnsType( columns, ownerEntity, mappings );
+ PersistentClass associatedClass = columns[0].getPropertyHolder() != null ?
+ columns[0].getPropertyHolder().getPersistentClass() :
+ null;
+ if ( Ejb3JoinColumn.NON_PK_REFERENCE == fkEnum ) {
+ /**
+ * Create a synthetic property to refer to including an
+ * embedded component value containing all the properties
+ * mapped to the referenced columns
+ * We need to shallow copy those properties to mark them
+ * as non insertable / non updatable
+ */
+ StringBuilder propertyNameBuffer = new StringBuilder( "_" );
+ propertyNameBuffer.append( associatedClass.getEntityName().replace( '.', '_' ) );
+ propertyNameBuffer.append( "_" ).append( columns[0].getPropertyName() );
+ String syntheticPropertyName = propertyNameBuffer.toString();
+ //find properties associated to a certain column
+ Object columnOwner = findColumnOwner( ownerEntity, columns[0].getReferencedColumn(), mappings );
+ List<Property> properties = findPropertiesByColumns( columnOwner, columns, mappings );
+ //create an embeddable component
+ Property synthProp = null;
+ if ( properties != null ) {
+ //todo how about properties.size() == 1, this should be much simpler
+ Component embeddedComp = columnOwner instanceof PersistentClass ?
+ new Component( (PersistentClass) columnOwner ) :
+ new Component( (Join) columnOwner );
+ embeddedComp.setEmbedded( true );
+ embeddedComp.setNodeName( syntheticPropertyName );
+ embeddedComp.setComponentClassName( embeddedComp.getOwner().getClassName() );
+ for (Property property : properties) {
+ Property clone = BinderHelper.shallowCopy( property );
+ clone.setInsertable( false );
+ clone.setUpdateable( false );
+ clone.setNaturalIdentifier( false );
+ embeddedComp.addProperty( clone );
+ }
+ synthProp = new Property();
+ synthProp.setName( syntheticPropertyName );
+ synthProp.setNodeName( syntheticPropertyName );
+ synthProp.setPersistentClass( ownerEntity );
+ synthProp.setUpdateable( false );
+ synthProp.setInsertable( false );
+ synthProp.setValue( embeddedComp );
+ synthProp.setPropertyAccessorName( "embedded" );
+ ownerEntity.addProperty( synthProp );
+ //make it unique
+ TableBinder.createUniqueConstraint( embeddedComp );
+ }
+ else {
+ //TODO use a ToOne type doing a second select
+ StringBuilder columnsList = new StringBuilder();
+ columnsList.append( "referencedColumnNames(" );
+ for (Ejb3JoinColumn column : columns) {
+ columnsList.append( column.getReferencedColumn() ).append( ", " );
+ }
+ columnsList.setLength( columnsList.length() - 2 );
+ columnsList.append( ") " );
+
+ if ( associatedEntity != null ) {
+ //overidden destination
+ columnsList.append( "of " )
+ .append( associatedEntity.getEntityName() )
+ .append( "." )
+ .append( columns[0].getPropertyName() )
+ .append( " " );
+ }
+ else {
+ if ( columns[0].getPropertyHolder() != null ) {
+ columnsList.append( "of " )
+ .append( columns[0].getPropertyHolder().getEntityName() )
+ .append( "." )
+ .append( columns[0].getPropertyName() )
+ .append( " " );
+ }
+ }
+ columnsList.append( "referencing " )
+ .append( ownerEntity.getEntityName() )
+ .append( " not mapped to a single property" );
+ throw new AnnotationException( columnsList.toString() );
+ }
+
+ /**
+ * creating the property ref to the new synthetic property
+ */
+ if ( value instanceof ToOne ) {
+ ( (ToOne) value ).setReferencedPropertyName( syntheticPropertyName );
+ mappings.addUniquePropertyReference( ownerEntity.getEntityName(), syntheticPropertyName );
+ }
+ else if ( value instanceof Collection ) {
+ ( (Collection) value ).setReferencedPropertyName( syntheticPropertyName );
+ //not unique because we could create a mtm wo association table
+ mappings.addPropertyReference( ownerEntity.getEntityName(), syntheticPropertyName );
+ }
+ else {
+ throw new AssertionFailure(
+ "Do a property ref on an unexpected Value type: "
+ + value.getClass().getName()
+ );
+ }
+ mappings.addPropertyReferencedAssociation(
+ ( inverse ? "inverse__" : "" ) + associatedClass.getEntityName(),
+ columns[0].getPropertyName(),
+ syntheticPropertyName
+ );
+ }
+ }
+
+
+ private static List<Property> findPropertiesByColumns(
+ Object columnOwner, Ejb3JoinColumn[] columns,
+ ExtendedMappings mappings
+ ) {
+ Map<Column, Set<Property>> columnsToProperty = new HashMap<Column, Set<Property>>();
+ List<Column> orderedColumns = new ArrayList<Column>( columns.length );
+ Table referencedTable = null;
+ if ( columnOwner instanceof PersistentClass ) {
+ referencedTable = ( (PersistentClass) columnOwner ).getTable();
+ }
+ else if ( columnOwner instanceof Join ) {
+ referencedTable = ( (Join) columnOwner ).getTable();
+ }
+ else {
+ throw new AssertionFailure(
+ columnOwner == null ?
+ "columnOwner is null" :
+ "columnOwner neither PersistentClass nor Join: " + columnOwner.getClass()
+ );
+ }
+ //build the list of column names
+ for (Ejb3JoinColumn column1 : columns) {
+ Column column = new Column(
+ mappings.getPhysicalColumnName( column1.getReferencedColumn(), referencedTable )
+ );
+ orderedColumns.add( column );
+ columnsToProperty.put( column, new HashSet<Property>() );
+ }
+ boolean isPersistentClass = columnOwner instanceof PersistentClass;
+ Iterator it = isPersistentClass ?
+ ( (PersistentClass) columnOwner ).getPropertyIterator() :
+ ( (Join) columnOwner ).getPropertyIterator();
+ while ( it.hasNext() ) {
+ matchColumnsByProperty( (Property) it.next(), columnsToProperty );
+ }
+ if ( isPersistentClass ) {
+ matchColumnsByProperty( ( (PersistentClass) columnOwner ).getIdentifierProperty(), columnsToProperty );
+ }
+
+ //first naive implementation
+ //only check 1 columns properties
+ //TODO make it smarter by checking correctly ordered multi column properties
+ List<Property> orderedProperties = new ArrayList<Property>();
+ for (Column column : orderedColumns) {
+ boolean found = false;
+ for (Property property : columnsToProperty.get( column )) {
+ if ( property.getColumnSpan() == 1 ) {
+ orderedProperties.add( property );
+ found = true;
+ break;
+ }
+ }
+ if ( !found ) return null; //have to find it the hard way
+ }
+ return orderedProperties;
+ }
+
+ private static void matchColumnsByProperty(Property property, Map<Column, Set<Property>> columnsToProperty) {
+ if ( property == null ) return;
+ if ( "noop".equals( property.getPropertyAccessorName() )
+ || "embedded".equals( property.getPropertyAccessorName() ) ) {
+ return;
+ }
+// FIXME cannot use subproperties becasue the caller needs top level properties
+// if ( property.isComposite() ) {
+// Iterator subProperties = ( (Component) property.getValue() ).getPropertyIterator();
+// while ( subProperties.hasNext() ) {
+// matchColumnsByProperty( (Property) subProperties.next(), columnsToProperty );
+// }
+// }
+ else {
+ Iterator columnIt = property.getColumnIterator();
+ while ( columnIt.hasNext() ) {
+ Object column = columnIt.next(); //can be a Formula so we don't cast
+ //noinspection SuspiciousMethodCalls
+ if ( columnsToProperty.containsKey( column ) ) {
+ columnsToProperty.get( column ).add( property );
+ }
+ }
+ }
+ }
+
+ /**
+ * Retrieve the property by path in a recursive way, including IndetifierProperty in the loop
+ * If propertyName is null or empty, the IdentifierProperty is returned
+ */
+ public static Property findPropertyByName(PersistentClass associatedClass, String propertyName) {
+ Property property = null;
+ Property idProperty = associatedClass.getIdentifierProperty();
+ String idName = idProperty != null ? idProperty.getName() : null;
+ try {
+ if ( propertyName == null
+ || propertyName.length() == 0
+ || propertyName.equals( idName ) ) {
+ //default to id
+ property = idProperty;
+ }
+ else {
+ if ( propertyName.indexOf( idName + "." ) == 0 ) {
+ property = idProperty;
+ propertyName = propertyName.substring( idName.length() + 1 );
+ }
+ StringTokenizer st = new StringTokenizer( propertyName, ".", false );
+ while ( st.hasMoreElements() ) {
+ String element = (String) st.nextElement();
+ if ( property == null ) {
+ property = associatedClass.getProperty( element );
+ }
+ else {
+ if ( !property.isComposite() ) return null;
+ property = ( (Component) property.getValue() ).getProperty( element );
+ }
+ }
+ }
+ }
+ catch (MappingException e) {
+ try {
+ //if we do not find it try to check the identifier mapper
+ if ( associatedClass.getIdentifierMapper() == null ) return null;
+ StringTokenizer st = new StringTokenizer( propertyName, ".", false );
+ while ( st.hasMoreElements() ) {
+ String element = (String) st.nextElement();
+ if ( property == null ) {
+ property = associatedClass.getIdentifierMapper().getProperty( element );
+ }
+ else {
+ if ( !property.isComposite() ) return null;
+ property = ( (Component) property.getValue() ).getProperty( element );
+ }
+ }
+ }
+ catch (MappingException ee) {
+ return null;
+ }
+ }
+ return property;
+ }
+
+ public static String getRelativePath(PropertyHolder propertyHolder, String propertyName) {
+ if ( propertyHolder == null ) return propertyName;
+ String path = propertyHolder.getPath();
+ String entityName = propertyHolder.getPersistentClass().getEntityName();
+ if ( path.length() == entityName.length() ) {
+ return propertyName;
+ }
+ else {
+ return StringHelper.qualify( path.substring( entityName.length() + 1 ), propertyName );
+ }
+ }
+
+ /**
+ * Find the column owner (ie PersistentClass or Join) of columnName.
+ * If columnName is null or empty, persistentClass is returned
+ */
+ public static Object findColumnOwner(
+ PersistentClass persistentClass, String columnName, ExtendedMappings mappings
+ ) {
+ if ( StringHelper.isEmpty( columnName ) ) {
+ return persistentClass; //shortcut for implicit referenced column names
+ }
+ PersistentClass current = persistentClass;
+ Object result = null;
+ boolean found = false;
+ do {
+ result = current;
+ Table currentTable = current.getTable();
+ try {
+ mappings.getPhysicalColumnName( columnName, currentTable );
+ found = true;
+ }
+ catch (MappingException me) {
+ //swallow it
+ }
+ Iterator joins = current.getJoinIterator();
+ while ( !found && joins.hasNext() ) {
+ result = joins.next();
+ currentTable = ( (Join) result ).getTable();
+ try {
+ mappings.getPhysicalColumnName( columnName, currentTable );
+ found = true;
+ }
+ catch (MappingException me) {
+ //swallow it
+ }
+ }
+ current = current.getSuperclass();
+ }
+ while ( !found && current != null );
+ return found ? result : null;
+ }
+
+ /**
+ * apply an id generator to a SimpleValue
+ */
+ public static void makeIdGenerator(
+ SimpleValue id, String generatorType, String generatorName, ExtendedMappings mappings,
+ Map<String, IdGenerator> localGenerators
+ ) {
+ Table table = id.getTable();
+ table.setIdentifierValue( id );
+ //generator settings
+ id.setIdentifierGeneratorStrategy( generatorType );
+ Properties params = new Properties();
+ //always settable
+ params.setProperty(
+ PersistentIdentifierGenerator.TABLE, table.getName()
+ );
+
+ if ( id.getColumnSpan() == 1 ) {
+ params.setProperty(
+ PersistentIdentifierGenerator.PK,
+ ( (org.hibernate.mapping.Column) id.getColumnIterator().next() ).getName()
+ );
+ }
+ if ( !isDefault( generatorName ) ) {
+ //we have a named generator
+ IdGenerator gen = mappings.getGenerator( generatorName, localGenerators );
+ if ( gen == null ) {
+ throw new AnnotationException( "Unknown Id.generator: " + generatorName );
+ }
+ //This is quite vague in the spec but a generator could override the generate choice
+ String identifierGeneratorStrategy = gen.getIdentifierGeneratorStrategy();
+ //yuk! this is a hack not to override 'AUTO' even if generator is set
+ final boolean avoidOverriding =
+ identifierGeneratorStrategy.equals( "identity" )
+ || identifierGeneratorStrategy.equals( "seqhilo" )
+ || identifierGeneratorStrategy.equals( MultipleHiLoPerTableGenerator.class.getName() );
+ if ( generatorType == null || !avoidOverriding ) {
+ id.setIdentifierGeneratorStrategy( identifierGeneratorStrategy );
+ }
+ //checkIfMatchingGenerator(gen, generatorType, generatorName);
+ Iterator genParams = gen.getParams().entrySet().iterator();
+ while ( genParams.hasNext() ) {
+ Map.Entry elt = (Map.Entry) genParams.next();
+ params.setProperty( (String) elt.getKey(), (String) elt.getValue() );
+ }
+ }
+ if ( "assigned".equals( generatorType ) ) id.setNullValue( "undefined" );
+ id.setIdentifierGeneratorProperties( params );
+ }
+
+ public static boolean isDefault(String annotationString) {
+ return annotationString != null && annotationString.length() == 0;
+ //equivalent to (but faster) ANNOTATION_STRING_DEFAULT.equals( annotationString );
+ }
+
+ public static Any buildAnyValue(String anyMetaDefName, Ejb3JoinColumn[] columns, javax.persistence.Column metaColumn, PropertyData inferredData,
+ boolean cascadeOnDelete, Nullability nullability, PropertyHolder propertyHolder,
+ EntityBinder entityBinder, boolean optional, ExtendedMappings mappings) {
+ //All FK columns should be in the same table
+ Any value = new Any( columns[0].getTable() );
+ AnyMetaDef metaAnnDef = inferredData.getProperty().getAnnotation( AnyMetaDef.class );
+
+ if ( metaAnnDef != null ) {
+ //local has precedence over general and can be mapped for future reference if named
+ bindAnyMetaDefs( inferredData.getProperty(), mappings );
+ }
+ else {
+ metaAnnDef = mappings.getAnyMetaDef( anyMetaDefName );
+ }
+ if ( metaAnnDef != null ) {
+ value.setIdentifierType( metaAnnDef.idType() );
+ value.setMetaType( metaAnnDef.metaType() );
+
+ HashMap values = new HashMap();
+ org.hibernate.type.Type metaType = TypeFactory.heuristicType( value.getMetaType() );
+ for (MetaValue metaValue : metaAnnDef.metaValues()) {
+ try {
+ Object discrim = ( (org.hibernate.type.DiscriminatorType) metaType ).stringToObject( metaValue
+ .value() );
+ String entityName = metaValue.targetEntity().getName();
+ values.put( discrim, entityName );
+ }
+ catch (ClassCastException cce) {
+ throw new MappingException( "metaType was not a DiscriminatorType: "
+ + metaType.getName() );
+ }
+ catch (Exception e) {
+ throw new MappingException( "could not interpret metaValue", e );
+ }
+ }
+ if ( !values.isEmpty() ) value.setMetaValues( values );
+ }
+ else {
+ throw new AnnotationException( "Unable to find @AnyMetaDef for an @(ManyTo)Any mapping: "
+ + StringHelper.qualify( propertyHolder.getPath(), inferredData.getPropertyName() ) );
+ }
+
+ value.setCascadeDeleteEnabled( cascadeOnDelete );
+ if ( !optional ) {
+ for (Ejb3JoinColumn column : columns) {
+ column.setNullable( false );
+ }
+ }
+
+ Ejb3Column[] metaColumns = Ejb3Column.buildColumnFromAnnotation( new javax.persistence.Column[] { metaColumn }, null,
+ nullability, propertyHolder, inferredData, entityBinder.getSecondaryTables(), mappings );
+ //set metaColumn to the right table
+ for (Ejb3Column column : metaColumns) {
+ column.setTable( value.getTable() );
+ }
+ //meta column
+ for (Ejb3Column column : metaColumns) {
+ column.linkWithValue( value );
+ }
+
+ //id columns
+ final String propertyName = inferredData.getPropertyName();
+ Ejb3Column.checkPropertyConsistency( columns, propertyHolder.getEntityName() + propertyName );
+ for (Ejb3JoinColumn column : columns) {
+ column.linkWithValue( value );
+ }
+ return value;
+ }
+
+ public static void bindAnyMetaDefs(XAnnotatedElement annotatedElement, ExtendedMappings mappings) {
+ AnyMetaDef defAnn = annotatedElement.getAnnotation( AnyMetaDef.class );
+ AnyMetaDefs defsAnn = annotatedElement.getAnnotation( AnyMetaDefs.class );
+ boolean mustHaveName = XClass.class.isAssignableFrom( annotatedElement.getClass() )
+ || XPackage.class.isAssignableFrom( annotatedElement.getClass() );
+ if ( defAnn != null ) {
+ checkAnyMetaDefValidity( mustHaveName, defAnn, annotatedElement );
+ bindAnyMetaDef( defAnn, mappings );
+ }
+ if ( defsAnn != null ) {
+ for (AnyMetaDef def : defsAnn.value()) {
+ checkAnyMetaDefValidity( mustHaveName, def, annotatedElement );
+ bindAnyMetaDef( def, mappings );
+ }
+ }
+ }
+
+ private static void checkAnyMetaDefValidity(boolean mustHaveName, AnyMetaDef defAnn, XAnnotatedElement annotatedElement) {
+ if ( mustHaveName && isDefault( defAnn.name() ) ) {
+ String name = XClass.class.isAssignableFrom( annotatedElement.getClass() ) ?
+ ( (XClass) annotatedElement ).getName() :
+ ( (XPackage) annotatedElement ).getName();
+ throw new AnnotationException( "@AnyMetaDef.name cannot be null on an entity or a package: " + name );
+ }
+ }
+
+ private static void bindAnyMetaDef(AnyMetaDef defAnn, ExtendedMappings mappings) {
+ if ( isDefault( defAnn.name() ) ) return; //don't map not named definitions
+ log.info( "Binding Any Meta definition: {}", defAnn.name() );
+ mappings.addAnyMetaDef( defAnn );
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/ClassPropertyHolder.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/ClassPropertyHolder.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/ClassPropertyHolder.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,120 @@
+//$Id: ClassPropertyHolder.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.cfg;
+
+import java.util.HashMap;
+import java.util.Map;
+import javax.persistence.JoinTable;
+
+import org.hibernate.annotations.common.reflection.XClass;
+import org.hibernate.cfg.annotations.EntityBinder;
+import org.hibernate.mapping.Component;
+import org.hibernate.mapping.Join;
+import org.hibernate.mapping.KeyValue;
+import org.hibernate.mapping.PersistentClass;
+import org.hibernate.mapping.Property;
+import org.hibernate.mapping.Table;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class ClassPropertyHolder extends AbstractPropertyHolder {
+ private PersistentClass persistentClass;
+ private Map<String, Join> joins;
+ private transient Map<String, Join> joinsPerRealTableName;
+ private EntityBinder entityBinder;
+
+ public ClassPropertyHolder(
+ PersistentClass persistentClass, XClass clazzToProcess, Map<String, Join> joins, ExtendedMappings mappings
+ ) {
+ super( persistentClass.getEntityName(), null, clazzToProcess, mappings );
+ this.persistentClass = persistentClass;
+ this.joins = joins;
+ }
+
+ public ClassPropertyHolder(
+ PersistentClass persistentClass, XClass clazzToProcess, EntityBinder entityBinder,
+ ExtendedMappings mappings
+ ) {
+ this( persistentClass, clazzToProcess, entityBinder.getSecondaryTables(), mappings );
+ this.entityBinder = entityBinder;
+ }
+
+ public String getEntityName() {
+ return persistentClass.getEntityName();
+ }
+
+ public void addProperty(Property prop, Ejb3Column[] columns) {
+ //Ejb3Column.checkPropertyConsistency( ); //already called earlier
+ if ( columns[0].isSecondary() ) {
+ //TODO move the getJoin() code here?
+ columns[0].getJoin().addProperty( prop );
+ }
+ else {
+ addProperty( prop );
+ }
+ }
+
+ public Join addJoin(JoinTable joinTableAnn, boolean noDelayInPkColumnCreation) {
+ Join join = entityBinder.addJoin( joinTableAnn, this, noDelayInPkColumnCreation );
+ this.joins = entityBinder.getSecondaryTables();
+ return join;
+ }
+
+ public void addProperty(Property prop) {
+ if ( prop.getValue() instanceof Component ) {
+ //TODO handle quote and non quote table comparison
+ String tableName = prop.getValue().getTable().getName();
+ if ( getJoinsPerRealTableName().containsKey( tableName ) ) {
+ getJoinsPerRealTableName().get( tableName ).addProperty( prop );
+ }
+ else {
+ persistentClass.addProperty( prop );
+ }
+ }
+ else {
+ persistentClass.addProperty( prop );
+ }
+ }
+
+ /**
+ * Needed for proper compliance with naming strategy, the property table
+ * can be overriden if the properties are part of secondary tables
+ */
+ private Map<String, Join> getJoinsPerRealTableName() {
+ if ( joinsPerRealTableName == null ) {
+ joinsPerRealTableName = new HashMap<String, Join>( joins.size() );
+ for (Join join : joins.values()) {
+ joinsPerRealTableName.put( join.getTable().getName(), join );
+ }
+ }
+ return joinsPerRealTableName;
+ }
+
+ public String getClassName() {
+ return persistentClass.getClassName();
+ }
+
+ public String getEntityOwnerClassName() {
+ return getClassName();
+ }
+
+ public Table getTable() {
+ return persistentClass.getTable();
+ }
+
+ public boolean isComponent() {
+ return false;
+ }
+
+ public boolean isEntity() {
+ return true;
+ }
+
+ public PersistentClass getPersistentClass() {
+ return persistentClass;
+ }
+
+ public KeyValue getIdentifier() {
+ return persistentClass.getIdentifier();
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/CollectionPropertyHolder.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/CollectionPropertyHolder.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/CollectionPropertyHolder.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,75 @@
+//$Id: CollectionPropertyHolder.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.cfg;
+
+import javax.persistence.JoinTable;
+
+import org.hibernate.AssertionFailure;
+import org.hibernate.annotations.common.reflection.XClass;
+import org.hibernate.annotations.common.reflection.XProperty;
+import org.hibernate.mapping.Collection;
+import org.hibernate.mapping.Join;
+import org.hibernate.mapping.KeyValue;
+import org.hibernate.mapping.PersistentClass;
+import org.hibernate.mapping.Property;
+import org.hibernate.mapping.Table;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class CollectionPropertyHolder extends AbstractPropertyHolder {
+ Collection collection;
+
+ public CollectionPropertyHolder(
+ Collection collection, String path, XClass clazzToProcess, XProperty property,
+ PropertyHolder parentPropertyHolder, ExtendedMappings mappings
+ ) {
+ super( path, parentPropertyHolder, clazzToProcess, mappings );
+ this.collection = collection;
+ setCurrentProperty( property );
+ }
+
+ public String getClassName() {
+ throw new AssertionFailure( "Collection property holder does not have a class name" );
+ }
+
+ public String getEntityOwnerClassName() {
+ return null;
+ }
+
+ public Table getTable() {
+ return collection.getCollectionTable();
+ }
+
+ public void addProperty(Property prop) {
+ throw new AssertionFailure( "Cannot add property to a collection" );
+ }
+
+ public KeyValue getIdentifier() {
+ throw new AssertionFailure( "Identifier collection not yet managed" );
+ }
+
+ public PersistentClass getPersistentClass() {
+ return collection.getOwner();
+ }
+
+ public boolean isComponent() {
+ return false;
+ }
+
+ public boolean isEntity() {
+ return false;
+ }
+
+ public String getEntityName() {
+ return collection.getOwner().getEntityName();
+ }
+
+ public void addProperty(Property prop, Ejb3Column[] columns) {
+ //Ejb3Column.checkPropertyConsistency( ); //already called earlier
+ throw new AssertionFailure( "addProperty to a join table of a collection: does it make sense?" );
+ }
+
+ public Join addJoin(JoinTable joinTableAnn, boolean noDelayInPkColumnCreation) {
+ throw new AssertionFailure( "Add a <join> in a second pass" );
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/ComponentPropertyHolder.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/ComponentPropertyHolder.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/ComponentPropertyHolder.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,136 @@
+//$Id: ComponentPropertyHolder.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.cfg;
+
+import javax.persistence.Column;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinTable;
+
+import org.hibernate.AnnotationException;
+import org.hibernate.mapping.Component;
+import org.hibernate.mapping.Join;
+import org.hibernate.mapping.KeyValue;
+import org.hibernate.mapping.PersistentClass;
+import org.hibernate.mapping.Property;
+import org.hibernate.mapping.Table;
+
+/**
+ * Component implementation of property holder
+ *
+ * @author Emmanuel Bernard
+ */
+public class ComponentPropertyHolder extends AbstractPropertyHolder {
+ //TODO introduce a overrideTable() method for columns held by sec table rather than the hack
+ // joinsPerRealTableName in ClassPropertyHolder
+ private Component component;
+
+ public String getEntityName() {
+ return component.getComponentClassName();
+ }
+
+ public void addProperty(Property prop, Ejb3Column[] columns) {
+ //Ejb3Column.checkPropertyConsistency( ); //already called earlier
+ /*
+ * Check table matches between the component and the columns
+ * if not, change the component table if no properties are set
+ * if a property is set already the core cannot support that
+ */
+ Table table = columns[0].getTable();
+ if ( !table.equals( component.getTable() ) ) {
+ if ( component.getPropertySpan() == 0 ) {
+ component.setTable( table );
+ }
+ else {
+ throw new AnnotationException(
+ "A component cannot hold properties split into 2 different tables: "
+ + this.getPath()
+ );
+ }
+ }
+ addProperty( prop );
+ }
+
+ public Join addJoin(JoinTable joinTableAnn, boolean noDelayInPkColumnCreation) {
+ return parent.addJoin( joinTableAnn, noDelayInPkColumnCreation );
+
+ }
+
+ public ComponentPropertyHolder(
+ Component component, String path, PropertyData inferredData, PropertyHolder parent,
+ ExtendedMappings mappings
+ ) {
+ super( path, parent, inferredData.getPropertyClass(), mappings );
+ setCurrentProperty( inferredData.getProperty() );
+ this.component = component;
+ }
+
+ public String getClassName() {
+ return component.getComponentClassName();
+ }
+
+ public String getEntityOwnerClassName() {
+ return component.getOwner().getClassName();
+ }
+
+ public Table getTable() {
+ return component.getTable();
+ }
+
+ public void addProperty(Property prop) {
+ component.addProperty( prop );
+ }
+
+ public KeyValue getIdentifier() {
+ return component.getOwner().getIdentifier();
+ }
+
+ public PersistentClass getPersistentClass() {
+ return component.getOwner();
+ }
+
+ public boolean isComponent() {
+ return true;
+ }
+
+ public boolean isEntity() {
+ return false;
+ }
+
+ public void setParentProperty(String parentProperty) {
+ component.setParentProperty( parentProperty );
+ }
+
+ @Override
+ public Column[] getOverriddenColumn(String propertyName) {
+ //FIXME this is yukky
+ Column[] result = super.getOverriddenColumn( propertyName );
+ if ( result == null ) {
+ String userPropertyName = extractUserPropertyName( "id", propertyName );
+ if ( userPropertyName != null ) result = super.getOverriddenColumn( userPropertyName );
+ }
+ if ( result == null ) {
+ String userPropertyName = extractUserPropertyName( "_identifierMapper", propertyName );
+ if ( userPropertyName != null ) result = super.getOverriddenColumn( userPropertyName );
+ }
+ return result;
+ }
+
+ private String extractUserPropertyName(String redundantString, String propertyName) {
+ String result = null;
+ String className = component.getOwner().getClassName();
+ if ( propertyName.startsWith( className )
+ && propertyName.length() > className.length() + 2 + redundantString.length() // .id.
+ && propertyName.substring(
+ className.length() + 1, className.length() + 1 + redundantString.length()
+ ).equals( redundantString )
+ ) {
+ //remove id we might be in a @IdCLass case
+ result = className + propertyName.substring( className.length() + 1 + redundantString.length() );
+ }
+ return result;
+ }
+
+ @Override
+ public JoinColumn[] getOverriddenJoinColumn(String propertyName) {
+ return super.getOverriddenJoinColumn( propertyName );
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/CreateKeySecondPass.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/CreateKeySecondPass.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/CreateKeySecondPass.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,37 @@
+//$Id: CreateKeySecondPass.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.cfg;
+
+import java.util.Map;
+
+import org.hibernate.MappingException;
+import org.hibernate.mapping.JoinedSubclass;
+import org.hibernate.mapping.RootClass;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class CreateKeySecondPass implements SecondPass {
+ private RootClass rootClass;
+ private JoinedSubclass joinedSubClass;
+
+ public CreateKeySecondPass(RootClass rootClass) {
+ this.rootClass = rootClass;
+ }
+
+ public CreateKeySecondPass(JoinedSubclass joinedSubClass) {
+ this.joinedSubClass = joinedSubClass;
+ }
+
+ public void doSecondPass(Map persistentClasses) throws MappingException {
+ if ( rootClass != null ) {
+ rootClass.createPrimaryKey();
+ }
+ else if ( joinedSubClass != null ) {
+ joinedSubClass.createPrimaryKey();
+ joinedSubClass.createForeignKey();
+ }
+ else {
+ throw new AssertionError( "rootClass and joinedSubClass are null" );
+ }
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/DefaultComponentSafeNamingStrategy.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/DefaultComponentSafeNamingStrategy.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/DefaultComponentSafeNamingStrategy.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,77 @@
+//$Id: DefaultComponentSafeNamingStrategy.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.cfg;
+
+import org.hibernate.AssertionFailure;
+import org.hibernate.util.StringHelper;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class DefaultComponentSafeNamingStrategy extends EJB3NamingStrategy {
+ public static final NamingStrategy INSTANCE = new DefaultComponentSafeNamingStrategy();
+
+ protected static String addUnderscores(String name) {
+ return name.replace( '.', '_' ).toLowerCase();
+ }
+
+ @Override
+ public String propertyToColumnName(String propertyName) {
+ return addUnderscores( propertyName );
+ }
+
+ @Override
+ public String collectionTableName(
+ String ownerEntity, String ownerEntityTable, String associatedEntity, String associatedEntityTable,
+ String propertyName
+ ) {
+ return tableName(
+ new StringBuilder( ownerEntityTable ).append( "_" )
+ .append(
+ associatedEntityTable != null ?
+ associatedEntityTable :
+ addUnderscores( propertyName )
+ ).toString()
+ );
+ }
+
+
+ public String foreignKeyColumnName(
+ String propertyName, String propertyEntityName, String propertyTableName, String referencedColumnName
+ ) {
+ String header = propertyName != null ? addUnderscores( propertyName ) : propertyTableName;
+ if ( header == null ) throw new AssertionFailure( "NamingStrategy not properly filled" );
+ return columnName( header + "_" + referencedColumnName );
+ }
+
+ @Override
+ public String logicalColumnName(String columnName, String propertyName) {
+ return StringHelper.isNotEmpty( columnName ) ? columnName : propertyName;
+ }
+
+ @Override
+ public String logicalCollectionTableName(
+ String tableName, String ownerEntityTable, String associatedEntityTable, String propertyName
+ ) {
+ if ( tableName != null ) {
+ return tableName;
+ }
+ else {
+ //use of a stringbuffer to workaround a JDK bug
+ return new StringBuffer( ownerEntityTable ).append( "_" )
+ .append(
+ associatedEntityTable != null ?
+ associatedEntityTable :
+ propertyName
+ ).toString();
+ }
+
+ }
+
+ @Override
+ public String logicalCollectionColumnName(String columnName, String propertyName, String referencedColumn) {
+ return StringHelper.isNotEmpty( columnName ) ?
+ columnName :
+ propertyName + "_" + referencedColumn;
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/EJB3DTDEntityResolver.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/EJB3DTDEntityResolver.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/EJB3DTDEntityResolver.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,75 @@
+//$Id: EJB3DTDEntityResolver.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.cfg;
+
+import java.io.InputStream;
+
+import org.hibernate.util.DTDEntityResolver;
+import org.xml.sax.EntityResolver;
+import org.xml.sax.InputSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class EJB3DTDEntityResolver extends DTDEntityResolver {
+ public static final EntityResolver INSTANCE = new EJB3DTDEntityResolver();
+
+ private final Logger log = LoggerFactory.getLogger( EJB3DTDEntityResolver.class );
+
+ boolean resolved = false;
+
+ public boolean isResolved() {
+ return resolved;
+ }
+
+ public InputSource resolveEntity(String publicId, String systemId) {
+ InputSource is = super.resolveEntity( publicId, systemId );
+ if ( is == null ) {
+ if ( systemId != null ) {
+ if ( systemId.endsWith( "orm_1_0.xsd" ) ) {
+ log.debug(
+ "recognized EJB3 ORM namespace; attempting to resolve on classpath under org/hibernate/ejb"
+ );
+ String path = "org/hibernate/ejb/" + "orm_1_0.xsd";
+ InputStream dtdStream = resolveInHibernateNamespace( path );
+ if ( dtdStream == null ) {
+ log.debug( "unable to locate [{}] on classpath", systemId );
+ }
+ else {
+ log.debug( "located [{}] in classpath", systemId );
+ InputSource source = new InputSource( dtdStream );
+ source.setPublicId( publicId );
+ source.setSystemId( systemId );
+ resolved = false;
+ return source;
+ }
+ }
+ else if ( systemId.endsWith( "persistence_1_0.xsd" ) ) {
+ log.debug(
+ "recognized EJB3 ORM namespace; attempting to resolve on classpath under org/hibernate/ejb"
+ );
+ String path = "org/hibernate/ejb/" + "persistence_1_0.xsd";
+ InputStream dtdStream = resolveInHibernateNamespace( path );
+ if ( dtdStream == null ) {
+ log.debug( "unable to locate [{}] on classpath", systemId );
+ }
+ else {
+ log.debug( "located [{}] in classpath", systemId );
+ InputSource source = new InputSource( dtdStream );
+ source.setPublicId( publicId );
+ source.setSystemId( systemId );
+ resolved = true;
+ return source;
+ }
+ }
+ }
+ }
+ else {
+ resolved = true;
+ return is;
+ }
+ //use the default behavior
+ return null;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/EJB3NamingStrategy.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/EJB3NamingStrategy.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/EJB3NamingStrategy.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,86 @@
+//$Id: EJB3NamingStrategy.java 14741 2008-06-05 11:25:56Z hardy.ferentschik $
+package org.hibernate.cfg;
+
+import java.io.Serializable;
+
+import org.hibernate.AssertionFailure;
+import org.hibernate.util.StringHelper;
+
+/**
+ * Naming strategy implementing the EJB3 standards
+ *
+ * @author Emmanuel Bernard
+ */
+public class EJB3NamingStrategy implements NamingStrategy, Serializable {
+ public static final NamingStrategy INSTANCE = new EJB3NamingStrategy();
+
+ public String classToTableName(String className) {
+ return StringHelper.unqualify( className );
+ }
+
+ public String propertyToColumnName(String propertyName) {
+ return StringHelper.unqualify( propertyName );
+ }
+
+ public String tableName(String tableName) {
+ return tableName;
+ }
+
+ public String columnName(String columnName) {
+ return columnName;
+ }
+
+ public String collectionTableName(
+ String ownerEntity, String ownerEntityTable, String associatedEntity, String associatedEntityTable,
+ String propertyName
+ ) {
+ return tableName(
+ new StringBuilder( ownerEntityTable ).append( "_" )
+ .append(
+ associatedEntityTable != null ?
+ associatedEntityTable :
+ StringHelper.unqualify( propertyName )
+ ).toString()
+ );
+ }
+
+ public String joinKeyColumnName(String joinedColumn, String joinedTable) {
+ return columnName( joinedColumn );
+ }
+
+ public String foreignKeyColumnName(
+ String propertyName, String propertyEntityName, String propertyTableName, String referencedColumnName
+ ) {
+ String header = propertyName != null ? StringHelper.unqualify( propertyName ) : propertyTableName;
+ if ( header == null ) throw new AssertionFailure( "NamingStrategy not properly filled" );
+ return columnName( header + "_" + referencedColumnName );
+ }
+
+ public String logicalColumnName(String columnName, String propertyName) {
+ return StringHelper.isNotEmpty( columnName ) ? columnName : StringHelper.unqualify( propertyName );
+ }
+
+ public String logicalCollectionTableName(
+ String tableName,
+ String ownerEntityTable, String associatedEntityTable, String propertyName
+ ) {
+ if ( tableName != null ) {
+ return tableName;
+ }
+ else {
+ //use of a stringbuffer to workaround a JDK bug
+ return new StringBuffer( ownerEntityTable ).append( "_" )
+ .append(
+ associatedEntityTable != null ?
+ associatedEntityTable :
+ StringHelper.unqualify( propertyName )
+ ).toString();
+ }
+ }
+
+ public String logicalCollectionColumnName(String columnName, String propertyName, String referencedColumn) {
+ return StringHelper.isNotEmpty( columnName ) ?
+ columnName :
+ StringHelper.unqualify( propertyName ) + "_" + referencedColumn;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/Ejb3Column.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/Ejb3Column.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/Ejb3Column.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,461 @@
+//$Id: Ejb3Column.java 14748 2008-06-06 10:35:35Z hardy.ferentschik $
+package org.hibernate.cfg;
+
+import java.util.Map;
+
+import org.hibernate.AnnotationException;
+import org.hibernate.AssertionFailure;
+import org.hibernate.annotations.Index;
+import org.hibernate.cfg.annotations.Nullability;
+import org.hibernate.mapping.Column;
+import org.hibernate.mapping.Formula;
+import org.hibernate.mapping.Join;
+import org.hibernate.mapping.SimpleValue;
+import org.hibernate.mapping.Table;
+import org.hibernate.util.StringHelper;
+import org.slf4j.LoggerFactory;
+import org.slf4j.Logger;
+
+/**
+ * Wrap state of an EJB3 @Column annotation
+ * and build the Hibernate column mapping element
+ *
+ * @author Emmanuel Bernard
+ */
+public class Ejb3Column {
+ private static final Logger log = LoggerFactory.getLogger( Ejb3Column.class );
+ private Column mappingColumn;
+ private boolean insertable = true;
+ private boolean updatable = true;
+ private String secondaryTableName;
+ protected Map<String, Join> joins;
+ protected PropertyHolder propertyHolder;
+ private ExtendedMappings mappings;
+ private boolean isImplicit;
+ public static final int DEFAULT_COLUMN_LENGTH = 255;
+ public String sqlType;
+ private int length = DEFAULT_COLUMN_LENGTH;
+ private int precision;
+ private int scale;
+ private String logicalColumnName;
+ private String propertyName;
+ private boolean unique;
+ private boolean nullable = true;
+ private String formulaString;
+ private Formula formula;
+ private Table table;
+
+ public void setTable(Table table) {
+ this.table = table;
+ }
+
+ public String getLogicalColumnName() {
+ return logicalColumnName;
+ }
+
+ public String getSqlType() {
+ return sqlType;
+ }
+
+ public int getLength() {
+ return length;
+ }
+
+ public int getPrecision() {
+ return precision;
+ }
+
+ public int getScale() {
+ return scale;
+ }
+
+ public boolean isUnique() {
+ return unique;
+ }
+
+ public String getFormulaString() {
+ return formulaString;
+ }
+
+ public String getSecondaryTableName() {
+ return secondaryTableName;
+ }
+
+ public void setFormula(String formula) {
+ this.formulaString = formula;
+ }
+
+ public boolean isImplicit() {
+ return isImplicit;
+ }
+
+ public void setInsertable(boolean insertable) {
+ this.insertable = insertable;
+ }
+
+ public void setUpdatable(boolean updatable) {
+ this.updatable = updatable;
+ }
+
+ protected ExtendedMappings getMappings() {
+ return mappings;
+ }
+
+ public void setMappings(ExtendedMappings mappings) {
+ this.mappings = mappings;
+ }
+
+ public void setImplicit(boolean implicit) {
+ isImplicit = implicit;
+ }
+
+ public void setSqlType(String sqlType) {
+ this.sqlType = sqlType;
+ }
+
+ public void setLength(int length) {
+ this.length = length;
+ }
+
+ public void setPrecision(int precision) {
+ this.precision = precision;
+ }
+
+ public void setScale(int scale) {
+ this.scale = scale;
+ }
+
+ public void setLogicalColumnName(String logicalColumnName) {
+ this.logicalColumnName = logicalColumnName;
+ }
+
+ public void setPropertyName(String propertyName) {
+ this.propertyName = propertyName;
+ }
+
+ public String getPropertyName() {
+ return propertyName;
+ }
+
+ public void setUnique(boolean unique) {
+ this.unique = unique;
+ }
+
+ public boolean isNullable() {
+ return mappingColumn.isNullable();
+ }
+
+ public Ejb3Column() {
+ }
+
+ public void bind() {
+ if ( StringHelper.isNotEmpty( formulaString ) ) {
+ log.debug( "binding formula {}", formulaString );
+ formula = new Formula();
+ formula.setFormula( formulaString );
+ }
+ else {
+ initMappingColumn(
+ logicalColumnName, propertyName, length, precision, scale, nullable, sqlType, unique, true
+ );
+ log.debug( "Binding column {}. Unique {}. Nullable {}.", new Object[] {mappingColumn.getName(), unique, nullable});
+ }
+ }
+
+ protected void initMappingColumn(
+ String columnName, String propertyName, int length, int precision, int scale, boolean nullable,
+ String sqlType, boolean unique, boolean applyNamingStrategy
+ ) {
+ this.mappingColumn = new Column();
+ redefineColumnName( columnName, propertyName, applyNamingStrategy );
+ this.mappingColumn.setLength( length );
+ if ( precision > 0 ) { //revelent precision
+ this.mappingColumn.setPrecision( precision );
+ this.mappingColumn.setScale( scale );
+ }
+ this.mappingColumn.setNullable( nullable );
+ this.mappingColumn.setSqlType( sqlType );
+ this.mappingColumn.setUnique( unique );
+ }
+
+ public boolean isNameDeferred() {
+ return mappingColumn == null || StringHelper.isEmpty( mappingColumn.getName() );
+ }
+
+ public void redefineColumnName(String columnName, String propertyName, boolean applyNamingStrategy) {
+ if ( applyNamingStrategy ) {
+ if ( StringHelper.isEmpty( columnName ) ) {
+ if ( propertyName != null ) {
+ mappingColumn.setName( mappings.getNamingStrategy().propertyToColumnName( propertyName ) );
+ }
+ //Do nothing otherwise
+ }
+ else {
+ mappingColumn.setName( mappings.getNamingStrategy().columnName( columnName ) );
+ }
+ }
+ else {
+ if ( StringHelper.isNotEmpty( columnName ) ) mappingColumn.setName( columnName );
+ }
+ }
+
+ public String getName() {
+ return mappingColumn.getName();
+ }
+
+ public Column getMappingColumn() {
+ return mappingColumn;
+ }
+
+ public boolean isInsertable() {
+ return insertable;
+ }
+
+ public boolean isUpdatable() {
+ return updatable;
+ }
+
+ public void setNullable(boolean nullable) {
+ if ( mappingColumn != null ) {
+ mappingColumn.setNullable( nullable );
+ }
+ else {
+ this.nullable = nullable;
+ }
+ }
+
+ public void setJoins(Map<String, Join> joins) {
+ this.joins = joins;
+ }
+
+ public PropertyHolder getPropertyHolder() {
+ return propertyHolder;
+ }
+
+ public void setPropertyHolder(PropertyHolder propertyHolder) {
+ this.propertyHolder = propertyHolder;
+ }
+
+ protected void setMappingColumn(Column mappingColumn) {
+ this.mappingColumn = mappingColumn;
+ }
+
+ public void linkWithValue(SimpleValue value) {
+ if ( formula != null ) {
+ value.addFormula( formula );
+ }
+ else {
+ getMappingColumn().setValue( value );
+ value.addColumn( getMappingColumn() );
+ value.getTable().addColumn( getMappingColumn() );
+ addColumnBinding( value );
+ table = value.getTable();
+ }
+ }
+
+ protected void addColumnBinding(SimpleValue value) {
+ String logicalColumnName = mappings.getNamingStrategy()
+ .logicalColumnName( this.logicalColumnName, propertyName );
+ mappings.addColumnBinding( logicalColumnName, getMappingColumn(), value.getTable() );
+ }
+
+ /**
+ * Find appropriate table of the column.
+ * It can come from a secondary table or from the main table of the persistent class
+ *
+ * @return appropriate table
+ * @throws AnnotationException missing secondary table
+ */
+ public Table getTable() {
+ if ( table != null ) return table; //association table
+ if ( isSecondary() ) {
+ return getJoin().getTable();
+ }
+ else {
+ return propertyHolder.getTable();
+ }
+ }
+
+ public boolean isSecondary() {
+ if ( propertyHolder == null ) {
+ throw new AssertionFailure( "Should not call getTable() on column wo persistent class defined" );
+ }
+ if ( StringHelper.isNotEmpty( secondaryTableName ) ) {
+ return true;
+ }
+ // else {
+ return false;
+ }
+
+ public Join getJoin() {
+ Join join = joins.get( secondaryTableName );
+ if ( join == null ) {
+ throw new AnnotationException(
+ "Cannot find the expected secondary table: no "
+ + secondaryTableName + " available for " + propertyHolder.getClassName()
+ );
+ }
+ else {
+ return join;
+ }
+ }
+
+ public void forceNotNull() {
+ mappingColumn.setNullable( false );
+ }
+
+ public void setSecondaryTableName(String secondaryTableName) {
+ this.secondaryTableName = secondaryTableName;
+ }
+
+ public static Ejb3Column[] buildColumnFromAnnotation(
+ javax.persistence.Column[] anns,
+ org.hibernate.annotations.Formula formulaAnn, Nullability nullability, PropertyHolder propertyHolder,
+ PropertyData inferredData,
+ Map<String, Join> secondaryTables,
+ ExtendedMappings mappings
+ ) {
+ Ejb3Column[] columns;
+ if ( formulaAnn != null ) {
+ Ejb3Column formulaColumn = new Ejb3Column();
+ formulaColumn.setFormula( formulaAnn.value() );
+ formulaColumn.setImplicit( false );
+ formulaColumn.setMappings( mappings );
+ formulaColumn.setPropertyHolder( propertyHolder );
+ formulaColumn.bind();
+ columns = new Ejb3Column[] { formulaColumn };
+ }
+ else {
+ javax.persistence.Column[] actualCols = anns;
+ javax.persistence.Column[] overriddenCols = propertyHolder.getOverriddenColumn(
+ StringHelper.qualify( propertyHolder.getPath(), inferredData.getPropertyName() )
+ );
+ if ( overriddenCols != null ) {
+ //check for overridden first
+ if ( anns != null && overriddenCols.length != anns.length ) {
+ throw new AnnotationException( "AttributeOverride.column() should override all columns for now" );
+ }
+ actualCols = overriddenCols.length == 0 ? null : overriddenCols;
+ log.debug( "Column(s) overridden for property {}", inferredData.getPropertyName() );
+ }
+ if ( actualCols == null ) {
+ columns = buildImplicitColumn( inferredData, secondaryTables, propertyHolder, nullability, mappings );
+ }
+ else {
+ final int length = actualCols.length;
+ columns = new Ejb3Column[length];
+ for (int index = 0; index < length; index++) {
+ javax.persistence.Column col = actualCols[index];
+ String sqlType = col.columnDefinition().equals( "" ) ? null : col.columnDefinition();
+ Ejb3Column column = new Ejb3Column();
+ column.setImplicit( false );
+ column.setSqlType( sqlType );
+ column.setLength( col.length() );
+ column.setPrecision( col.precision() );
+ column.setScale( col.scale() );
+ column.setLogicalColumnName( col.name() );
+ column.setPropertyName(
+ BinderHelper.getRelativePath( propertyHolder, inferredData.getPropertyName() )
+ );
+ column.setNullable(
+ col.nullable()
+ ); //TODO force to not null if available? This is a (bad) user choice.
+ column.setUnique( col.unique() );
+ column.setInsertable( col.insertable() );
+ column.setUpdatable( col.updatable() );
+ column.setSecondaryTableName( col.table() );
+ column.setPropertyHolder( propertyHolder );
+ column.setJoins( secondaryTables );
+ column.setMappings( mappings );
+ column.bind();
+ columns[index] = column;
+ }
+ }
+ }
+ return columns;
+ }
+
+ private static Ejb3Column[] buildImplicitColumn(
+ PropertyData inferredData, Map<String, Join> secondaryTables, PropertyHolder propertyHolder,
+ Nullability nullability, ExtendedMappings mappings
+ ) {
+ Ejb3Column[] columns;
+ columns = new Ejb3Column[1];
+ Ejb3Column column = new Ejb3Column();
+ column.setImplicit( false );
+ //not following the spec but more clean
+ if ( nullability != Nullability.FORCED_NULL
+ && inferredData.getClassOrElement().isPrimitive()
+ && !inferredData.getProperty().isArray() ) {
+ column.setNullable( false );
+ }
+ column.setLength( DEFAULT_COLUMN_LENGTH );
+ column.setPropertyName(
+ BinderHelper.getRelativePath( propertyHolder, inferredData.getPropertyName() )
+ );
+ column.setPropertyHolder( propertyHolder );
+ column.setJoins( secondaryTables );
+ column.setMappings( mappings );
+ column.bind();
+ columns[0] = column;
+ return columns;
+ }
+
+ public static void checkPropertyConsistency(Ejb3Column[] columns, String propertyName) {
+ int nbrOfColumns = columns.length;
+ if ( nbrOfColumns > 1 ) {
+ for (int currentIndex = 1; currentIndex < nbrOfColumns; currentIndex++) {
+ if ( columns[currentIndex].isInsertable() != columns[currentIndex - 1].isInsertable() ) {
+ throw new AnnotationException(
+ "Mixing insertable and non insertable columns in a property is not allowed: " + propertyName
+ );
+ }
+ if ( columns[currentIndex].isNullable() != columns[currentIndex - 1].isNullable() ) {
+ throw new AnnotationException(
+ "Mixing nullable and non nullable columns in a property is not allowed: " + propertyName
+ );
+ }
+ if ( columns[currentIndex].isUpdatable() != columns[currentIndex - 1].isUpdatable() ) {
+ throw new AnnotationException(
+ "Mixing updatable and non updatable columns in a property is not allowed: " + propertyName
+ );
+ }
+ if ( !columns[currentIndex].getTable().equals( columns[currentIndex - 1].getTable() ) ) {
+ throw new AnnotationException(
+ "Mixing different tables in a property is not allowed: " + propertyName
+ );
+ }
+ }
+ }
+ }
+
+ public void addIndex(Index index, boolean inSecondPass) {
+ if ( index == null ) return;
+ String indexName = index.name();
+ addIndex( indexName, inSecondPass );
+ }
+
+ void addIndex(String indexName, boolean inSecondPass) {
+ IndexOrUniqueKeySecondPass secondPass = new IndexOrUniqueKeySecondPass( indexName, this, mappings, false );
+ if ( inSecondPass ) {
+ secondPass.doSecondPass( mappings.getClasses() );
+ }
+ else {
+ mappings.addSecondPass(
+ secondPass
+ );
+ }
+ }
+
+ void addUniqueKey(String uniqueKeyName, boolean inSecondPass) {
+ IndexOrUniqueKeySecondPass secondPass = new IndexOrUniqueKeySecondPass( uniqueKeyName, this, mappings, true );
+ if ( inSecondPass ) {
+ secondPass.doSecondPass( mappings.getClasses() );
+ }
+ else {
+ mappings.addSecondPass(
+ secondPass
+ );
+ }
+ }
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/Ejb3DiscriminatorColumn.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/Ejb3DiscriminatorColumn.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/Ejb3DiscriminatorColumn.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,82 @@
+//$Id: Ejb3DiscriminatorColumn.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.cfg;
+
+import javax.persistence.DiscriminatorColumn;
+import javax.persistence.DiscriminatorType;
+
+import org.hibernate.AssertionFailure;
+import org.hibernate.annotations.DiscriminatorFormula;
+
+/**
+ * Discriminator column
+ *
+ * @author Emmanuel Bernard
+ */
+public class Ejb3DiscriminatorColumn extends Ejb3Column {
+
+
+ private static final String DEFAULT_DISCRIMINATOR_COLUMN_NAME = "DTYPE";
+ private static final String DEFAULT_DISCRIMINATOR_TYPE = "string";
+
+ private String discriminatorTypeName;
+ private static final int DEFAULT_DISCRIMINATOR_LENGTH = 31;
+
+ public Ejb3DiscriminatorColumn() {
+ //discriminator default value
+ super();
+ setLogicalColumnName( DEFAULT_DISCRIMINATOR_COLUMN_NAME );
+ setNullable( false );
+ setDiscriminatorTypeName( DEFAULT_DISCRIMINATOR_TYPE );
+ setLength( DEFAULT_DISCRIMINATOR_LENGTH );
+ }
+
+ public String getDiscriminatorTypeName() {
+ return discriminatorTypeName;
+ }
+
+ public void setDiscriminatorTypeName(String discriminatorTypeName) {
+ this.discriminatorTypeName = discriminatorTypeName;
+ }
+
+ public static Ejb3DiscriminatorColumn buildDiscriminatorColumn(
+ DiscriminatorType type, DiscriminatorColumn discAnn, DiscriminatorFormula discFormulaAnn,
+ ExtendedMappings mappings
+ ) {
+ Ejb3DiscriminatorColumn discriminatorColumn = new Ejb3DiscriminatorColumn();
+ discriminatorColumn.setMappings( mappings );
+ discriminatorColumn.setImplicit( true );
+ if ( discFormulaAnn != null ) {
+ discriminatorColumn.setImplicit( false );
+ discriminatorColumn.setFormula( discFormulaAnn.value() );
+ }
+ else if ( discAnn != null ) {
+ discriminatorColumn.setImplicit( false );
+ if ( !BinderHelper.isDefault( discAnn.columnDefinition() ) ) {
+ discriminatorColumn.setSqlType(
+ discAnn.columnDefinition()
+ );
+ }
+ if ( !BinderHelper.isDefault( discAnn.name() ) ) {
+ discriminatorColumn.setLogicalColumnName( discAnn.name() );
+ }
+ discriminatorColumn.setNullable( false );
+ }
+ if ( DiscriminatorType.CHAR.equals( type ) ) {
+ discriminatorColumn.setDiscriminatorTypeName( "character" );
+ discriminatorColumn.setImplicit( false );
+ }
+ else if ( DiscriminatorType.INTEGER.equals( type ) ) {
+ discriminatorColumn.setDiscriminatorTypeName( "integer" );
+ discriminatorColumn.setImplicit( false );
+ }
+ else if ( DiscriminatorType.STRING.equals( type ) || type == null ) {
+ if ( discAnn != null ) discriminatorColumn.setLength( discAnn.length() );
+ discriminatorColumn.setDiscriminatorTypeName( "string" );
+ }
+ else {
+ throw new AssertionFailure( "Unknown discriminator type: " + type );
+ }
+ discriminatorColumn.bind();
+ return discriminatorColumn;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/Ejb3JoinColumn.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/Ejb3JoinColumn.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/Ejb3JoinColumn.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,530 @@
+//$Id: Ejb3JoinColumn.java 14761 2008-06-11 13:51:06Z hardy.ferentschik $
+package org.hibernate.cfg;
+
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+import javax.persistence.JoinColumn;
+import javax.persistence.PrimaryKeyJoinColumn;
+
+import org.hibernate.AnnotationException;
+import org.hibernate.MappingException;
+import org.hibernate.annotations.common.util.StringHelper;
+import org.hibernate.mapping.Column;
+import org.hibernate.mapping.Join;
+import org.hibernate.mapping.PersistentClass;
+import org.hibernate.mapping.SimpleValue;
+import org.hibernate.mapping.Table;
+import org.hibernate.mapping.Value;
+
+/**
+ * Wrap state of an EJB3 @JoinColumn annotation
+ * and build the Hibernate column mapping element
+ *
+ * @author Emmanuel Bernard
+ */
+@SuppressWarnings("unchecked")
+public class Ejb3JoinColumn extends Ejb3Column {
+ /**
+ * property name repated to this column
+ */
+ private String referencedColumn;
+ private String mappedBy;
+ //property name on the mapped by side if any
+ private String mappedByPropertyName;
+ //table name on the mapped by side if any
+ private String mappedByTableName;
+ private String mappedByEntityName;
+
+ //FIXME hacky solution to get the information at property ref resolution
+ public String getManyToManyOwnerSideEntityName() {
+ return manyToManyOwnerSideEntityName;
+ }
+
+ public void setManyToManyOwnerSideEntityName(String manyToManyOwnerSideEntityName) {
+ this.manyToManyOwnerSideEntityName = manyToManyOwnerSideEntityName;
+ }
+
+ private String manyToManyOwnerSideEntityName;
+
+ public void setReferencedColumn(String referencedColumn) {
+ this.referencedColumn = referencedColumn;
+ }
+
+ public String getMappedBy() {
+ return mappedBy;
+ }
+
+ public void setMappedBy(String mappedBy) {
+ this.mappedBy = mappedBy;
+ }
+
+ //Due to @AnnotationOverride overriding rules, I don't want the constructor to be public
+ private Ejb3JoinColumn() {
+ setMappedBy( BinderHelper.ANNOTATION_STRING_DEFAULT );
+ }
+
+ //Due to @AnnotationOverride overriding rules, I don't want the constructor to be public
+ //TODO get rid of it and use setters
+ private Ejb3JoinColumn(
+ String sqlType,
+ String name,
+ boolean nullable,
+ boolean unique,
+ boolean insertable,
+ boolean updatable,
+ String referencedColumn,
+ String secondaryTable,
+ Map<String, Join> joins,
+ PropertyHolder propertyHolder,
+ String propertyName,
+ String mappedBy,
+ boolean isImplicit,
+ ExtendedMappings mappings
+ ) {
+ super();
+ setImplicit( isImplicit );
+ setSqlType( sqlType );
+ setLogicalColumnName( name );
+ setNullable( nullable );
+ setUnique( unique );
+ setInsertable( insertable );
+ setUpdatable( updatable );
+ setSecondaryTableName( secondaryTable );
+ setPropertyHolder( propertyHolder );
+ setJoins( joins );
+ setMappings( mappings );
+ setPropertyName( BinderHelper.getRelativePath( propertyHolder, propertyName ) );
+ bind();
+ this.referencedColumn = referencedColumn;
+ this.mappedBy = mappedBy;
+ }
+
+ public String getReferencedColumn() {
+ return referencedColumn;
+ }
+
+ public static Ejb3JoinColumn[] buildJoinColumns(
+ JoinColumn[] anns,
+ String mappedBy, Map<String, Join> joins,
+ PropertyHolder propertyHolder,
+ String propertyName,
+ ExtendedMappings mappings
+ ) {
+ JoinColumn[] actualColumns = propertyHolder.getOverriddenJoinColumn(
+ StringHelper.qualify( propertyHolder.getPath(), propertyName )
+ );
+ if ( actualColumns == null ) actualColumns = anns;
+ if ( actualColumns == null || actualColumns.length == 0 ) {
+ return new Ejb3JoinColumn[] {
+ buildJoinColumn( (JoinColumn) null, mappedBy, joins, propertyHolder, propertyName, mappings )
+ };
+ }
+ else {
+ int size = actualColumns.length;
+ Ejb3JoinColumn[] result = new Ejb3JoinColumn[size];
+ for (int index = 0; index < size; index++) {
+ result[index] = buildJoinColumn(
+ actualColumns[index],
+ mappedBy,
+ joins,
+ propertyHolder,
+ propertyName,
+ mappings
+ );
+ }
+ return result;
+ }
+ }
+
+ /**
+ * build join column for SecondaryTables
+ */
+ private static Ejb3JoinColumn buildJoinColumn(
+ JoinColumn ann,
+ String mappedBy, Map<String, Join> joins,
+ PropertyHolder propertyHolder,
+ String propertyName,
+ ExtendedMappings mappings
+ ) {
+ if ( ann != null ) {
+ if ( BinderHelper.isDefault( mappedBy ) ) {
+ throw new AnnotationException(
+ "Illegal attempt to define a @JoinColumn with a mappedBy association: "
+ + BinderHelper.getRelativePath( propertyHolder, propertyName )
+ );
+ }
+ Ejb3JoinColumn joinColumn = new Ejb3JoinColumn();
+ joinColumn.setJoinAnnotation( ann, null );
+ joinColumn.setJoins( joins );
+ joinColumn.setPropertyHolder( propertyHolder );
+ joinColumn.setPropertyName( BinderHelper.getRelativePath( propertyHolder, propertyName ) );
+ joinColumn.setImplicit( false );
+ joinColumn.setMappings( mappings );
+ joinColumn.bind();
+ return joinColumn;
+ }
+ else {
+ Ejb3JoinColumn joinColumn = new Ejb3JoinColumn();
+ joinColumn.setMappedBy( mappedBy );
+ joinColumn.setJoins( joins );
+ joinColumn.setPropertyHolder( propertyHolder );
+ joinColumn.setPropertyName( BinderHelper.getRelativePath( propertyHolder, propertyName ) );
+ joinColumn.setImplicit( true );
+ joinColumn.setMappings( mappings );
+ joinColumn.bind();
+ return joinColumn;
+ }
+ }
+
+
+ //FIXME default name still useful in association table
+ public void setJoinAnnotation(JoinColumn annJoin, String defaultName) {
+ if ( annJoin == null ) {
+ setImplicit( true );
+ }
+ else {
+ setImplicit( false );
+ if ( !BinderHelper.isDefault( annJoin.columnDefinition() ) ) setSqlType( annJoin.columnDefinition() );
+ if ( !BinderHelper.isDefault( annJoin.name() ) ) setLogicalColumnName( annJoin.name() );
+ setNullable( annJoin.nullable() );
+ setUnique( annJoin.unique() );
+ setInsertable( annJoin.insertable() );
+ setUpdatable( annJoin.updatable() );
+ setReferencedColumn( annJoin.referencedColumnName() );
+ setSecondaryTableName( annJoin.table() );
+ }
+ }
+
+ /**
+ * Build JoinColumn for a JOINED hierarchy
+ */
+ public static Ejb3JoinColumn buildJoinColumn(
+ PrimaryKeyJoinColumn pkJoinAnn,
+ JoinColumn joinAnn,
+ Value identifier,
+ Map<String, Join> joins,
+ PropertyHolder propertyHolder, ExtendedMappings mappings
+ ) {
+
+ Column col = (Column) identifier.getColumnIterator().next();
+ String defaultName = mappings.getLogicalColumnName( col.getQuotedName(), identifier.getTable() );
+ if ( pkJoinAnn != null || joinAnn != null ) {
+ String colName;
+ String columnDefinition;
+ String referencedColumnName;
+ if ( pkJoinAnn != null ) {
+ colName = pkJoinAnn.name();
+ columnDefinition = pkJoinAnn.columnDefinition();
+ referencedColumnName = pkJoinAnn.referencedColumnName();
+ }
+ else {
+ colName = joinAnn.name();
+ columnDefinition = joinAnn.columnDefinition();
+ referencedColumnName = joinAnn.referencedColumnName();
+ }
+ String sqlType = "".equals( columnDefinition ) ? null : columnDefinition;
+ String name = "".equals( colName ) ? defaultName : colName;
+ return new Ejb3JoinColumn(
+ sqlType,
+ name, false, false,
+ true, true,
+ referencedColumnName,
+ null, joins,
+ propertyHolder, null, null, false, mappings
+ );
+ }
+ else {
+ return new Ejb3JoinColumn(
+ (String) null, defaultName,
+ false, false, true, true, null, (String) null,
+ joins, propertyHolder, null, null, true, mappings
+ );
+ }
+ }
+
+ /**
+ * Override persistent class on oneToMany Cases for late settings
+ * Must only be used on second level pass binding
+ */
+ public void setPersistentClass(PersistentClass persistentClass, Map<String, Join> joins) {
+ //FIXME shouldn't we deduce the classname from the persistentclasS?
+ this.propertyHolder = PropertyHolderBuilder.buildPropertyHolder( persistentClass, joins, getMappings() );
+ }
+
+ public static void checkIfJoinColumn(Object columns, PropertyHolder holder, PropertyData property) {
+ if ( !( columns instanceof Ejb3JoinColumn[] ) ) {
+ throw new AnnotationException(
+ "@Column cannot be used on an association property: "
+ + holder.getEntityName()
+ + "."
+ + property.getPropertyName()
+ );
+ }
+ }
+
+ public void linkValueUsingDefaultColumnNaming(
+ Column referencedColumn, PersistentClass referencedEntity, SimpleValue value
+ ) {
+ String columnName;
+ String logicalReferencedColumn = getMappings().getLogicalColumnName(
+ referencedColumn.getQuotedName(), referencedEntity.getTable()
+ );
+ boolean mappedBySide = mappedByTableName != null || mappedByPropertyName != null;
+ boolean ownerSide = getPropertyName() != null;
+
+ Boolean isRefColumnQuoted = StringHelper.isQuoted( logicalReferencedColumn );
+ String unquotedLogicalReferenceColumn = isRefColumnQuoted ?
+ StringHelper.unquote( logicalReferencedColumn ) :
+ logicalReferencedColumn;
+
+ if ( mappedBySide ) {
+ String unquotedMappedbyTable = StringHelper.unquote( mappedByTableName );
+ columnName = getMappings().getNamingStrategy().foreignKeyColumnName(
+ mappedByPropertyName,
+ mappedByEntityName,
+ unquotedMappedbyTable,
+ unquotedLogicalReferenceColumn
+ );
+ //one element was quoted so we quote
+ if ( isRefColumnQuoted || StringHelper.isQuoted( mappedByTableName ) ) {
+ columnName = StringHelper.quote( columnName );
+ }
+ }
+ else if ( ownerSide ) {
+ String logicalTableName = getMappings().getLogicalTableName( referencedEntity.getTable() );
+ String unquotedLogicalTableName = StringHelper.unquote( logicalTableName );
+ columnName = getMappings().getNamingStrategy().foreignKeyColumnName(
+ getPropertyName(),
+ referencedEntity.getEntityName(),
+ unquotedLogicalTableName,
+ unquotedLogicalReferenceColumn
+ );
+ //one element was quoted so we quote
+ if ( isRefColumnQuoted || StringHelper.isQuoted( logicalTableName ) ) {
+ columnName = StringHelper.quote( columnName );
+ }
+ }
+ else {
+ //is an intra-entity hierarchy table join so copy the name by default
+ String logicalTableName = getMappings().getLogicalTableName( referencedEntity.getTable() );
+ String unquotedLogicalTableName = StringHelper.unquote( logicalTableName );
+ columnName = getMappings().getNamingStrategy().joinKeyColumnName(
+ unquotedLogicalReferenceColumn,
+ unquotedLogicalTableName
+ );
+ //one element was quoted so we quote
+ if ( isRefColumnQuoted || StringHelper.isQuoted( logicalTableName ) ) {
+ columnName = StringHelper.quote( columnName );
+ }
+ }
+ //yuk side effect on an implicit column
+ setLogicalColumnName( columnName );
+ setReferencedColumn( logicalReferencedColumn );
+ initMappingColumn(
+ columnName,
+ null, referencedColumn.getLength(),
+ referencedColumn.getPrecision(),
+ referencedColumn.getScale(),
+ getMappingColumn().isNullable(),
+ referencedColumn.getSqlType(),
+ getMappingColumn().isUnique(), false
+ );
+ linkWithValue( value );
+ }
+
+ /**
+ * used for mappedBy cases
+ */
+ public void linkValueUsingAColumnCopy(Column column, SimpleValue value) {
+ initMappingColumn(
+ //column.getName(),
+ column.getQuotedName(),
+ null, column.getLength(),
+ column.getPrecision(),
+ column.getScale(),
+ getMappingColumn().isNullable(),
+ column.getSqlType(),
+ getMappingColumn().isUnique(),
+ false //We do copy no strategy here
+ );
+ linkWithValue( value );
+ }
+
+ protected void addColumnBinding(SimpleValue value) {
+ if ( StringHelper.isEmpty( mappedBy ) ) {
+ String unquotedLogColName = StringHelper.unquote( getLogicalColumnName() );
+ String unquotedRefColumn = StringHelper.unquote( getReferencedColumn() );
+ String logicalColumnName = getMappings().getNamingStrategy()
+ .logicalCollectionColumnName( unquotedLogColName, getPropertyName(), unquotedRefColumn );
+ if ( StringHelper.isQuoted( getLogicalColumnName() ) || StringHelper.isQuoted( getLogicalColumnName() ) ) {
+ logicalColumnName = StringHelper.quote( logicalColumnName );
+ }
+ getMappings().addColumnBinding( logicalColumnName, getMappingColumn(), value.getTable() );
+ }
+ }
+
+ //keep it JDK 1.4 compliant
+ //implicit way
+ public static final int NO_REFERENCE = 0;
+ //reference to the pk in an explicit order
+ public static final int PK_REFERENCE = 1;
+ //reference to non pk columns
+ public static final int NON_PK_REFERENCE = 2;
+
+ public static int checkReferencedColumnsType(
+ Ejb3JoinColumn[] columns, PersistentClass referencedEntity,
+ ExtendedMappings mappings
+ ) {
+ //convenient container to find whether a column is an id one or not
+ Set<Column> idColumns = new HashSet<Column>();
+ Iterator idColumnsIt = referencedEntity.getKey().getColumnIterator();
+ while ( idColumnsIt.hasNext() ) {
+ idColumns.add( (Column) idColumnsIt.next() );
+ }
+
+ boolean isFkReferencedColumnName = false;
+ boolean noReferencedColumn = true;
+ //build the list of potential tables
+ if ( columns.length == 0 ) return NO_REFERENCE; //shortcut
+ Object columnOwner = BinderHelper.findColumnOwner(
+ referencedEntity, columns[0].getReferencedColumn(), mappings
+ );
+ if ( columnOwner == null ) {
+ try {
+ throw new MappingException(
+ "Unable to find column with logical name: "
+ + columns[0].getReferencedColumn() + " in " + referencedEntity.getTable() + " and its related "
+ + "supertables and secondary tables"
+ );
+ }
+ catch (MappingException e) {
+ throw new RecoverableException(e);
+ }
+ }
+ Table matchingTable = columnOwner instanceof PersistentClass ?
+ ( (PersistentClass) columnOwner ).getTable() :
+ ( (Join) columnOwner ).getTable();
+ //check each referenced column
+ for (Ejb3JoinColumn ejb3Column : columns) {
+ String logicalReferencedColumnName = ejb3Column.getReferencedColumn();
+ if ( StringHelper.isNotEmpty( logicalReferencedColumnName ) ) {
+ String referencedColumnName = null;
+ try {
+ referencedColumnName = mappings.getPhysicalColumnName( logicalReferencedColumnName, matchingTable );
+ }
+ catch (MappingException me) {
+ //rewrite the exception
+ throw new MappingException(
+ "Unable to find column with logical name: "
+ + logicalReferencedColumnName + " in " + matchingTable.getName()
+ );
+ }
+ noReferencedColumn = false;
+ Column refCol = new Column( referencedColumnName );
+ boolean contains = idColumns.contains( refCol );
+ if ( !contains ) {
+ isFkReferencedColumnName = true;
+ break; //we know the state
+ }
+ }
+ }
+ if ( isFkReferencedColumnName ) {
+ return NON_PK_REFERENCE;
+ }
+ else if ( noReferencedColumn ) {
+ return NO_REFERENCE;
+ }
+ else if ( idColumns.size() != columns.length ) {
+ //reference use PK but is a subset or a superset
+ return NON_PK_REFERENCE;
+ }
+ else {
+ return PK_REFERENCE;
+ }
+ }
+
+ /**
+ * Called to apply column definitions from the referenced FK column to this column.
+ *
+ * @param column the referenced column.
+ */
+ public void overrideFromReferencedColumnIfNecessary(org.hibernate.mapping.Column column) {
+
+ // columnDefinition can also be specified using @JoinColumn, hence we have to check
+ // whether it is set or not
+ if ( StringHelper.isEmpty( sqlType ) ) {
+ sqlType = column.getSqlType();
+ if ( getMappingColumn() != null ) getMappingColumn().setSqlType( sqlType );
+ }
+
+ // these properties can only be applied on the referenced column - we can just take them over
+ getMappingColumn().setLength(column.getLength());
+ getMappingColumn().setPrecision(column.getPrecision());
+ getMappingColumn().setScale(column.getScale());
+ }
+
+ @Override
+ public void redefineColumnName(String columnName, String propertyName, boolean applyNamingStrategy) {
+ if ( StringHelper.isNotEmpty( columnName ) ) {
+ getMappingColumn().setName(
+ applyNamingStrategy ?
+ getMappings().getNamingStrategy().columnName( columnName ) :
+ columnName
+ );
+ }
+ }
+
+ public static Ejb3JoinColumn[] buildJoinTableJoinColumns(
+ JoinColumn[] annJoins, Map<String, Join> secondaryTables,
+ PropertyHolder propertyHolder, String propertyName, String mappedBy, ExtendedMappings mappings
+ ) {
+ Ejb3JoinColumn[] joinColumns;
+ if ( annJoins == null ) {
+ Ejb3JoinColumn currentJoinColumn = new Ejb3JoinColumn();
+ currentJoinColumn.setImplicit( true );
+ currentJoinColumn.setNullable( false ); //I break the spec, but it's for good
+ currentJoinColumn.setPropertyHolder( propertyHolder );
+ currentJoinColumn.setJoins( secondaryTables );
+ currentJoinColumn.setMappings( mappings );
+ currentJoinColumn.setPropertyName(
+ BinderHelper.getRelativePath( propertyHolder, propertyName )
+ );
+ currentJoinColumn.setMappedBy( mappedBy );
+ currentJoinColumn.bind();
+
+ joinColumns = new Ejb3JoinColumn[] {
+ currentJoinColumn
+
+ };
+ }
+ else {
+ joinColumns = new Ejb3JoinColumn[annJoins.length];
+ JoinColumn annJoin;
+ int length = annJoins.length;
+ for (int index = 0; index < length; index++) {
+ annJoin = annJoins[index];
+ Ejb3JoinColumn currentJoinColumn = new Ejb3JoinColumn();
+ currentJoinColumn.setImplicit( true );
+ currentJoinColumn.setPropertyHolder( propertyHolder );
+ currentJoinColumn.setJoins( secondaryTables );
+ currentJoinColumn.setMappings( mappings );
+ currentJoinColumn.setPropertyName( BinderHelper.getRelativePath( propertyHolder, propertyName ) );
+ currentJoinColumn.setMappedBy( mappedBy );
+ currentJoinColumn.setJoinAnnotation( annJoin, propertyName );
+ currentJoinColumn.setNullable( false ); //I break the spec, but it's for good
+ //done after the annotation to override it
+ currentJoinColumn.bind();
+ joinColumns[index] = currentJoinColumn;
+ }
+ }
+ return joinColumns;
+ }
+
+ public void setMappedBy(String entityName, String logicalTableName, String mappedByProperty) {
+ this.mappedByEntityName = entityName;
+ this.mappedByTableName = logicalTableName;
+ this.mappedByPropertyName = mappedByProperty;
+ }
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/ExtendedMappings.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/ExtendedMappings.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/ExtendedMappings.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,282 @@
+//$Id: ExtendedMappings.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.cfg;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import javax.persistence.Embeddable;
+import javax.persistence.Entity;
+import javax.persistence.MappedSuperclass;
+
+import org.hibernate.AnnotationException;
+import org.hibernate.MappingException;
+import org.hibernate.annotations.AnyMetaDef;
+import org.hibernate.annotations.common.reflection.ReflectionManager;
+import org.hibernate.annotations.common.reflection.XClass;
+import org.hibernate.engine.NamedQueryDefinition;
+import org.hibernate.engine.NamedSQLQueryDefinition;
+import org.hibernate.engine.ResultSetMappingDefinition;
+import org.hibernate.mapping.IdGenerator;
+import org.hibernate.mapping.Join;
+import org.hibernate.mapping.PersistentClass;
+import org.hibernate.mapping.Table;
+import org.slf4j.LoggerFactory;
+import org.slf4j.Logger;
+
+/**
+ * Allow annotation related mappings
+ * <p/>
+ * at least for named generators
+ *
+ * @author Emmanuel Bernard
+ */
+public class ExtendedMappings extends Mappings {
+
+ private final Logger log = LoggerFactory.getLogger( ExtendedMappings.class );
+
+ private final Map<String, IdGenerator> namedGenerators;
+ private final Map<String, Map<String, Join>> joins;
+ private final Map<String, AnnotatedClassType> classTypes;
+ private final Map<String, Properties> generatorTables;
+ private final Map<Table, List<String[]>> tableUniqueConstraints;
+ private final Map<String, String> mappedByResolver;
+ private final Map<String, String> propertyRefResolver;
+ private final ReflectionManager reflectionManager;
+ private final Set<String> defaultNamedQueryNames;
+ private final Set<String> defaultNamedNativeQueryNames;
+ private final Set<String> defaultSqlResulSetMappingNames;
+ private final Set<String> defaultNamedGenerators;
+ private final Map<String, AnyMetaDef> anyMetaDefs;
+
+ ExtendedMappings(
+ Map classes, Map collections, Map tables, Map queries, Map sqlqueries, Map sqlResultSetMappings,
+ Set<String> defaultNamedQueryNames, Set<String> defaultNamedNativeQueryNames,
+ Set<String> defaultSqlResulSetMappingNames, Set<String> defaultNamedGenerators, Map imports,
+ List secondPasses, List propertyReferences, NamingStrategy namingStrategy, Map typeDefs,
+ Map filterDefinitions, Map namedGenerators, Map<String, Map<String, Join>> joins, Map<String,
+ AnnotatedClassType> classTypes, Map extendsQueue, Map<String, TableDescription> tableNameBinding,
+ Map<Table, ColumnNames> columnNameBindingPerTable,
+ final List auxiliaryDatabaseObjects,
+ Map<String, Properties> generatorTables,
+ Map<Table, List<String[]>> tableUniqueConstraints,
+ Map<String, String> mappedByResolver,
+ Map<String, String> propertyRefResolver,
+ Map<String, AnyMetaDef> anyMetaDefs,
+ ReflectionManager reflectionManager
+ ) {
+ super(
+ classes,
+ collections,
+ tables,
+ queries,
+ sqlqueries,
+ sqlResultSetMappings,
+ imports,
+ secondPasses,
+ propertyReferences,
+ namingStrategy,
+ typeDefs,
+ filterDefinitions,
+ extendsQueue,
+ auxiliaryDatabaseObjects,
+ tableNameBinding,
+ columnNameBindingPerTable
+ );
+ this.namedGenerators = namedGenerators;
+ this.joins = joins;
+ this.classTypes = classTypes;
+ this.generatorTables = generatorTables;
+ this.tableUniqueConstraints = tableUniqueConstraints;
+ this.mappedByResolver = mappedByResolver;
+ this.propertyRefResolver = propertyRefResolver;
+ this.reflectionManager = reflectionManager;
+ this.defaultNamedQueryNames = defaultNamedQueryNames;
+ this.defaultNamedNativeQueryNames = defaultNamedNativeQueryNames;
+ this.defaultSqlResulSetMappingNames = defaultSqlResulSetMappingNames;
+ this.defaultNamedGenerators = defaultNamedGenerators;
+ this.anyMetaDefs = anyMetaDefs;
+ }
+
+ public void addGenerator(IdGenerator generator) throws MappingException {
+ if ( !defaultNamedGenerators.contains( generator.getName() ) ) {
+ Object old = namedGenerators.put( generator.getName(), generator );
+ if ( old != null ) log.warn( "duplicate generator name: {}", generator.getName() );
+ }
+ }
+
+ public void addJoins(PersistentClass persistentClass, Map<String, Join> joins) throws MappingException {
+ Object old = this.joins.put( persistentClass.getEntityName(), joins );
+ if ( old != null ) log.warn( "duplicate joins for class: {}", persistentClass.getEntityName() );
+ }
+
+ public AnnotatedClassType addClassType(XClass clazz) {
+ AnnotatedClassType type;
+ if ( clazz.isAnnotationPresent( Entity.class ) ) {
+ type = AnnotatedClassType.ENTITY;
+ }
+ else if ( clazz.isAnnotationPresent( Embeddable.class ) ) {
+ type = AnnotatedClassType.EMBEDDABLE;
+ }
+ else if ( clazz.isAnnotationPresent( MappedSuperclass.class ) ) {
+ type = AnnotatedClassType.EMBEDDABLE_SUPERCLASS;
+ }
+ else {
+ type = AnnotatedClassType.NONE;
+ }
+ classTypes.put( clazz.getName(), type );
+ return type;
+ }
+
+ /**
+ * get and maintain a cache of class type.
+ * A class can be an entity, a embedded objet or nothing.
+ */
+ public AnnotatedClassType getClassType(XClass clazz) {
+ AnnotatedClassType type = classTypes.get( clazz.getName() );
+ if ( type == null ) {
+ return addClassType( clazz );
+ }
+ else {
+ return type;
+ }
+ }
+
+ public IdGenerator getGenerator(String name) {
+ return getGenerator( name, null );
+ }
+
+ public Map<String, Join> getJoins(String persistentClass) {
+ return joins.get( persistentClass );
+ }
+
+ /**
+ * Try to find the generator from the localGenerators
+ * and then from the global generator list
+ *
+ * @param name generator name
+ * @param localGenerators local generators to find to
+ * @return the appropriate idgenerator or null if not found
+ */
+ public IdGenerator getGenerator(String name, Map<String, IdGenerator> localGenerators) {
+ if ( localGenerators != null ) {
+ IdGenerator result = localGenerators.get( name );
+ if ( result != null ) return result;
+ }
+ return namedGenerators.get( name );
+ }
+
+ public void addGeneratorTable(String name, Properties params) {
+ Object old = generatorTables.put( name, params );
+ if ( old != null ) log.warn( "duplicate generator table: {}", name );
+ }
+
+ public Properties getGeneratorTableProperties(String name, Map<String, Properties> localGeneratorTables) {
+ if ( localGeneratorTables != null ) {
+ Properties result = localGeneratorTables.get( name );
+ if ( result != null ) return result;
+ }
+ return generatorTables.get( name );
+ }
+
+ public void addUniqueConstraints(Table table, List uniqueConstraints) {
+ List oldConstraints = tableUniqueConstraints.get( table );
+ if ( oldConstraints == null ) {
+ oldConstraints = new ArrayList();
+ tableUniqueConstraints.put( table, oldConstraints );
+ }
+ oldConstraints.addAll( uniqueConstraints );
+ }
+
+ public Map<Table, List<String[]>> getTableUniqueConstraints() {
+ return tableUniqueConstraints;
+ }
+
+ public void addMappedBy(String entityName, String propertyName, String inversePropertyName) {
+ mappedByResolver.put( entityName + "." + propertyName, inversePropertyName );
+ }
+
+ public String getFromMappedBy(String entityName, String propertyName) {
+ return mappedByResolver.get( entityName + "." + propertyName );
+ }
+
+ public void addPropertyReferencedAssociation(String entityName, String propertyName, String propertyRef) {
+ propertyRefResolver.put( entityName + "." + propertyName, propertyRef );
+ }
+
+ public String getPropertyReferencedAssociation(String entityName, String propertyName) {
+ return propertyRefResolver.get( entityName + "." + propertyName );
+ }
+
+ @Override
+ public void addUniquePropertyReference(String referencedClass, String propertyName) {
+ super.addUniquePropertyReference( referencedClass, propertyName );
+ }
+
+ @Override
+ public void addPropertyReference(String referencedClass, String propertyName) {
+ super.addPropertyReference( referencedClass, propertyName );
+ }
+
+ public ReflectionManager getReflectionManager() {
+ return reflectionManager;
+ }
+
+ public void addDefaultQuery(String name, NamedQueryDefinition query) {
+ super.addQuery( name, query );
+ defaultNamedQueryNames.add( name );
+ }
+
+ public void addDefaultSQLQuery(String name, NamedSQLQueryDefinition query) {
+ super.addSQLQuery( name, query );
+ defaultNamedNativeQueryNames.add( name );
+ }
+
+ public void addDefaultGenerator(IdGenerator idGen) {
+ this.addGenerator( idGen );
+ defaultNamedGenerators.add( idGen.getName() );
+
+ }
+
+ public void addDefaultResultSetMapping(ResultSetMappingDefinition definition) {
+ final String name = definition.getName();
+ if ( !defaultSqlResulSetMappingNames.contains( name )
+ && super.getResultSetMapping( name ) != null ) {
+ resultSetMappings.remove( name );
+ }
+ super.addResultSetMapping( definition );
+ defaultSqlResulSetMappingNames.add( name );
+ }
+
+ @Override
+ public void addQuery(String name, NamedQueryDefinition query) throws MappingException {
+ if ( !defaultNamedQueryNames.contains( name ) ) super.addQuery( name, query );
+ }
+
+ @Override
+ public void addResultSetMapping(ResultSetMappingDefinition definition) {
+ if ( !defaultSqlResulSetMappingNames.contains( definition.getName() ) )
+ super.addResultSetMapping( definition );
+ }
+
+ @Override
+ public void addSQLQuery(String name, NamedSQLQueryDefinition query) throws MappingException {
+ if ( !defaultNamedNativeQueryNames.contains( name ) ) super.addSQLQuery( name, query );
+ }
+
+ public Map getClasses() {
+ return classes;
+ }
+
+ public void addAnyMetaDef(AnyMetaDef defAnn) {
+ if ( anyMetaDefs.containsKey( defAnn.name() ) ) {
+ throw new AnnotationException( "Two @AnyMetaDef with the same name defined: " + defAnn.name() );
+ }
+ anyMetaDefs.put( defAnn.name(), defAnn );
+ }
+
+ public AnyMetaDef getAnyMetaDef(String name) {
+ return anyMetaDefs.get( name );
+ }
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/FkSecondPass.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/FkSecondPass.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/FkSecondPass.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,56 @@
+//$Id: FkSecondPass.java 14779 2008-06-18 17:56:27Z hardy.ferentschik $
+package org.hibernate.cfg;
+
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.hibernate.mapping.SimpleValue;
+import org.hibernate.mapping.Value;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public abstract class FkSecondPass implements SecondPass {
+ protected SimpleValue value;
+ protected Ejb3JoinColumn[] columns;
+ /**
+ * unique counter is needed to differentiate 2 instances of FKSecondPass
+ * as they are compared.
+ * Fairly hacky but IBM VM sometimes returns the same hashCode for 2 different objects
+ * TODO is it doable to rely on the Ejb3JoinColumn names? Not sure at they could be inferred
+ */
+ private int uniqueCounter;
+ private static AtomicInteger globalCounter = new AtomicInteger();
+
+ public FkSecondPass(SimpleValue value, Ejb3JoinColumn[] columns) {
+ this.value = value;
+ this.columns = columns;
+ this.uniqueCounter = globalCounter.getAndIncrement();
+ }
+
+ public int getUniqueCounter() {
+ return uniqueCounter;
+ }
+
+ public Value getValue() {
+ return value;
+ }
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( !( o instanceof FkSecondPass ) ) return false;
+
+ FkSecondPass that = (FkSecondPass) o;
+
+ if ( uniqueCounter != that.uniqueCounter ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ return uniqueCounter;
+ }
+
+ public abstract String getReferencedEntityName();
+
+ public abstract boolean isInPrimaryKey();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/IndexColumn.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/IndexColumn.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/IndexColumn.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,87 @@
+package org.hibernate.cfg;
+
+import java.util.Map;
+
+import org.hibernate.mapping.Join;
+
+/**
+ * index column
+ *
+ * @author inger
+ */
+public class IndexColumn
+ extends Ejb3Column {
+
+ private int base;
+
+ //FIXME move to a getter setter strategy for readeability
+ public IndexColumn(
+ boolean isImplicit,
+ String sqlType,
+ int length,
+ int precision,
+ int scale,
+ String name,
+ boolean nullable,
+ boolean unique,
+ boolean insertable,
+ boolean updatable,
+ String secondaryTableName,
+ Map<String, Join> joins,
+ PropertyHolder propertyHolder,
+ ExtendedMappings mappings
+ ) {
+ super();
+ setImplicit( isImplicit );
+ setSqlType( sqlType );
+ setLength( length );
+ setPrecision( precision );
+ setScale( scale );
+ setLogicalColumnName( name );
+ setNullable( nullable );
+ setUnique( unique );
+ setInsertable( insertable );
+ setUpdatable( updatable );
+ setSecondaryTableName( secondaryTableName );
+ setPropertyHolder( propertyHolder );
+ setJoins( joins );
+ setMappings( mappings );
+ bind();
+ //super(isImplicit, sqlType, length, precision, scale, name, nullable, unique, insertable, updatable, secondaryTableName, joins, propertyHolder, mappings);
+
+ }
+
+ public int getBase() {
+ return base;
+ }
+
+ public void setBase(int base) {
+ this.base = base;
+ }
+
+ public static IndexColumn buildColumnFromAnnotation(
+ org.hibernate.annotations.IndexColumn ann,
+ PropertyHolder propertyHolder,
+ PropertyData inferredData,
+ ExtendedMappings mappings
+ ) {
+ IndexColumn column;
+ if ( ann != null ) {
+ String sqlType = BinderHelper.isDefault( ann.columnDefinition() ) ? null : ann.columnDefinition();
+ String name = BinderHelper.isDefault( ann.name() ) ? inferredData.getPropertyName() : ann.name();
+ //TODO move it to a getter based system and remove the constructor
+ column = new IndexColumn(
+ false, sqlType, 0, 0, 0, name, ann.nullable(),
+ false, true, true, null, null, propertyHolder, mappings
+ );
+ column.setBase( ann.base() );
+ }
+ else {
+ column = new IndexColumn(
+ true, null, 0, 0, 0, null, true,
+ false, true, true, null, null, propertyHolder, mappings
+ );
+ }
+ return column;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/IndexOrUniqueKeySecondPass.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/IndexOrUniqueKeySecondPass.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/IndexOrUniqueKeySecondPass.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,81 @@
+//$Id: IndexOrUniqueKeySecondPass.java 14747 2008-06-06 08:16:25Z hardy.ferentschik $
+package org.hibernate.cfg;
+
+import java.util.Map;
+
+import org.hibernate.AnnotationException;
+import org.hibernate.MappingException;
+import org.hibernate.mapping.Column;
+import org.hibernate.mapping.Table;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class IndexOrUniqueKeySecondPass implements SecondPass {
+ private Table table;
+ private final String indexName;
+ private final String[] columns;
+ private final ExtendedMappings mappings;
+ private final Ejb3Column column;
+ private final boolean unique;
+
+ /**
+ * Build an index
+ */
+ public IndexOrUniqueKeySecondPass(Table table, String indexName, String[] columns, ExtendedMappings mappings) {
+ this.table = table;
+ this.indexName = indexName;
+ this.columns = columns;
+ this.mappings = mappings;
+ this.column = null;
+ this.unique = false;
+ }
+
+ /**
+ * Build an index
+ */
+ public IndexOrUniqueKeySecondPass(String indexName, Ejb3Column column, ExtendedMappings mappings) {
+ this( indexName, column, mappings, false );
+ }
+
+ /**
+ * Build an index if unique is false or a Unique Key if unique is true
+ */
+ public IndexOrUniqueKeySecondPass(String indexName, Ejb3Column column,
+ ExtendedMappings mappings, boolean unique) {
+ this.indexName = indexName;
+ this.column = column;
+ this.columns = null;
+ this.mappings = mappings;
+ this.unique = unique;
+ }
+
+ public void doSecondPass(Map persistentClasses) throws MappingException {
+ if ( columns != null ) {
+ for (String columnName : columns) {
+ addConstraintToColumn( columnName );
+ }
+ }
+ if ( column != null ) {
+ this.table = column.getTable();
+ addConstraintToColumn( mappings.getLogicalColumnName( column.getMappingColumn().getQuotedName(), table ) );
+ }
+ }
+
+ private void addConstraintToColumn(String columnName) {
+ Column column = table.getColumn(
+ new Column(
+ mappings.getPhysicalColumnName( columnName, table )
+ )
+ );
+ if ( column == null ) {
+ throw new AnnotationException(
+ "@Index references a unknown column: " + columnName
+ );
+ }
+ if ( unique )
+ table.getOrCreateUniqueKey( indexName ).addColumn( column );
+ else
+ table.getOrCreateIndex( indexName ).addColumn( column );
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/InheritanceState.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/InheritanceState.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/InheritanceState.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,90 @@
+//$Id: InheritanceState.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.cfg;
+
+import java.util.Map;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+import javax.persistence.MappedSuperclass;
+
+import org.hibernate.annotations.common.reflection.ReflectionManager;
+import org.hibernate.annotations.common.reflection.XAnnotatedElement;
+import org.hibernate.annotations.common.reflection.XClass;
+
+/**
+ * Some extra data to the inheritance position of a class
+ *
+ * @author Emmanuel Bernard
+ */
+public class InheritanceState {
+ public InheritanceState(XClass clazz) {
+ this.clazz = clazz;
+ extractInheritanceType();
+ }
+
+ public XClass clazz;
+ /**
+ * has son either mappedsuperclass son or entity son
+ */
+ public boolean hasSons = false;
+ /**
+ * a mother entity is available
+ */
+ public boolean hasParents = false;
+ public InheritanceType type;
+ public boolean isEmbeddableSuperclass = false;
+
+ /**
+ * only defined on embedded superclasses
+ */
+ public String accessType = null;
+ public Boolean isPropertyAnnotated;
+
+ private void extractInheritanceType() {
+ XAnnotatedElement element = clazz;
+ Inheritance inhAnn = element.getAnnotation( Inheritance.class );
+ MappedSuperclass mappedSuperClass = element.getAnnotation( MappedSuperclass.class );
+ if ( mappedSuperClass != null ) {
+ isEmbeddableSuperclass = true;
+ type = inhAnn == null ? null : inhAnn.strategy();
+ }
+ else {
+ type = inhAnn == null ? InheritanceType.SINGLE_TABLE : inhAnn.strategy();
+ }
+ }
+
+ boolean hasTable() {
+ return !hasParents || !InheritanceType.SINGLE_TABLE.equals( type );
+ }
+
+ boolean hasDenormalizedTable() {
+ return hasParents && InheritanceType.TABLE_PER_CLASS.equals( type );
+ }
+
+ public static InheritanceState getSuperEntityInheritanceState(
+ XClass clazz, Map<XClass, InheritanceState> states,
+ ReflectionManager reflectionManager
+ ) {
+ XClass superclass = clazz;
+ do {
+ superclass = superclass.getSuperclass();
+ InheritanceState currentState = states.get( superclass );
+ if ( currentState != null && !currentState.isEmbeddableSuperclass ) return currentState;
+ }
+ while ( superclass != null && !reflectionManager.equals( superclass, Object.class ) );
+ return null;
+ }
+
+ public static InheritanceState getSuperclassInheritanceState(
+ XClass clazz, Map<XClass, InheritanceState> states,
+ ReflectionManager reflectionManager
+ ) {
+ XClass superclass = clazz;
+ do {
+ superclass = superclass.getSuperclass();
+ InheritanceState currentState = states.get( superclass );
+ if ( currentState != null ) return currentState;
+ }
+ while ( superclass != null && !reflectionManager.equals( superclass, Object.class ) );
+ return null;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/JoinedSubclassFkSecondPass.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/JoinedSubclassFkSecondPass.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/JoinedSubclassFkSecondPass.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,36 @@
+//$Id: JoinedSubclassFkSecondPass.java 14779 2008-06-18 17:56:27Z hardy.ferentschik $
+package org.hibernate.cfg;
+
+import java.util.Map;
+
+import org.hibernate.MappingException;
+import org.hibernate.cfg.annotations.TableBinder;
+import org.hibernate.mapping.JoinedSubclass;
+import org.hibernate.mapping.SimpleValue;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@SuppressWarnings({"serial", "unchecked"})
+public class JoinedSubclassFkSecondPass extends FkSecondPass {
+ private JoinedSubclass entity;
+ private ExtendedMappings mappings;
+
+ public JoinedSubclassFkSecondPass(JoinedSubclass entity, Ejb3JoinColumn[] inheritanceJoinedColumns, SimpleValue key, ExtendedMappings mappings) {
+ super( key, inheritanceJoinedColumns );
+ this.entity = entity;
+ this.mappings = mappings;
+ }
+
+ public String getReferencedEntityName() {
+ return entity.getSuperclass().getEntityName();
+ }
+
+ public boolean isInPrimaryKey() {
+ return true;
+ }
+
+ public void doSecondPass(Map persistentClasses) throws MappingException {
+ TableBinder.bindFk( entity.getSuperclass(), entity, columns, value, false, mappings );
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/NotYetImplementedException.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/NotYetImplementedException.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/NotYetImplementedException.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,25 @@
+//$Id: NotYetImplementedException.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.cfg;
+
+import org.hibernate.MappingException;
+
+/**
+ * Mapping not yet implemented
+ *
+ * @author Emmanuel Bernard
+ */
+public class NotYetImplementedException extends MappingException {
+
+ public NotYetImplementedException(String msg, Throwable root) {
+ super( msg, root );
+ }
+
+ public NotYetImplementedException(Throwable root) {
+ super( root );
+ }
+
+ public NotYetImplementedException(String s) {
+ super( s );
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/OneToOneSecondPass.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/OneToOneSecondPass.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/OneToOneSecondPass.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,263 @@
+//$Id: OneToOneSecondPass.java 14759 2008-06-10 14:14:15Z hardy.ferentschik $
+package org.hibernate.cfg;
+
+import java.util.Iterator;
+import java.util.Map;
+
+import org.hibernate.AnnotationException;
+import org.hibernate.MappingException;
+import org.hibernate.annotations.ForeignKey;
+import org.hibernate.annotations.common.reflection.XClass;
+import org.hibernate.cfg.annotations.PropertyBinder;
+import org.hibernate.mapping.Column;
+import org.hibernate.mapping.DependantValue;
+import org.hibernate.mapping.Join;
+import org.hibernate.mapping.ManyToOne;
+import org.hibernate.mapping.OneToOne;
+import org.hibernate.mapping.PersistentClass;
+import org.hibernate.mapping.Property;
+import org.hibernate.mapping.SimpleValue;
+import org.hibernate.type.ForeignKeyDirection;
+import org.hibernate.util.StringHelper;
+
+/**
+ * We have to handle OneToOne in a second pass because:
+ * -
+ */
+public class OneToOneSecondPass implements SecondPass {
+ private String mappedBy;
+ private ExtendedMappings mappings;
+ private String ownerEntity;
+ private String ownerProperty;
+ private PropertyHolder propertyHolder;
+ private boolean ignoreNotFound;
+ private PropertyData inferredData;
+ private XClass targetEntity;
+ private boolean cascadeOnDelete;
+ private boolean optional;
+ private String cascadeStrategy;
+ private Ejb3JoinColumn[] joinColumns;
+
+ //that suck, we should read that from the property mainly
+ public OneToOneSecondPass(
+ String mappedBy, String ownerEntity, String ownerProperty,
+ PropertyHolder propertyHolder, PropertyData inferredData, XClass targetEntity, boolean ignoreNotFound,
+ boolean cascadeOnDelete, boolean optional, String cascadeStrategy, Ejb3JoinColumn[] columns,
+ ExtendedMappings mappings
+ ) {
+ this.ownerEntity = ownerEntity;
+ this.ownerProperty = ownerProperty;
+ this.mappedBy = mappedBy;
+ this.propertyHolder = propertyHolder;
+ this.mappings = mappings;
+ this.ignoreNotFound = ignoreNotFound;
+ this.inferredData = inferredData;
+ this.targetEntity = targetEntity;
+ this.cascadeOnDelete = cascadeOnDelete;
+ this.optional = optional;
+ this.cascadeStrategy = cascadeStrategy;
+ this.joinColumns = columns;
+ }
+
+ //TODO refactor this code, there is a lot of duplication in this method
+ public void doSecondPass(Map persistentClasses) throws MappingException {
+ org.hibernate.mapping.OneToOne value = new org.hibernate.mapping.OneToOne(
+ propertyHolder.getTable(), propertyHolder.getPersistentClass()
+ );
+ final String propertyName = inferredData.getPropertyName();
+ value.setPropertyName( propertyName );
+ String referencedEntityName;
+ if ( AnnotationBinder.isDefault( targetEntity, mappings ) ) {
+ referencedEntityName = inferredData.getClassOrElementName();
+ }
+ else {
+ referencedEntityName = targetEntity.getName();
+ }
+ value.setReferencedEntityName( referencedEntityName );
+ AnnotationBinder.defineFetchingStrategy( value, inferredData.getProperty() );
+ //value.setFetchMode( fetchMode );
+ value.setCascadeDeleteEnabled( cascadeOnDelete );
+ //value.setLazy( fetchMode != FetchMode.JOIN );
+
+ if ( !optional ) value.setConstrained( true );
+ value.setForeignKeyType(
+ value.isConstrained() ?
+ ForeignKeyDirection.FOREIGN_KEY_FROM_PARENT :
+ ForeignKeyDirection.FOREIGN_KEY_TO_PARENT
+ );
+ PropertyBinder binder = new PropertyBinder();
+ binder.setName( propertyName );
+ binder.setValue( value );
+ binder.setCascade( cascadeStrategy );
+ binder.setPropertyAccessorName( inferredData.getDefaultAccess() );
+ Property prop = binder.make();
+ if ( BinderHelper.isDefault( mappedBy ) ) {
+ /*
+ * we need to check if the columns are in the right order
+ * if not, then we need to create a many to one and formula
+ * but actually, since entities linked by a one to one need
+ * to share the same composite id class, this cannot happen in hibernate
+ */
+ boolean rightOrder = true;
+
+ if ( rightOrder ) {
+ String path = StringHelper.qualify( propertyHolder.getPath(), propertyName );
+ ( new ToOneFkSecondPass(
+ value, joinColumns,
+ !optional, //cannot have nullabe and unique on certain DBs
+ propertyHolder.getEntityOwnerClassName(),
+ path, mappings
+ ) ).doSecondPass( persistentClasses );
+ //no column associated since its a one to one
+ propertyHolder.addProperty( prop );
+ }
+ else {
+ //this is a many to one with Formula
+
+ }
+ }
+ else {
+ PersistentClass otherSide = (PersistentClass) persistentClasses.get( value.getReferencedEntityName() );
+ Property otherSideProperty;
+ try {
+ if ( otherSide == null ) {
+ throw new MappingException( "Unable to find entity: " + value.getReferencedEntityName() );
+ }
+ otherSideProperty = BinderHelper.findPropertyByName( otherSide, mappedBy );
+ }
+ catch (MappingException e) {
+ throw new AnnotationException(
+ "Unknown mappedBy in: " + StringHelper.qualify( ownerEntity, ownerProperty )
+ + ", referenced property unknown: "
+ + StringHelper.qualify( value.getReferencedEntityName(), mappedBy )
+ );
+ }
+ if ( otherSideProperty == null ) {
+ throw new AnnotationException(
+ "Unknown mappedBy in: " + StringHelper.qualify( ownerEntity, ownerProperty )
+ + ", referenced property unknown: "
+ + StringHelper.qualify( value.getReferencedEntityName(), mappedBy )
+ );
+ }
+ if ( otherSideProperty.getValue() instanceof OneToOne ) {
+ propertyHolder.addProperty( prop );
+ }
+ else if ( otherSideProperty.getValue() instanceof ManyToOne ) {
+ Iterator it = otherSide.getJoinIterator();
+ Join otherSideJoin = null;
+ while ( it.hasNext() ) {
+ otherSideJoin = (Join) it.next();
+ if ( otherSideJoin.containsProperty( otherSideProperty ) ) {
+ break;
+ }
+ }
+ if ( otherSideJoin != null ) {
+ //@OneToOne @JoinTable
+ Join mappedByJoin = buildJoinFromMappedBySide(
+ (PersistentClass) persistentClasses.get( ownerEntity ), otherSideProperty, otherSideJoin
+ );
+ ManyToOne manyToOne = new ManyToOne( mappedByJoin.getTable() );
+ //FIXME use ignore not found here
+ manyToOne.setIgnoreNotFound( ignoreNotFound );
+ manyToOne.setCascadeDeleteEnabled( value.isCascadeDeleteEnabled() );
+ manyToOne.setEmbedded( value.isEmbedded() );
+ manyToOne.setFetchMode( value.getFetchMode() );
+ manyToOne.setLazy( value.isLazy() );
+ manyToOne.setReferencedEntityName( value.getReferencedEntityName() );
+ manyToOne.setUnwrapProxy( value.isUnwrapProxy() );
+ prop.setValue( manyToOne );
+ Iterator otherSideJoinKeyColumns = otherSideJoin.getKey().getColumnIterator();
+ while ( otherSideJoinKeyColumns.hasNext() ) {
+ Column column = (Column) otherSideJoinKeyColumns.next();
+ Column copy = new Column();
+ copy.setLength( column.getLength() );
+ copy.setScale( column.getScale() );
+ copy.setValue( manyToOne );
+ copy.setName( column.getQuotedName() );
+ copy.setNullable( column.isNullable() );
+ copy.setPrecision( column.getPrecision() );
+ copy.setUnique( column.isUnique() );
+ copy.setSqlType( column.getSqlType() );
+ copy.setCheckConstraint( column.getCheckConstraint() );
+ copy.setComment( column.getComment() );
+ copy.setDefaultValue( column.getDefaultValue() );
+ manyToOne.addColumn( copy );
+ }
+ mappedByJoin.addProperty( prop );
+ }
+ else {
+ propertyHolder.addProperty( prop );
+ }
+
+ value.setReferencedPropertyName( mappedBy );
+
+ String propertyRef = value.getReferencedPropertyName();
+ if ( propertyRef != null ) {
+ mappings.addUniquePropertyReference(
+ value.getReferencedEntityName(),
+ propertyRef
+ );
+ }
+ }
+ else {
+ throw new AnnotationException(
+ "Referenced property not a (One|Many)ToOne: "
+ + StringHelper.qualify(
+ otherSide.getEntityName(), mappedBy
+ )
+ + " in mappedBy of "
+ + StringHelper.qualify( ownerEntity, ownerProperty )
+ );
+ }
+ }
+ ForeignKey fk = inferredData.getProperty().getAnnotation( ForeignKey.class );
+ String fkName = fk != null ? fk.name() : "";
+ if ( !BinderHelper.isDefault( fkName ) ) value.setForeignKeyName( fkName );
+ }
+
+ /**
+ * Builds the <code>Join</code> instance for the mapped by side of a <i>OneToOne</i> association using
+ * a join tables.
+ * <p>
+ * Note:<br/>
+ * <ul>
+ * <li>From the mappedBy side we should not create the PK nor the FK, this is handled from the other side.</li>
+ * <li>This method is a dirty dupe of EntityBinder.bindSecondaryTable</i>.
+ * </p>
+ */
+ private Join buildJoinFromMappedBySide(PersistentClass persistentClass, Property otherSideProperty, Join originalJoin) {
+ Join join = new Join();
+ join.setPersistentClass( persistentClass );
+
+ //no check constraints available on joins
+ join.setTable( originalJoin.getTable() );
+ join.setInverse( true );
+ SimpleValue key = new DependantValue( join.getTable(), persistentClass.getIdentifier() );
+ //TODO support @ForeignKey
+ join.setKey( key );
+ join.setSequentialSelect( false );
+ //TODO support for inverse and optional
+ join.setOptional( true ); //perhaps not quite per-spec, but a Good Thing anyway
+ key.setCascadeDeleteEnabled( false );
+ Iterator mappedByColumns = otherSideProperty.getValue().getColumnIterator();
+ while ( mappedByColumns.hasNext() ) {
+ Column column = (Column) mappedByColumns.next();
+ Column copy = new Column();
+ copy.setLength( column.getLength() );
+ copy.setScale( column.getScale() );
+ copy.setValue( key );
+ copy.setName( column.getQuotedName() );
+ copy.setNullable( column.isNullable() );
+ copy.setPrecision( column.getPrecision() );
+ copy.setUnique( column.isUnique() );
+ copy.setSqlType( column.getSqlType() );
+ copy.setCheckConstraint( column.getCheckConstraint() );
+ copy.setComment( column.getComment() );
+ copy.setDefaultValue( column.getDefaultValue() );
+ key.addColumn( copy );
+ }
+ persistentClass.addJoin( join );
+ return join;
+ }
+}
+
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/PropertyData.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/PropertyData.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/PropertyData.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,42 @@
+package org.hibernate.cfg;
+
+import org.hibernate.MappingException;
+import org.hibernate.annotations.common.reflection.XClass;
+import org.hibernate.annotations.common.reflection.XProperty;
+
+public interface PropertyData {
+
+ /**
+ * @return default member access (whether field or property)
+ * @throws MappingException No getter or field found or wrong JavaBean spec usage
+ */
+ public String getDefaultAccess();
+
+ /**
+ * @return property name
+ * @throws MappingException No getter or field found or wrong JavaBean spec usage
+ */
+ public String getPropertyName() throws MappingException;
+
+ /**
+ * Returns the returned class itself or the element type if an array
+ */
+ public XClass getClassOrElement() throws MappingException;
+
+ /**
+ * Return the class itself
+ */
+ public XClass getPropertyClass() throws MappingException;
+
+ /**
+ * Returns the returned class name itself or the element type if an array
+ */
+ public String getClassOrElementName() throws MappingException;
+
+ /**
+ * Returns the returned class name itself
+ */
+ public String getTypeName() throws MappingException;
+
+ public XProperty getProperty();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/PropertyHolder.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/PropertyHolder.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/PropertyHolder.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,54 @@
+package org.hibernate.cfg;
+
+import javax.persistence.Column;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinTable;
+
+import org.hibernate.mapping.Join;
+import org.hibernate.mapping.KeyValue;
+import org.hibernate.mapping.PersistentClass;
+import org.hibernate.mapping.Property;
+import org.hibernate.mapping.Table;
+
+/**
+ * Property holder abstract property containers from their direct implementation
+ *
+ * @author Emmanuel Bernard
+ */
+public interface PropertyHolder {
+ String getClassName();
+
+ String getEntityOwnerClassName();
+
+ Table getTable();
+
+ void addProperty(Property prop);
+
+ KeyValue getIdentifier();
+
+ PersistentClass getPersistentClass();
+
+ boolean isComponent();
+
+ boolean isEntity();
+
+ void setParentProperty(String parentProperty);
+
+ String getPath();
+
+ /**
+ * return null if the column is not overridden, or an array of column if true
+ */
+ Column[] getOverriddenColumn(String propertyName);
+
+ /**
+ * return null if the column is not overridden, or an array of column if true
+ */
+ JoinColumn[] getOverriddenJoinColumn(String propertyName);
+
+ String getEntityName();
+
+ void addProperty(Property prop, Ejb3Column[] columns);
+
+ Join addJoin(JoinTable joinTableAnn, boolean noDelayInPkColumnCreation);
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/PropertyHolderBuilder.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/PropertyHolderBuilder.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/PropertyHolderBuilder.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,67 @@
+//$Id: PropertyHolderBuilder.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.cfg;
+
+import java.util.Map;
+
+import org.hibernate.annotations.common.reflection.XClass;
+import org.hibernate.annotations.common.reflection.XProperty;
+import org.hibernate.cfg.annotations.EntityBinder;
+import org.hibernate.mapping.Collection;
+import org.hibernate.mapping.Component;
+import org.hibernate.mapping.Join;
+import org.hibernate.mapping.PersistentClass;
+
+/**
+ * This factory is here ot build a PropertyHolder and prevent .mapping interface adding
+ *
+ * @author Emmanuel Bernard
+ */
+public final class PropertyHolderBuilder {
+ private PropertyHolderBuilder() {
+ }
+
+ public static PropertyHolder buildPropertyHolder(
+ XClass clazzToProcess,
+ PersistentClass persistentClass,
+ EntityBinder entityBinder,
+ //Map<String, Join> joins,
+ ExtendedMappings mappings
+ ) {
+ return new ClassPropertyHolder( persistentClass, clazzToProcess, entityBinder, mappings );
+ }
+
+ /**
+ * build a component property holder
+ *
+ * @param component component to wrap
+ * @param path component path
+ * @param mappings
+ * @return PropertyHolder
+ */
+ public static PropertyHolder buildPropertyHolder(
+ Component component, String path, PropertyData inferredData, PropertyHolder parent,
+ ExtendedMappings mappings
+ ) {
+ return new ComponentPropertyHolder( component, path, inferredData, parent, mappings );
+ }
+
+ /**
+ * buid a property holder on top of a collection
+ */
+ public static PropertyHolder buildPropertyHolder(
+ Collection collection, String path, XClass clazzToProcess, XProperty property,
+ PropertyHolder parentPropertyHolder, ExtendedMappings mappings
+ ) {
+ return new CollectionPropertyHolder( collection, path, clazzToProcess, property, parentPropertyHolder, mappings );
+ }
+
+ /**
+ * must only be used on second level phases (<join> has to be settled already)
+ */
+ public static PropertyHolder buildPropertyHolder(
+ PersistentClass persistentClass, Map<String, Join> joins,
+ ExtendedMappings mappings
+ ) {
+ return new ClassPropertyHolder( persistentClass, null, joins, mappings );
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/PropertyInferredData.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/PropertyInferredData.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/PropertyInferredData.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,72 @@
+//$Id: PropertyInferredData.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.cfg;
+
+import org.hibernate.MappingException;
+import org.hibernate.annotations.AccessType;
+import org.hibernate.annotations.Target;
+import org.hibernate.annotations.common.reflection.ReflectionManager;
+import org.hibernate.annotations.common.reflection.XClass;
+import org.hibernate.annotations.common.reflection.XProperty;
+
+/**
+ * Retrieve all inferred data from an annnoted element
+ *
+ * @author Emmanuel Bernard
+ * @author Paolo Perrotta
+ */
+public class PropertyInferredData implements PropertyData {
+ private final String defaultAccess;
+
+ private final XProperty property;
+ private final ReflectionManager reflectionManager;
+
+ /**
+ * Take the annoted element for lazy process
+ */
+ public PropertyInferredData(XProperty property, String propertyAccessor, ReflectionManager reflectionManager) {
+ this.property = property;
+ this.defaultAccess = propertyAccessor;
+ this.reflectionManager = reflectionManager;
+ }
+
+ public String getDefaultAccess() throws MappingException {
+ // if(skip())
+ // return defaultAccess;
+ AccessType access = property.getAnnotation( AccessType.class );
+ return access != null ? access.value() : defaultAccess;
+ }
+
+ public String getPropertyName() throws MappingException {
+ return property.getName();
+ }
+
+ public XClass getPropertyClass() throws MappingException {
+ if ( property.isAnnotationPresent( Target.class ) ) {
+ return reflectionManager.toXClass( property.getAnnotation( Target.class ).value() );
+ }
+ else {
+ return property.getType();
+ }
+ }
+
+ public XClass getClassOrElement() throws MappingException {
+ if ( property.isAnnotationPresent( Target.class ) ) {
+ return reflectionManager.toXClass( property.getAnnotation( Target.class ).value() );
+ }
+ else {
+ return property.getClassOrElementClass();
+ }
+ }
+
+ public String getClassOrElementName() throws MappingException {
+ return getClassOrElement().getName();
+ }
+
+ public String getTypeName() throws MappingException {
+ return getPropertyClass().getName();
+ }
+
+ public XProperty getProperty() {
+ return property;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/PropertyPreloadedData.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/PropertyPreloadedData.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/PropertyPreloadedData.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,48 @@
+//$Id: PropertyPreloadedData.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.cfg;
+
+import org.hibernate.MappingException;
+import org.hibernate.annotations.common.reflection.XClass;
+import org.hibernate.annotations.common.reflection.XProperty;
+
+public class PropertyPreloadedData implements PropertyData {
+ private final String defaultAccess;
+
+ private final String propertyName;
+
+ private final XClass returnedClass;
+
+ public PropertyPreloadedData(String defaultAccess, String propertyName, XClass returnedClass) {
+ this.defaultAccess = defaultAccess;
+ this.propertyName = propertyName;
+ this.returnedClass = returnedClass;
+ }
+
+ public String getDefaultAccess() throws MappingException {
+ return defaultAccess;
+ }
+
+ public String getPropertyName() throws MappingException {
+ return propertyName;
+ }
+
+ public XClass getClassOrElement() throws MappingException {
+ return getPropertyClass();
+ }
+
+ public XClass getPropertyClass() throws MappingException {
+ return returnedClass;
+ }
+
+ public String getClassOrElementName() throws MappingException {
+ return getTypeName();
+ }
+
+ public String getTypeName() throws MappingException {
+ return returnedClass == null ? null : returnedClass.getName();
+ }
+
+ public XProperty getProperty() {
+ return null; //instead of UnsupportedOperationException
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/RecoverableException.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/RecoverableException.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/RecoverableException.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,25 @@
+//$
+package org.hibernate.cfg;
+
+import org.hibernate.AnnotationException;
+
+/**
+ * Should neven be exposed to the client
+ * An exception that wrap an underlying exception whith the hope
+ * subsequent processing will recover from it.
+ *
+ * @author Emmanuel Bernard
+ */
+public class RecoverableException extends AnnotationException {
+ public RecoverableException(String msg, Throwable root) {
+ super( msg, root );
+ }
+
+ public RecoverableException(Throwable root) {
+ super( root );
+ }
+
+ public RecoverableException(String s) {
+ super( s );
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/SecondaryTableSecondPass.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/SecondaryTableSecondPass.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/SecondaryTableSecondPass.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,28 @@
+//$Id: SecondaryTableSecondPass.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.cfg;
+
+import java.util.Map;
+
+import org.hibernate.MappingException;
+import org.hibernate.annotations.common.reflection.XAnnotatedElement;
+import org.hibernate.cfg.annotations.EntityBinder;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class SecondaryTableSecondPass implements SecondPass {
+ private EntityBinder entityBinder;
+ private PropertyHolder propertyHolder;
+ private XAnnotatedElement annotatedClass;
+
+ public SecondaryTableSecondPass(EntityBinder entityBinder, PropertyHolder propertyHolder, XAnnotatedElement annotatedClass) {
+ this.entityBinder = entityBinder;
+ this.propertyHolder = propertyHolder;
+ this.annotatedClass = annotatedClass;
+ }
+
+ public void doSecondPass(Map persistentClasses) throws MappingException {
+ entityBinder.finalSecondaryTableBinding( propertyHolder );
+
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/ToOneFkSecondPass.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/ToOneFkSecondPass.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/ToOneFkSecondPass.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,102 @@
+// $Id: ToOneFkSecondPass.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.cfg;
+
+import java.util.Iterator;
+
+import org.hibernate.AnnotationException;
+import org.hibernate.AssertionFailure;
+import org.hibernate.MappingException;
+import org.hibernate.cfg.annotations.TableBinder;
+import org.hibernate.mapping.ManyToOne;
+import org.hibernate.mapping.OneToOne;
+import org.hibernate.mapping.PersistentClass;
+import org.hibernate.mapping.Property;
+import org.hibernate.mapping.ToOne;
+import org.hibernate.mapping.KeyValue;
+import org.hibernate.mapping.Component;
+import org.hibernate.util.StringHelper;
+
+/**
+ * Enable a proper set of the FK columns in respect with the id column order
+ * Allow the correct implementation of the default EJB3 values which needs both
+ * sides of the association to be resolved
+ *
+ * @author Emmanuel Bernard
+ */
+public class ToOneFkSecondPass extends FkSecondPass {
+ private boolean unique;
+ private ExtendedMappings mappings;
+ private String path;
+ private String entityClassName;
+
+ public ToOneFkSecondPass(
+ ToOne value, Ejb3JoinColumn[] columns, boolean unique, String entityClassName, String path, ExtendedMappings mappings
+ ) {
+ super( value, columns );
+ this.mappings = mappings;
+ this.unique = unique;
+ this.entityClassName = entityClassName;
+ this.path = entityClassName != null ? path.substring( entityClassName.length() + 1 ) : path;
+ }
+
+ public String getReferencedEntityName() {
+ return ( (ToOne) value ).getReferencedEntityName();
+ }
+
+ public boolean isInPrimaryKey() {
+ if ( entityClassName == null ) return false;
+ final PersistentClass persistentClass = mappings.getClass( entityClassName );
+ Property property = persistentClass.getIdentifierProperty();
+ if ( path == null ) {
+ return false;
+ }
+ else if ( property != null) {
+ //try explicit identifier property
+ return path.startsWith( property.getName() + "." );
+ }
+ else {
+ //try the embedded property
+ //embedded property starts their path with 'id.' See PropertyPreloadedData( ) use when idClass != null in AnnotationBinder
+ if ( path.startsWith( "id." ) ) {
+ KeyValue valueIdentifier = persistentClass.getIdentifier();
+ String localPath = path.substring( 3 );
+ if ( valueIdentifier instanceof Component ) {
+ Iterator it = ( (Component) valueIdentifier ).getPropertyIterator();
+ while ( it.hasNext() ) {
+ Property idProperty = (Property) it.next();
+ if ( localPath.startsWith( idProperty.getName() ) ) return true;
+ }
+
+ }
+ }
+ }
+ return false;
+ }
+
+ public void doSecondPass(java.util.Map persistentClasses) throws MappingException {
+ if ( value instanceof ManyToOne ) {
+ ManyToOne manyToOne = (ManyToOne) value;
+ PersistentClass ref = (PersistentClass) persistentClasses.get( manyToOne.getReferencedEntityName() );
+ if ( ref == null ) {
+ throw new AnnotationException(
+ "@OneToOne or @ManyToOne on "
+ + StringHelper.qualify( entityClassName, path )
+ + " references an unknown entity: "
+ + manyToOne.getReferencedEntityName()
+ );
+ }
+ BinderHelper.createSyntheticPropertyReference( columns, ref, null, manyToOne, false, mappings );
+ TableBinder.bindFk( ref, null, columns, manyToOne, unique, mappings );
+ /*
+ * HbmBinder does this only when property-ref != null, but IMO, it makes sense event if it is null
+ */
+ if ( !manyToOne.isIgnoreNotFound() ) manyToOne.createPropertyRefConstraints( persistentClasses );
+ }
+ else if ( value instanceof OneToOne ) {
+ ( (OneToOne) value ).createForeignKey();
+ }
+ else {
+ throw new AssertionFailure( "FkSecondPass for a wrong value type: " + value.getClass().getName() );
+ }
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/WrappedInferredData.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/WrappedInferredData.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/WrappedInferredData.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,48 @@
+//$Id: WrappedInferredData.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.cfg;
+
+import org.hibernate.MappingException;
+import org.hibernate.annotations.common.reflection.XClass;
+import org.hibernate.annotations.common.reflection.XProperty;
+import org.hibernate.util.StringHelper;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class WrappedInferredData implements PropertyData {
+ private PropertyData wrappedInferredData;
+ private String propertyName;
+
+ public XClass getClassOrElement() throws MappingException {
+ return wrappedInferredData.getClassOrElement();
+ }
+
+ public String getClassOrElementName() throws MappingException {
+ return wrappedInferredData.getClassOrElementName();
+ }
+
+ public String getDefaultAccess() {
+ return wrappedInferredData.getDefaultAccess();
+ }
+
+ public XProperty getProperty() {
+ return wrappedInferredData.getProperty();
+ }
+
+ public XClass getPropertyClass() throws MappingException {
+ return wrappedInferredData.getPropertyClass();
+ }
+
+ public String getPropertyName() throws MappingException {
+ return propertyName;
+ }
+
+ public String getTypeName() throws MappingException {
+ return wrappedInferredData.getTypeName();
+ }
+
+ public WrappedInferredData(PropertyData inferredData, String suffix) {
+ this.wrappedInferredData = inferredData;
+ this.propertyName = StringHelper.qualify( inferredData.getPropertyName(), suffix );
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/ArrayBinder.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/ArrayBinder.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/ArrayBinder.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,20 @@
+package org.hibernate.cfg.annotations;
+
+import org.hibernate.mapping.Array;
+import org.hibernate.mapping.Collection;
+import org.hibernate.mapping.PersistentClass;
+
+/**
+ * Bind an Array
+ *
+ * @author Anthony Patricio
+ */
+public class ArrayBinder extends ListBinder {
+
+ public ArrayBinder() {
+ }
+
+ protected Collection createCollection(PersistentClass persistentClass) {
+ return new Array( persistentClass );
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/BagBinder.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/BagBinder.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/BagBinder.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,19 @@
+package org.hibernate.cfg.annotations;
+
+import org.hibernate.mapping.Collection;
+import org.hibernate.mapping.PersistentClass;
+
+/**
+ * Bind a bag.
+ *
+ * @author Matthew Inger
+ */
+public class BagBinder extends CollectionBinder {
+
+ public BagBinder() {
+ }
+
+ protected Collection createCollection(PersistentClass persistentClass) {
+ return new org.hibernate.mapping.Bag( persistentClass );
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/CollectionBinder.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/CollectionBinder.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/CollectionBinder.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,1429 @@
+package org.hibernate.cfg.annotations;
+
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.StringTokenizer;
+import javax.persistence.AttributeOverride;
+import javax.persistence.AttributeOverrides;
+import javax.persistence.Embeddable;
+import javax.persistence.FetchType;
+import javax.persistence.JoinTable;
+import javax.persistence.ManyToMany;
+import javax.persistence.MapKey;
+import javax.persistence.OneToMany;
+
+import org.hibernate.AnnotationException;
+import org.hibernate.AssertionFailure;
+import org.hibernate.FetchMode;
+import org.hibernate.MappingException;
+import org.hibernate.annotations.BatchSize;
+import org.hibernate.annotations.Cache;
+import org.hibernate.annotations.CollectionId;
+import org.hibernate.annotations.CollectionOfElements;
+import org.hibernate.annotations.Fetch;
+import org.hibernate.annotations.Filter;
+import org.hibernate.annotations.FilterJoinTable;
+import org.hibernate.annotations.FilterJoinTables;
+import org.hibernate.annotations.Filters;
+import org.hibernate.annotations.ForeignKey;
+import org.hibernate.annotations.Immutable;
+import org.hibernate.annotations.LazyCollection;
+import org.hibernate.annotations.LazyCollectionOption;
+import org.hibernate.annotations.Loader;
+import org.hibernate.annotations.ManyToAny;
+import org.hibernate.annotations.OptimisticLock;
+import org.hibernate.annotations.OrderBy;
+import org.hibernate.annotations.Persister;
+import org.hibernate.annotations.SQLDelete;
+import org.hibernate.annotations.SQLDeleteAll;
+import org.hibernate.annotations.SQLInsert;
+import org.hibernate.annotations.SQLUpdate;
+import org.hibernate.annotations.Sort;
+import org.hibernate.annotations.SortType;
+import org.hibernate.annotations.Where;
+import org.hibernate.annotations.WhereJoinTable;
+import org.hibernate.annotations.common.reflection.XClass;
+import org.hibernate.annotations.common.reflection.XProperty;
+import org.hibernate.cfg.AnnotatedClassType;
+import org.hibernate.cfg.AnnotationBinder;
+import org.hibernate.cfg.BinderHelper;
+import org.hibernate.cfg.CollectionSecondPass;
+import org.hibernate.cfg.Ejb3Column;
+import org.hibernate.cfg.Ejb3JoinColumn;
+import org.hibernate.cfg.ExtendedMappings;
+import org.hibernate.cfg.IndexColumn;
+import org.hibernate.cfg.PropertyData;
+import org.hibernate.cfg.PropertyHolder;
+import org.hibernate.cfg.PropertyHolderBuilder;
+import org.hibernate.cfg.PropertyInferredData;
+import org.hibernate.cfg.PropertyPreloadedData;
+import org.hibernate.cfg.SecondPass;
+import org.hibernate.engine.ExecuteUpdateResultCheckStyle;
+import org.hibernate.mapping.Any;
+import org.hibernate.mapping.Backref;
+import org.hibernate.mapping.Collection;
+import org.hibernate.mapping.Column;
+import org.hibernate.mapping.Component;
+import org.hibernate.mapping.DependantValue;
+import org.hibernate.mapping.IdGenerator;
+import org.hibernate.mapping.Join;
+import org.hibernate.mapping.KeyValue;
+import org.hibernate.mapping.ManyToOne;
+import org.hibernate.mapping.PersistentClass;
+import org.hibernate.mapping.Property;
+import org.hibernate.mapping.Selectable;
+import org.hibernate.mapping.SimpleValue;
+import org.hibernate.mapping.SingleTableSubclass;
+import org.hibernate.mapping.Table;
+import org.hibernate.util.StringHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Base class for binding different types of collections to Hibernate configuration objects.
+ *
+ * @author inger
+ * @author Emmanuel Bernard
+ */
+@SuppressWarnings({"unchecked", "serial"})
+public abstract class CollectionBinder {
+
+ private Logger log = LoggerFactory.getLogger( CollectionBinder.class );
+
+ protected Collection collection;
+ protected String propertyName;
+ PropertyHolder propertyHolder;
+ int batchSize;
+ private String mappedBy;
+ private XClass collectionType;
+ private XClass targetEntity;
+ private ExtendedMappings mappings;
+ private Ejb3JoinColumn[] inverseJoinColumns;
+ private String cascadeStrategy;
+ String cacheConcurrencyStrategy;
+ String cacheRegionName;
+ private boolean oneToMany;
+ protected IndexColumn indexColumn;
+ private String orderBy;
+ protected String hqlOrderBy;
+ private boolean isSorted;
+ private Class comparator;
+ private boolean hasToBeSorted;
+ protected boolean cascadeDeleteEnabled;
+ protected String mapKeyPropertyName;
+ private boolean insertable = true;
+ private boolean updatable = true;
+ private Ejb3JoinColumn[] fkJoinColumns;
+ private boolean isExplicitAssociationTable;
+ private Ejb3Column[] elementColumns;
+ private boolean isEmbedded;
+ private XProperty property;
+ private boolean ignoreNotFound;
+ private TableBinder tableBinder;
+ private Ejb3Column[] mapKeyColumns;
+ private Ejb3JoinColumn[] mapKeyManyToManyColumns;
+ protected HashMap<String, IdGenerator> localGenerators;
+
+ public void setUpdatable(boolean updatable) {
+ this.updatable = updatable;
+ }
+
+ public void setInsertable(boolean insertable) {
+ this.insertable = insertable;
+ }
+
+
+ public void setCascadeStrategy(String cascadeStrategy) {
+ this.cascadeStrategy = cascadeStrategy;
+ }
+
+ public void setPropertyAccessorName(String propertyAccessorName) {
+ this.propertyAccessorName = propertyAccessorName;
+ }
+
+ private String propertyAccessorName;
+
+ public void setInverseJoinColumns(Ejb3JoinColumn[] inverseJoinColumns) {
+ this.inverseJoinColumns = inverseJoinColumns;
+ }
+
+ public void setJoinColumns(Ejb3JoinColumn[] joinColumns) {
+ this.joinColumns = joinColumns;
+ }
+
+ private Ejb3JoinColumn[] joinColumns;
+
+ public void setPropertyHolder(PropertyHolder propertyHolder) {
+ this.propertyHolder = propertyHolder;
+ }
+
+ public void setBatchSize(BatchSize batchSize) {
+ this.batchSize = batchSize == null ? -1 : batchSize.size();
+ }
+
+ public void setEjb3OrderBy(javax.persistence.OrderBy orderByAnn) {
+ if ( orderByAnn != null ) {
+ hqlOrderBy = orderByAnn.value();
+ }
+ }
+
+ public void setSqlOrderBy(OrderBy orderByAnn) {
+ if ( orderByAnn != null ) {
+ if ( !BinderHelper.isDefault( orderByAnn.clause() ) ) orderBy = orderByAnn.clause();
+ }
+ }
+
+ public void setSort(Sort sortAnn) {
+ if ( sortAnn != null ) {
+ isSorted = !SortType.UNSORTED.equals( sortAnn.type() );
+ if ( isSorted && SortType.COMPARATOR.equals( sortAnn.type() ) ) {
+ comparator = sortAnn.comparator();
+ }
+ }
+ }
+
+ /**
+ * collection binder factory
+ */
+ public static CollectionBinder getCollectionBinder(
+ String entityName, XProperty property,
+ boolean isIndexed
+ ) {
+ if ( property.isArray() ) {
+ if ( property.getElementClass().isPrimitive() ) {
+ return new PrimitiveArrayBinder();
+ }
+ else {
+ return new ArrayBinder();
+ }
+ }
+ else if ( property.isCollection() ) {
+ //TODO consider using an XClass
+ Class returnedClass = property.getCollectionClass();
+ if ( java.util.Set.class.equals( returnedClass ) ) {
+ if ( property.isAnnotationPresent( CollectionId.class ) ) {
+ throw new AnnotationException( "Set do not support @CollectionId: "
+ + StringHelper.qualify( entityName, property.getName() ) );
+ }
+ return new SetBinder();
+ }
+ else if ( java.util.SortedSet.class.equals( returnedClass ) ) {
+ if ( property.isAnnotationPresent( CollectionId.class ) ) {
+ throw new AnnotationException( "Set do not support @CollectionId: "
+ + StringHelper.qualify( entityName, property.getName() ) );
+ }
+ return new SetBinder( true );
+ }
+ else if ( java.util.Map.class.equals( returnedClass ) ) {
+ if ( property.isAnnotationPresent( CollectionId.class ) ) {
+ throw new AnnotationException( "Map do not support @CollectionId: "
+ + StringHelper.qualify( entityName, property.getName() ) );
+ }
+ return new MapBinder();
+ }
+ else if ( java.util.SortedMap.class.equals( returnedClass ) ) {
+ if ( property.isAnnotationPresent( CollectionId.class ) ) {
+ throw new AnnotationException( "Map do not support @CollectionId: "
+ + StringHelper.qualify( entityName, property.getName() ) );
+ }
+ return new MapBinder( true );
+ }
+ else if ( java.util.Collection.class.equals( returnedClass ) ) {
+ if ( property.isAnnotationPresent( CollectionId.class ) ) {
+ return new IdBagBinder();
+ }
+ else {
+ return new BagBinder();
+ }
+ }
+ else if ( java.util.List.class.equals( returnedClass ) ) {
+ if ( isIndexed ) {
+ if ( property.isAnnotationPresent( CollectionId.class ) ) {
+ throw new AnnotationException( "List do not support @CollectionId and @IndexColumn at the same time: "
+ + StringHelper.qualify( entityName, property.getName() ) );
+ }
+ return new ListBinder();
+ }
+ else if ( property.isAnnotationPresent( CollectionId.class ) ) {
+ return new IdBagBinder();
+ }
+ else {
+ return new BagBinder();
+ }
+ }
+ else {
+ throw new AnnotationException(
+ returnedClass.getName() + " collection not yet supported: "
+ + StringHelper.qualify( entityName, property.getName() )
+ );
+ }
+ }
+ else {
+ throw new AnnotationException(
+ "Illegal attempt to map a non collection as a @OneToMany, @ManyToMany or @CollectionOfElements: "
+ + StringHelper.qualify( entityName, property.getName() )
+ );
+ }
+ }
+
+ protected CollectionBinder() {
+ }
+
+ protected CollectionBinder(boolean sorted) {
+ this.hasToBeSorted = sorted;
+ }
+
+ public void setMappedBy(String mappedBy) {
+ this.mappedBy = mappedBy;
+ }
+
+ public void setTableBinder(TableBinder tableBinder) {
+ this.tableBinder = tableBinder;
+ }
+
+ public void setCollectionType(XClass collectionType) {
+ this.collectionType = collectionType;
+ }
+
+ public void setTargetEntity(XClass targetEntity) {
+ this.targetEntity = targetEntity;
+ }
+
+ public void setMappings(ExtendedMappings mappings) {
+ this.mappings = mappings;
+ }
+
+ protected abstract Collection createCollection(PersistentClass persistentClass);
+
+ public Collection getCollection() {
+ return collection;
+ }
+
+ public void setPropertyName(String propertyName) {
+ this.propertyName = propertyName;
+ }
+
+ public void bind() {
+ this.collection = createCollection( propertyHolder.getPersistentClass() );
+ log.debug( "Collection role: {}", StringHelper.qualify( propertyHolder.getPath(), propertyName ) );
+ collection.setRole( StringHelper.qualify( propertyHolder.getPath(), propertyName ) );
+ collection.setNodeName( propertyName );
+
+ if ( property.isAnnotationPresent( org.hibernate.annotations.MapKey.class ) && mapKeyPropertyName != null ) {
+ throw new AnnotationException(
+ "Cannot mix @javax.persistence.MapKey and @org.hibernate.annotations.MapKey "
+ + "on the same collection: " + StringHelper.qualify(
+ propertyHolder.getPath(), propertyName
+ )
+ );
+ }
+
+ //set laziness
+ defineFetchingStrategy();
+ collection.setBatchSize( batchSize );
+ if ( orderBy != null && hqlOrderBy != null ) {
+ throw new AnnotationException(
+ "Cannot use sql order by clause in conjunction of EJB3 order by clause: " + safeCollectionRole()
+ );
+ }
+
+ collection.setMutable( !property.isAnnotationPresent( Immutable.class ) );
+ OptimisticLock lockAnn = property.getAnnotation( OptimisticLock.class );
+ if ( lockAnn != null ) collection.setOptimisticLocked( !lockAnn.excluded() );
+ Persister persisterAnn = property.getAnnotation( Persister.class );
+ if ( persisterAnn != null ) collection.setCollectionPersisterClass( persisterAnn.impl() );
+
+ // set ordering
+ if ( orderBy != null ) collection.setOrderBy( orderBy );
+ if ( isSorted ) {
+ collection.setSorted( true );
+ if ( comparator != null ) {
+ try {
+ collection.setComparator( (Comparator) comparator.newInstance() );
+ }
+ catch (ClassCastException e) {
+ throw new AnnotationException(
+ "Comparator not implementing java.util.Comparator class: "
+ + comparator.getName() + "(" + safeCollectionRole() + ")"
+ );
+ }
+ catch (Exception e) {
+ throw new AnnotationException(
+ "Could not instantiate comparator class: "
+ + comparator.getName() + "(" + safeCollectionRole() + ")"
+ );
+ }
+ }
+ }
+ else {
+ if ( hasToBeSorted ) {
+ throw new AnnotationException(
+ "A sorted collection has to define @Sort: "
+ + safeCollectionRole()
+ );
+ }
+ }
+
+ //set cache
+ if ( StringHelper.isNotEmpty( cacheConcurrencyStrategy ) ) {
+ collection.setCacheConcurrencyStrategy( cacheConcurrencyStrategy );
+ collection.setCacheRegionName( cacheRegionName );
+ }
+
+ //SQL overriding
+ SQLInsert sqlInsert = property.getAnnotation( SQLInsert.class );
+ SQLUpdate sqlUpdate = property.getAnnotation( SQLUpdate.class );
+ SQLDelete sqlDelete = property.getAnnotation( SQLDelete.class );
+ SQLDeleteAll sqlDeleteAll = property.getAnnotation( SQLDeleteAll.class );
+ Loader loader = property.getAnnotation( Loader.class );
+ if ( sqlInsert != null ) {
+ collection.setCustomSQLInsert( sqlInsert.sql().trim(), sqlInsert.callable(),
+ ExecuteUpdateResultCheckStyle.parse( sqlInsert.check().toString().toLowerCase() )
+ );
+
+ }
+ if ( sqlUpdate != null ) {
+ collection.setCustomSQLUpdate( sqlUpdate.sql(), sqlUpdate.callable(),
+ ExecuteUpdateResultCheckStyle.parse( sqlUpdate.check().toString().toLowerCase() )
+ );
+ }
+ if ( sqlDelete != null ) {
+ collection.setCustomSQLDelete( sqlDelete.sql(), sqlDelete.callable(),
+ ExecuteUpdateResultCheckStyle.parse( sqlDelete.check().toString().toLowerCase() )
+ );
+ }
+ if ( sqlDeleteAll != null ) {
+ collection.setCustomSQLDeleteAll( sqlDeleteAll.sql(), sqlDeleteAll.callable(),
+ ExecuteUpdateResultCheckStyle.parse( sqlDeleteAll.check().toString().toLowerCase() )
+ );
+ }
+ if ( loader != null ) {
+ collection.setLoaderName( loader.namedQuery() );
+ }
+
+ //work on association
+ boolean isMappedBy = !BinderHelper.isDefault( mappedBy );
+ collection.setInverse( isMappedBy );
+
+ //many to many may need some second pass informations
+ if ( !oneToMany && isMappedBy ) {
+ mappings.addMappedBy( getCollectionType().getName(), mappedBy, propertyName );
+ }
+ //TODO reducce tableBinder != null and oneToMany
+ XClass collectionType = getCollectionType();
+ SecondPass sp = getSecondPass(
+ fkJoinColumns,
+ joinColumns,
+ inverseJoinColumns,
+ elementColumns,
+ mapKeyColumns, mapKeyManyToManyColumns, isEmbedded,
+ property, collectionType,
+ ignoreNotFound, oneToMany,
+ tableBinder, mappings
+ );
+ if ( collectionType.isAnnotationPresent( Embeddable.class )
+ || property.isAnnotationPresent( CollectionOfElements.class ) ) {
+ // do it right away, otherwise @ManyToon on composite element call addSecondPass
+ // and raise a ConcurrentModificationException
+ //sp.doSecondPass( CollectionHelper.EMPTY_MAP );
+ mappings.addSecondPass( sp, !isMappedBy );
+ }
+ else {
+ mappings.addSecondPass( sp, !isMappedBy );
+ }
+
+ mappings.addCollection( collection );
+
+ //property building
+ PropertyBinder binder = new PropertyBinder();
+ binder.setName( propertyName );
+ binder.setValue( collection );
+ binder.setCascade( cascadeStrategy );
+ if ( cascadeStrategy != null && cascadeStrategy.indexOf( "delete-orphan" ) >= 0 ) {
+ collection.setOrphanDelete( true );
+ }
+ binder.setPropertyAccessorName( propertyAccessorName );
+ binder.setProperty( property );
+ binder.setInsertable( insertable );
+ binder.setUpdatable( updatable );
+ Property prop = binder.make();
+ //we don't care about the join stuffs because the column is on the association table.
+ propertyHolder.addProperty( prop );
+ }
+
+ private void defineFetchingStrategy() {
+ LazyCollection lazy = property.getAnnotation( LazyCollection.class );
+ Fetch fetch = property.getAnnotation( Fetch.class );
+ OneToMany oneToMany = property.getAnnotation( OneToMany.class );
+ ManyToMany manyToMany = property.getAnnotation( ManyToMany.class );
+ CollectionOfElements elements = property.getAnnotation( CollectionOfElements.class );
+ ManyToAny manyToAny = property.getAnnotation( ManyToAny.class );
+ FetchType fetchType;
+ if ( oneToMany != null ) {
+ fetchType = oneToMany.fetch();
+ }
+ else if ( manyToMany != null ) {
+ fetchType = manyToMany.fetch();
+ }
+ else if ( elements != null ) {
+ fetchType = elements.fetch();
+ }
+ else if ( manyToAny != null ) {
+ fetchType = FetchType.LAZY;
+ }
+ else {
+ throw new AssertionFailure(
+ "Define fetch strategy on a property not annotated with @ManyToOne nor @OneToMany nor @CollectionOfElements"
+ );
+ }
+ if ( lazy != null ) {
+ collection.setLazy( !( lazy.value() == LazyCollectionOption.FALSE ) );
+ collection.setExtraLazy( lazy.value() == LazyCollectionOption.EXTRA );
+ }
+ else {
+ collection.setLazy( fetchType == FetchType.LAZY );
+ collection.setExtraLazy( false );
+ }
+ if ( fetch != null ) {
+ if ( fetch.value() == org.hibernate.annotations.FetchMode.JOIN ) {
+ collection.setFetchMode( FetchMode.JOIN );
+ collection.setLazy( false );
+ }
+ else if ( fetch.value() == org.hibernate.annotations.FetchMode.SELECT ) {
+ collection.setFetchMode( FetchMode.SELECT );
+ }
+ else if ( fetch.value() == org.hibernate.annotations.FetchMode.SUBSELECT ) {
+ collection.setFetchMode( FetchMode.SELECT );
+ collection.setSubselectLoadable( true );
+ collection.getOwner().setSubselectLoadableCollections( true );
+ }
+ else {
+ throw new AssertionFailure( "Unknown FetchMode: " + fetch.value() );
+ }
+ }
+ else {
+ collection.setFetchMode( AnnotationBinder.getFetchMode( fetchType ) );
+ }
+ }
+
+ private XClass getCollectionType() {
+ if ( AnnotationBinder.isDefault( targetEntity, mappings ) ) {
+ if ( collectionType != null ) {
+ return collectionType;
+ }
+ else {
+ String errorMsg = "Collection has neither generic type or OneToMany.targetEntity() defined: "
+ + safeCollectionRole();
+ throw new AnnotationException( errorMsg );
+ }
+ }
+ else {
+ return targetEntity;
+ }
+ }
+
+ public SecondPass getSecondPass(
+ final Ejb3JoinColumn[] fkJoinColumns, final Ejb3JoinColumn[] keyColumns,
+ final Ejb3JoinColumn[] inverseColumns,
+ final Ejb3Column[] elementColumns,
+ final Ejb3Column[] mapKeyColumns, final Ejb3JoinColumn[] mapKeyManyToManyColumns, final boolean isEmbedded,
+ final XProperty property, final XClass collType,
+ final boolean ignoreNotFound, final boolean unique,
+ final TableBinder assocTableBinder, final ExtendedMappings mappings
+ ) {
+
+ return new CollectionSecondPass( mappings, collection ) {
+
+ public void secondPass(java.util.Map persistentClasses, java.util.Map inheritedMetas)
+ throws MappingException {
+ bindStarToManySecondPass(
+ persistentClasses, collType, fkJoinColumns, keyColumns, inverseColumns, elementColumns,
+ isEmbedded, property, unique, assocTableBinder, ignoreNotFound, mappings
+ );
+
+ }
+ };
+ }
+
+ /**
+ * return true if it's a Fk, false if it's an association table
+ */
+ protected boolean bindStarToManySecondPass(
+ Map persistentClasses, XClass collType, Ejb3JoinColumn[] fkJoinColumns,
+ Ejb3JoinColumn[] keyColumns, Ejb3JoinColumn[] inverseColumns, Ejb3Column[] elementColumns,
+ boolean isEmbedded,
+ XProperty property, boolean unique,
+ TableBinder associationTableBinder, boolean ignoreNotFound, ExtendedMappings mappings
+ ) {
+ PersistentClass persistentClass = (PersistentClass) persistentClasses.get( collType.getName() );
+ boolean reversePropertyInJoin = false;
+ if ( persistentClass != null && StringHelper.isNotEmpty( this.mappedBy ) ) {
+ try {
+ reversePropertyInJoin = 0 != persistentClass.getJoinNumber(
+ persistentClass.getRecursiveProperty( this.mappedBy )
+ );
+ }
+ catch (MappingException e) {
+ StringBuilder error = new StringBuilder( 80 );
+ error.append( "mappedBy reference an unknown target entity property: " )
+ .append( collType ).append( "." ).append( this.mappedBy )
+ .append( " in " )
+ .append( collection.getOwnerEntityName() )
+ .append( "." )
+ .append( property.getName() );
+ throw new AnnotationException( error.toString() );
+ }
+ }
+ if ( persistentClass != null
+ && !reversePropertyInJoin
+ && oneToMany
+ && !this.isExplicitAssociationTable
+ && ( joinColumns[0].isImplicit() && !BinderHelper.isDefault( this.mappedBy ) //implicit @JoinColumn
+ || !fkJoinColumns[0].isImplicit() ) //this is an explicit @JoinColumn
+ ) {
+ //this is a Foreign key
+ bindOneToManySecondPass(
+ getCollection(),
+ persistentClasses,
+ fkJoinColumns,
+ collType,
+ cascadeDeleteEnabled,
+ ignoreNotFound, hqlOrderBy,
+ mappings
+ );
+ return true;
+ }
+ else {
+ //this is an association table
+ bindManyToManySecondPass(
+ this.collection,
+ persistentClasses,
+ keyColumns,
+ inverseColumns,
+ elementColumns,
+ isEmbedded, collType,
+ ignoreNotFound, unique,
+ cascadeDeleteEnabled,
+ associationTableBinder, property, propertyHolder, hqlOrderBy, mappings
+ );
+ return false;
+ }
+ }
+
+ protected void bindOneToManySecondPass(
+ Collection collection, Map persistentClasses, Ejb3JoinColumn[] fkJoinColumns,
+ XClass collectionType,
+ boolean cascadeDeleteEnabled, boolean ignoreNotFound, String hqlOrderBy, ExtendedMappings extendedMappings
+ ) {
+
+ log.debug("Binding a OneToMany: {}.{} through a foreign key", propertyHolder.getEntityName(), propertyName);
+ org.hibernate.mapping.OneToMany oneToMany = new org.hibernate.mapping.OneToMany( collection.getOwner() );
+ collection.setElement( oneToMany );
+ oneToMany.setReferencedEntityName( collectionType.getName() );
+ oneToMany.setIgnoreNotFound( ignoreNotFound );
+
+ String assocClass = oneToMany.getReferencedEntityName();
+ PersistentClass associatedClass = (PersistentClass) persistentClasses.get( assocClass );
+ String orderBy = buildOrderByClauseFromHql( hqlOrderBy, associatedClass, collection.getRole() );
+ if ( orderBy != null ) collection.setOrderBy( orderBy );
+ if ( mappings == null ) {
+ throw new AssertionFailure(
+ "CollectionSecondPass for oneToMany should not be called with null mappings"
+ );
+ }
+ Map<String, Join> joins = mappings.getJoins( assocClass );
+ if ( associatedClass == null ) {
+ throw new MappingException(
+ "Association references unmapped class: " + assocClass
+ );
+ }
+ oneToMany.setAssociatedClass( associatedClass );
+ for (Ejb3JoinColumn column : fkJoinColumns) {
+ column.setPersistentClass( associatedClass, joins );
+ column.setJoins( joins );
+ collection.setCollectionTable( column.getTable() );
+ }
+ log.info(
+ "Mapping collection: " + collection.getRole() + " -> " + collection.getCollectionTable().getName()
+ );
+ bindFilters( false );
+ bindCollectionSecondPass( collection, null, fkJoinColumns, cascadeDeleteEnabled, property, mappings );
+ if ( !collection.isInverse()
+ && !collection.getKey().isNullable() ) {
+ // for non-inverse one-to-many, with a not-null fk, add a backref!
+ String entityName = oneToMany.getReferencedEntityName();
+ PersistentClass referenced = mappings.getClass( entityName );
+ Backref prop = new Backref();
+ prop.setName( '_' + fkJoinColumns[0].getPropertyName() + "Backref" );
+ prop.setUpdateable( false );
+ prop.setSelectable( false );
+ prop.setCollectionRole( collection.getRole() );
+ prop.setEntityName( collection.getOwner().getEntityName() );
+ prop.setValue( collection.getKey() );
+ referenced.addProperty( prop );
+ }
+ }
+
+
+ private void bindFilters(boolean hasAssociationTable) {
+ Filter simpleFilter = property.getAnnotation( Filter.class );
+ //set filtering
+ //test incompatible choices
+ //if ( StringHelper.isNotEmpty( where ) ) collection.setWhere( where );
+ if ( simpleFilter != null ) {
+ if ( hasAssociationTable ) {
+ collection.addManyToManyFilter( simpleFilter.name(), getCondition( simpleFilter ) );
+ }
+ else {
+ collection.addFilter( simpleFilter.name(), getCondition( simpleFilter ) );
+ }
+ }
+ Filters filters = property.getAnnotation( Filters.class );
+ if ( filters != null ) {
+ for (Filter filter : filters.value()) {
+ if ( hasAssociationTable ) {
+ collection.addManyToManyFilter( filter.name(), getCondition( filter ) );
+ }
+ else {
+ collection.addFilter( filter.name(), getCondition( filter ) );
+ }
+ }
+ }
+ FilterJoinTable simpleFilterJoinTable = property.getAnnotation( FilterJoinTable.class );
+ if ( simpleFilterJoinTable != null ) {
+ if ( hasAssociationTable ) {
+ collection.addFilter( simpleFilterJoinTable.name(), getCondition( simpleFilterJoinTable ) );
+ }
+ else {
+ throw new AnnotationException(
+ "Illegal use of @FilterJoinTable on an association without join table:"
+ + StringHelper.qualify( propertyHolder.getPath(), propertyName )
+ );
+ }
+ }
+ FilterJoinTables filterJoinTables = property.getAnnotation( FilterJoinTables.class );
+ if ( filterJoinTables != null ) {
+ for (FilterJoinTable filter : filterJoinTables.value()) {
+ if ( hasAssociationTable ) {
+ collection.addFilter( filter.name(), getCondition( filter ) );
+ }
+ else {
+ throw new AnnotationException(
+ "Illegal use of @FilterJoinTable on an association without join table:"
+ + StringHelper.qualify( propertyHolder.getPath(), propertyName )
+ );
+ }
+ }
+ }
+
+ Where where = property.getAnnotation( Where.class );
+ String whereClause = where == null ? null : where.clause();
+ if ( StringHelper.isNotEmpty( whereClause ) ) {
+ if ( hasAssociationTable ) {
+ collection.setManyToManyWhere( whereClause );
+ }
+ else {
+ collection.setWhere( whereClause );
+ }
+ }
+
+ WhereJoinTable whereJoinTable = property.getAnnotation( WhereJoinTable.class );
+ String whereJoinTableClause = whereJoinTable == null ? null : whereJoinTable.clause();
+ if ( StringHelper.isNotEmpty( whereJoinTableClause ) ) {
+ if ( hasAssociationTable ) {
+ collection.setWhere( whereJoinTableClause );
+ }
+ else {
+ throw new AnnotationException(
+ "Illegal use of @WhereJoinTable on an association without join table:"
+ + StringHelper.qualify( propertyHolder.getPath(), propertyName )
+ );
+ }
+ }
+// This cannot happen in annotations since the second fetch is hardcoded to join
+// if ( ( ! collection.getManyToManyFilterMap().isEmpty() || collection.getManyToManyWhere() != null ) &&
+// collection.getFetchMode() == FetchMode.JOIN &&
+// collection.getElement().getFetchMode() != FetchMode.JOIN ) {
+// throw new MappingException(
+// "association with join table defining filter or where without join fetching " +
+// "not valid within collection using join fetching [" + collection.getRole() + "]"
+// );
+// }
+ }
+
+ private String getCondition(FilterJoinTable filter) {
+ //set filtering
+ String name = filter.name();
+ String cond = filter.condition();
+ return getCondition( cond, name );
+ }
+
+ private String getCondition(Filter filter) {
+ //set filtering
+ String name = filter.name();
+ String cond = filter.condition();
+ return getCondition( cond, name );
+ }
+
+ private String getCondition(String cond, String name) {
+ if ( BinderHelper.isDefault( cond ) ) {
+ cond = mappings.getFilterDefinition( name ).getDefaultFilterCondition();
+ if ( StringHelper.isEmpty( cond ) ) {
+ throw new AnnotationException(
+ "no filter condition found for filter " + name + " in "
+ + StringHelper.qualify( propertyHolder.getPath(), propertyName )
+ );
+ }
+ }
+ return cond;
+ }
+
+ public void setCache(Cache cacheAnn) {
+ if ( cacheAnn != null ) {
+ cacheRegionName = BinderHelper.isDefault( cacheAnn.region() ) ? null : cacheAnn.region();
+ cacheConcurrencyStrategy = EntityBinder.getCacheConcurrencyStrategy( cacheAnn.usage() );
+ }
+ else {
+ cacheConcurrencyStrategy = null;
+ cacheRegionName = null;
+ }
+ }
+
+ public void setOneToMany(boolean oneToMany) {
+ this.oneToMany = oneToMany;
+ }
+
+ public void setIndexColumn(IndexColumn indexColumn) {
+ this.indexColumn = indexColumn;
+ }
+
+ public void setMapKey(MapKey key) {
+ if ( key != null ) {
+ mapKeyPropertyName = key.name();
+ }
+ }
+
+ private static String buildOrderByClauseFromHql(String hqlOrderBy, PersistentClass associatedClass, String role) {
+ String orderByString = null;
+ if ( hqlOrderBy != null ) {
+ List<String> properties = new ArrayList<String>();
+ List<String> ordering = new ArrayList<String>();
+ StringBuilder orderByBuffer = new StringBuilder();
+ if ( hqlOrderBy.length() == 0 ) {
+ //order by id
+ Iterator it = associatedClass.getIdentifier().getColumnIterator();
+ while ( it.hasNext() ) {
+ Selectable col = (Selectable) it.next();
+ orderByBuffer.append( col.getText() ).append( " asc" ).append( ", " );
+ }
+ }
+ else {
+ StringTokenizer st = new StringTokenizer( hqlOrderBy, " ,", false );
+ String currentOrdering = null;
+ //FIXME make this code decent
+ while ( st.hasMoreTokens() ) {
+ String token = st.nextToken();
+ if ( isNonPropertyToken( token ) ) {
+ if ( currentOrdering != null ) {
+ throw new AnnotationException(
+ "Error while parsing HQL orderBy clause: " + hqlOrderBy
+ + " (" + role + ")"
+ );
+ }
+ currentOrdering = token;
+ }
+ else {
+ //Add ordering of the previous
+ if ( currentOrdering == null ) {
+ //default ordering
+ ordering.add( "asc" );
+ }
+ else {
+ ordering.add( currentOrdering );
+ currentOrdering = null;
+ }
+ properties.add( token );
+ }
+ }
+ ordering.remove( 0 ); //first one is the algorithm starter
+ // add last one ordering
+ if ( currentOrdering == null ) {
+ //default ordering
+ ordering.add( "asc" );
+ }
+ else {
+ ordering.add( currentOrdering );
+ currentOrdering = null;
+ }
+ int index = 0;
+
+ for (String property : properties) {
+ Property p = BinderHelper.findPropertyByName( associatedClass, property );
+ if ( p == null ) {
+ throw new AnnotationException(
+ "property from @OrderBy clause not found: "
+ + associatedClass.getEntityName() + "." + property
+ );
+ }
+ PersistentClass pc = p.getPersistentClass();
+ String table;
+ if ( pc == null ) {
+ //we are touching a @IdClass property, the pc is not set
+ //this means pc == associatedClass
+ //TODO check whether @ManyToOne @JoinTable in @IdClass used for @OrderBy works: doh!
+ table = "";
+ }
+
+ else if (pc == associatedClass
+ || (associatedClass instanceof SingleTableSubclass && pc
+ .getMappedClass().isAssignableFrom(
+ associatedClass.getMappedClass()))) {
+ table = "";
+ } else {
+ table = pc.getTable().getQuotedName() + ".";
+ }
+
+ Iterator propertyColumns = p.getColumnIterator();
+ while ( propertyColumns.hasNext() ) {
+ Selectable column = (Selectable) propertyColumns.next();
+ orderByBuffer.append( table )
+ .append( column.getText() )
+ .append( " " )
+ .append( ordering.get( index ) )
+ .append( ", " );
+ }
+ index++;
+ }
+ }
+ orderByString = orderByBuffer.substring( 0, orderByBuffer.length() - 2 );
+ }
+ return orderByString;
+ }
+
+ private static String buildOrderByClauseFromHql(String hqlOrderBy, Component component, String role) {
+ String orderByString = null;
+ if ( hqlOrderBy != null ) {
+ List<String> properties = new ArrayList<String>();
+ List<String> ordering = new ArrayList<String>();
+ StringBuilder orderByBuffer = new StringBuilder();
+ if ( hqlOrderBy.length() == 0 ) {
+ //TODO : Check that. Maybe order by key for maps
+ }
+ else {
+ StringTokenizer st = new StringTokenizer( hqlOrderBy, " ,", false );
+ String currentOrdering = null;
+ //FIXME make this code decent
+ while ( st.hasMoreTokens() ) {
+ String token = st.nextToken();
+ if ( isNonPropertyToken( token ) ) {
+ if ( currentOrdering != null ) {
+ throw new AnnotationException(
+ "Error while parsing HQL orderBy clause: " + hqlOrderBy
+ + " (" + role + ")"
+ );
+ }
+ currentOrdering = token;
+ }
+ else {
+ //Add ordering of the previous
+ if ( currentOrdering == null ) {
+ //default ordering
+ ordering.add( "asc" );
+ }
+ else {
+ ordering.add( currentOrdering );
+ currentOrdering = null;
+ }
+ properties.add( token );
+ }
+ }
+ ordering.remove( 0 ); //first one is the algorithm starter
+ // add last one ordering
+ if ( currentOrdering == null ) {
+ //default ordering
+ ordering.add( "asc" );
+ }
+ else {
+ ordering.add( currentOrdering );
+ currentOrdering = null;
+ }
+ int index = 0;
+
+ for (String property : properties) {
+ Property p = component.getProperty( property );
+ if ( p == null ) {
+ throw new AnnotationException(
+ "property from @OrderBy clause not found: "
+ + role + "." + property
+ );
+ }
+
+ Iterator propertyColumns = p.getColumnIterator();
+ while ( propertyColumns.hasNext() ) {
+ Selectable column = (Selectable) propertyColumns.next();
+ orderByBuffer.append( column.getText() )
+ .append( " " )
+ .append( ordering.get( index ) )
+ .append( ", " );
+ }
+ index++;
+ }
+
+ if ( orderByBuffer.length() >= 2 ) {
+ orderByString = orderByBuffer.substring( 0, orderByBuffer.length() - 2 );
+ }
+ }
+ }
+ return orderByString;
+ }
+
+ private static boolean isNonPropertyToken(String token) {
+ if ( " ".equals( token ) ) return true;
+ if ( ",".equals( token ) ) return true;
+ if ( token.equalsIgnoreCase( "desc" ) ) return true;
+ if ( token.equalsIgnoreCase( "asc" ) ) return true;
+ return false;
+ }
+
+ private static SimpleValue buildCollectionKey(
+ Collection collValue, Ejb3JoinColumn[] joinColumns, boolean cascadeDeleteEnabled,
+ XProperty property, ExtendedMappings mappings
+ ) {
+ //binding key reference using column
+ KeyValue keyVal;
+ //give a chance to override the referenced property name
+ //has to do that here because the referencedProperty creation happens in a FKSecondPass for Many to one yuk!
+ if ( joinColumns.length > 0 && StringHelper.isNotEmpty( joinColumns[0].getMappedBy() ) ) {
+ String entityName = joinColumns[0].getManyToManyOwnerSideEntityName() != null ?
+ "inverse__" + joinColumns[0].getManyToManyOwnerSideEntityName() :
+ joinColumns[0].getPropertyHolder().getEntityName();
+ String propRef = mappings.getPropertyReferencedAssociation(
+ entityName,
+ joinColumns[0].getMappedBy()
+ );
+ if ( propRef != null ) {
+ collValue.setReferencedPropertyName( propRef );
+ mappings.addPropertyReference( collValue.getOwnerEntityName(), propRef );
+ }
+ }
+ String propRef = collValue.getReferencedPropertyName();
+ if ( propRef == null ) {
+ keyVal = collValue.getOwner().getIdentifier();
+ }
+ else {
+ keyVal = (KeyValue) collValue.getOwner()
+ .getRecursiveProperty( propRef )
+ .getValue();
+ }
+ DependantValue key = new DependantValue( collValue.getCollectionTable(), keyVal );
+ key.setTypeName( null );
+ Ejb3Column.checkPropertyConsistency( joinColumns, collValue.getOwnerEntityName() );
+ key.setNullable( joinColumns.length == 0 || joinColumns[0].isNullable() );
+ key.setUpdateable( joinColumns.length == 0 || joinColumns[0].isUpdatable() );
+ key.setCascadeDeleteEnabled( cascadeDeleteEnabled );
+ collValue.setKey( key );
+ ForeignKey fk = property != null ? property.getAnnotation( ForeignKey.class ) : null;
+ String fkName = fk != null ? fk.name() : "";
+ if ( !BinderHelper.isDefault( fkName ) ) key.setForeignKeyName( fkName );
+ return key;
+ }
+
+ protected void bindManyToManySecondPass(
+ Collection collValue,
+ Map persistentClasses,
+ Ejb3JoinColumn[] joinColumns,
+ Ejb3JoinColumn[] inverseJoinColumns,
+ Ejb3Column[] elementColumns,
+ boolean isEmbedded,
+ XClass collType,
+ boolean ignoreNotFound, boolean unique,
+ boolean cascadeDeleteEnabled,
+ TableBinder associationTableBinder, XProperty property, PropertyHolder parentPropertyHolder,
+ String hqlOrderBy, ExtendedMappings mappings
+ ) throws MappingException {
+
+ PersistentClass collectionEntity = (PersistentClass) persistentClasses.get( collType.getName() );
+ boolean isCollectionOfEntities = collectionEntity != null;
+ ManyToAny anyAnn = property.getAnnotation( ManyToAny.class );
+ if ( log.isDebugEnabled() ) {
+ String path = collValue.getOwnerEntityName() + "." + joinColumns[0].getPropertyName();
+ if ( isCollectionOfEntities && unique ) {
+ log.debug( "Binding a OneToMany: {} through an association table", path );
+ }
+ else if ( isCollectionOfEntities ) {
+ log.debug( "Binding as ManyToMany: {}", path );
+ }
+ else if ( anyAnn != null ) {
+ log.debug( "Binding a ManyToAny: {}", path );
+ }
+ else {
+ log.debug( "Binding a collection of element: {}", path );
+ }
+ }
+ //check for user error
+ if ( !isCollectionOfEntities ) {
+ if ( property.isAnnotationPresent( ManyToMany.class ) || property.isAnnotationPresent( OneToMany.class ) ) {
+ String path = collValue.getOwnerEntityName() + "." + joinColumns[0].getPropertyName();
+ throw new AnnotationException(
+ "Use of @OneToMany or @ManyToMany targeting an unmapped class: " + path + "[" + collType + "]"
+ );
+ }
+ else if ( anyAnn != null ) {
+ if ( !property.isAnnotationPresent( JoinTable.class ) ) {
+ String path = collValue.getOwnerEntityName() + "." + joinColumns[0].getPropertyName();
+ throw new AnnotationException(
+ "@JoinTable is mandatory when @ManyToAny is used: " + path
+ );
+ }
+ }
+ else {
+ JoinTable joinTableAnn = property.getAnnotation( JoinTable.class );
+ if ( joinTableAnn != null && joinTableAnn.inverseJoinColumns().length > 0 ) {
+ String path = collValue.getOwnerEntityName() + "." + joinColumns[0].getPropertyName();
+ throw new AnnotationException(
+ "Use of @JoinTable.inverseJoinColumns targeting an unmapped class: " + path + "[" + collType + "]"
+ );
+ }
+ }
+ }
+
+ boolean mappedBy = !BinderHelper.isDefault( joinColumns[0].getMappedBy() );
+ if ( mappedBy ) {
+ if ( !isCollectionOfEntities ) {
+ StringBuilder error = new StringBuilder( 80 )
+ .append(
+ "Collection of elements must not have mappedBy or association reference an unmapped entity: "
+ )
+ .append( collValue.getOwnerEntityName() )
+ .append( "." )
+ .append( joinColumns[0].getPropertyName() );
+ throw new AnnotationException( error.toString() );
+ }
+ Property otherSideProperty;
+ try {
+ otherSideProperty = collectionEntity.getRecursiveProperty( joinColumns[0].getMappedBy() );
+ }
+ catch (MappingException e) {
+ StringBuilder error = new StringBuilder( 80 );
+ error.append( "mappedBy reference an unknown target entity property: " )
+ .append( collType ).append( "." ).append( joinColumns[0].getMappedBy() )
+ .append( " in " )
+ .append( collValue.getOwnerEntityName() )
+ .append( "." )
+ .append( joinColumns[0].getPropertyName() );
+ throw new AnnotationException( error.toString() );
+ }
+ Table table;
+ if ( otherSideProperty.getValue() instanceof Collection ) {
+ //this is a collection on the other side
+ table = ( (Collection) otherSideProperty.getValue() ).getCollectionTable();
+ }
+ else {
+ //This is a ToOne with a @JoinTable or a regular property
+ table = otherSideProperty.getValue().getTable();
+ }
+ collValue.setCollectionTable( table );
+ String entityName = collectionEntity.getEntityName();
+ for (Ejb3JoinColumn column : joinColumns) {
+ //column.setDefaultColumnHeader( joinColumns[0].getMappedBy() ); //seems not to be used, make sense
+ column.setManyToManyOwnerSideEntityName( entityName );
+ }
+ }
+ else {
+ //TODO: only for implicit columns?
+ //FIXME NamingStrategy
+ for (Ejb3JoinColumn column : joinColumns) {
+ String mappedByProperty = mappings.getFromMappedBy(
+ collValue.getOwnerEntityName(), column.getPropertyName()
+ );
+ Table ownerTable = collValue.getOwner().getTable();
+ column.setMappedBy(
+ collValue.getOwner().getEntityName(), mappings.getLogicalTableName( ownerTable ),
+ mappedByProperty
+ );
+// String header = ( mappedByProperty == null ) ? mappings.getLogicalTableName( ownerTable ) : mappedByProperty;
+// column.setDefaultColumnHeader( header );
+ }
+ if ( StringHelper.isEmpty( associationTableBinder.getName() ) ) {
+ //default value
+ associationTableBinder.setDefaultName(
+ collValue.getOwner().getEntityName(),
+ mappings.getLogicalTableName( collValue.getOwner().getTable() ),
+ collectionEntity != null ? collectionEntity.getEntityName() : null,
+ collectionEntity != null ? mappings.getLogicalTableName( collectionEntity.getTable() ) : null,
+ joinColumns[0].getPropertyName()
+ );
+ }
+ collValue.setCollectionTable( associationTableBinder.bind() );
+ }
+ bindFilters( isCollectionOfEntities );
+ bindCollectionSecondPass( collValue, collectionEntity, joinColumns, cascadeDeleteEnabled, property, mappings );
+
+ ManyToOne element = null;
+ if ( isCollectionOfEntities ) {
+ element =
+ new ManyToOne( collValue.getCollectionTable() );
+ collValue.setElement( element );
+ element.setReferencedEntityName( collType.getName() );
+ //element.setFetchMode( fetchMode );
+ //element.setLazy( fetchMode != FetchMode.JOIN );
+ //make the second join non lazy
+ element.setFetchMode( FetchMode.JOIN );
+ element.setLazy( false );
+ element.setIgnoreNotFound( ignoreNotFound );
+ if ( StringHelper.isNotEmpty( hqlOrderBy ) ) {
+ collValue.setManyToManyOrdering(
+ buildOrderByClauseFromHql( hqlOrderBy, collectionEntity, collValue.getRole() )
+ );
+ }
+ ForeignKey fk = property != null ? property.getAnnotation( ForeignKey.class ) : null;
+ String fkName = fk != null ? fk.inverseName() : "";
+ if ( !BinderHelper.isDefault( fkName ) ) element.setForeignKeyName( fkName );
+ }
+ else if ( anyAnn != null ) {
+ //@ManyToAny
+ //Make sure that collTyp is never used during the @ManyToAny branch: it will be set to void.class
+ PropertyData inferredData = new PropertyInferredData( property, "unsupported", mappings.getReflectionManager() );
+ //override the table
+ for (Ejb3Column column : inverseJoinColumns) {
+ column.setTable( collValue.getCollectionTable() );
+ }
+ Any any = BinderHelper.buildAnyValue( anyAnn.metaDef(), inverseJoinColumns, anyAnn.metaColumn(),
+ inferredData, cascadeDeleteEnabled, Nullability.NO_CONSTRAINT,
+ propertyHolder, new EntityBinder(), true, mappings );
+ collValue.setElement( any );
+ }
+ else {
+ XClass elementClass;
+ AnnotatedClassType classType;
+// Map<String, javax.persistence.Column[]> columnOverrides = PropertyHolderBuilder.buildColumnOverride(
+// property, StringHelper.qualify( collValue.getRole(), "element" )
+// );
+ //FIXME the "element" is lost
+ PropertyHolder holder = null;
+ if ( BinderHelper.PRIMITIVE_NAMES.contains( collType.getName() ) ) {
+ classType = AnnotatedClassType.NONE;
+ elementClass = null;
+ }
+ else {
+ elementClass = collType;
+ classType = mappings.getClassType( elementClass );
+
+ holder = PropertyHolderBuilder.buildPropertyHolder(
+ collValue,
+ collValue.getRole(), // + ".element",
+ elementClass,
+ property, parentPropertyHolder, mappings
+ );
+ //force in case of attribute override
+ boolean attributeOverride = property.isAnnotationPresent( AttributeOverride.class )
+ || property.isAnnotationPresent( AttributeOverrides.class );
+ if ( isEmbedded || attributeOverride ) {
+ classType = AnnotatedClassType.EMBEDDABLE;
+ }
+ }
+
+ if ( AnnotatedClassType.EMBEDDABLE.equals( classType ) ) {
+ EntityBinder entityBinder = new EntityBinder();
+ PersistentClass owner = collValue.getOwner();
+ boolean isPropertyAnnotated;
+ //FIXME support @Access for collection of elements
+ //String accessType = access != null ? access.value() : null;
+ if ( owner.getIdentifierProperty() != null ) {
+ isPropertyAnnotated = owner.getIdentifierProperty().getPropertyAccessorName().equals( "property" );
+ }
+ else if ( owner.getIdentifierMapper() != null && owner.getIdentifierMapper().getPropertySpan() > 0 ) {
+ Property prop = (Property) owner.getIdentifierMapper().getPropertyIterator().next();
+ isPropertyAnnotated = prop.getPropertyAccessorName().equals( "property" );
+ }
+ else {
+ throw new AssertionFailure( "Unable to guess collection property accessor name" );
+ }
+
+ //boolean propertyAccess = embeddable == null || AccessType.PROPERTY.equals( embeddable.access() );
+ PropertyData inferredData = new PropertyPreloadedData( "property", "element", elementClass );
+ //TODO be smart with isNullable
+ Component component = AnnotationBinder.fillComponent(
+ holder, inferredData, isPropertyAnnotated, isPropertyAnnotated ? "property" : "field", true,
+ entityBinder, false, false,
+ true, mappings
+ );
+
+ collValue.setElement( component );
+
+ if ( StringHelper.isNotEmpty( hqlOrderBy ) ) {
+ String path = collValue.getOwnerEntityName() + "." + joinColumns[0].getPropertyName();
+ String orderBy = buildOrderByClauseFromHql( hqlOrderBy, component, path );
+ if ( orderBy != null ) {
+ collValue.setOrderBy( orderBy );
+ }
+ }
+ }
+ else {
+ SimpleValueBinder elementBinder = new SimpleValueBinder();
+ elementBinder.setMappings( mappings );
+ elementBinder.setReturnedClassName( collType.getName() );
+ if ( elementColumns == null || elementColumns.length == 0 ) {
+ elementColumns = new Ejb3Column[1];
+ Ejb3Column column = new Ejb3Column();
+ column.setImplicit( false );
+ //not following the spec but more clean
+ column.setNullable( true );
+ column.setLength( Ejb3Column.DEFAULT_COLUMN_LENGTH );
+ column.setLogicalColumnName( Collection.DEFAULT_ELEMENT_COLUMN_NAME );
+ //TODO create an EMPTY_JOINS collection
+ column.setJoins( new HashMap<String, Join>() );
+ column.setMappings( mappings );
+ column.bind();
+ elementColumns[0] = column;
+ }
+ //override the table
+ for (Ejb3Column column : elementColumns) {
+ column.setTable( collValue.getCollectionTable() );
+ }
+ elementBinder.setColumns( elementColumns );
+ elementBinder.setType( property, elementClass );
+ collValue.setElement( elementBinder.make() );
+ }
+ }
+
+ checkFilterConditions( collValue );
+
+ //FIXME: do optional = false
+ if ( isCollectionOfEntities ) {
+ bindManytoManyInverseFk( collectionEntity, inverseJoinColumns, element, unique, mappings );
+ }
+
+ }
+
+ private static void checkFilterConditions(Collection collValue) {
+ //for now it can't happen, but sometime soon...
+ if ( ( collValue.getFilterMap().size() != 0 || StringHelper.isNotEmpty( collValue.getWhere() ) ) &&
+ collValue.getFetchMode() == FetchMode.JOIN &&
+ !( collValue.getElement() instanceof SimpleValue ) && //SimpleValue (CollectionOfElements) are always SELECT but it does not matter
+ collValue.getElement().getFetchMode() != FetchMode.JOIN ) {
+ throw new MappingException(
+ "@ManyToMany or @CollectionOfElements defining filter or where without join fetching "
+ + "not valid within collection using join fetching[" + collValue.getRole() + "]"
+ );
+ }
+ }
+
+ private static void bindCollectionSecondPass(
+ Collection collValue, PersistentClass collectionEntity, Ejb3JoinColumn[] joinColumns,
+ boolean cascadeDeleteEnabled, XProperty property,
+ ExtendedMappings mappings
+ ) {
+ BinderHelper.createSyntheticPropertyReference(
+ joinColumns, collValue.getOwner(), collectionEntity, collValue, false, mappings
+ );
+ SimpleValue key = buildCollectionKey( collValue, joinColumns, cascadeDeleteEnabled, property, mappings );
+ TableBinder.bindFk( collValue.getOwner(), collectionEntity, joinColumns, key, false, mappings );
+ }
+
+ public void setCascadeDeleteEnabled(boolean onDeleteCascade) {
+ this.cascadeDeleteEnabled = onDeleteCascade;
+ }
+
+ private String safeCollectionRole() {
+ if ( propertyHolder != null ) {
+ return propertyHolder.getEntityName() + "." + propertyName;
+ }
+ else {
+ return "";
+ }
+ }
+
+
+ /**
+ * bind the inverse FK of a ManyToMany
+ * If we are in a mappedBy case, read the columns from the associated
+ * colletion element
+ * Otherwise delegates to the usual algorithm
+ */
+ public static void bindManytoManyInverseFk(
+ PersistentClass referencedEntity, Ejb3JoinColumn[] columns, SimpleValue value, boolean unique,
+ ExtendedMappings mappings
+ ) {
+ final String mappedBy = columns[0].getMappedBy();
+ if ( StringHelper.isNotEmpty( mappedBy ) ) {
+ final Property property = referencedEntity.getRecursiveProperty( mappedBy );
+ Iterator mappedByColumns;
+ if ( property.getValue() instanceof Collection ) {
+ mappedByColumns = ( (Collection) property.getValue() ).getKey().getColumnIterator();
+ }
+ else {
+ //find the appropriate reference key, can be in a join
+ Iterator joinsIt = referencedEntity.getJoinIterator();
+ KeyValue key = null;
+ while ( joinsIt.hasNext() ) {
+ Join join = (Join) joinsIt.next();
+ if ( join.containsProperty( property ) ) {
+ key = join.getKey();
+ break;
+ }
+ }
+ if ( key == null ) key = property.getPersistentClass().getIdentifier();
+ mappedByColumns = key.getColumnIterator();
+ }
+ while ( mappedByColumns.hasNext() ) {
+ Column column = (Column) mappedByColumns.next();
+ columns[0].linkValueUsingAColumnCopy( column, value );
+ }
+ String referencedPropertyName =
+ mappings.getPropertyReferencedAssociation(
+ "inverse__" + referencedEntity.getEntityName(), mappedBy
+ );
+ if ( referencedPropertyName != null ) {
+ //TODO always a many to one?
+ ( (ManyToOne) value ).setReferencedPropertyName( referencedPropertyName );
+ mappings.addUniquePropertyReference( referencedEntity.getEntityName(), referencedPropertyName );
+ }
+ value.createForeignKey();
+ }
+ else {
+ BinderHelper.createSyntheticPropertyReference( columns, referencedEntity, null, value, true, mappings );
+ TableBinder.bindFk( referencedEntity, null, columns, value, unique, mappings );
+ }
+ }
+
+ public void setFkJoinColumns(Ejb3JoinColumn[] ejb3JoinColumns) {
+ this.fkJoinColumns = ejb3JoinColumns;
+ }
+
+ public void setExplicitAssociationTable(boolean explicitAssocTable) {
+ this.isExplicitAssociationTable = explicitAssocTable;
+ }
+
+ public void setElementColumns(Ejb3Column[] elementColumns) {
+ this.elementColumns = elementColumns;
+ }
+
+ public void setEmbedded(boolean annotationPresent) {
+ this.isEmbedded = annotationPresent;
+ }
+
+ public void setProperty(XProperty property) {
+ this.property = property;
+ }
+
+ public void setIgnoreNotFound(boolean ignoreNotFound) {
+ this.ignoreNotFound = ignoreNotFound;
+ }
+
+ public void setMapKeyColumns(Ejb3Column[] mapKeyColumns) {
+ this.mapKeyColumns = mapKeyColumns;
+ }
+
+ public void setMapKeyManyToManyColumns(Ejb3JoinColumn[] mapJoinColumns) {
+ this.mapKeyManyToManyColumns = mapJoinColumns;
+ }
+
+ public void setLocalGenerators(HashMap<String, IdGenerator> localGenerators) {
+ this.localGenerators = localGenerators;
+ }
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/EntityBinder.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/EntityBinder.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/EntityBinder.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,808 @@
+//$Id: EntityBinder.java 14741 2008-06-05 11:25:56Z hardy.ferentschik $
+package org.hibernate.cfg.annotations;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import javax.persistence.Entity;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinTable;
+import javax.persistence.PrimaryKeyJoinColumn;
+import javax.persistence.SecondaryTable;
+import javax.persistence.SecondaryTables;
+import javax.persistence.UniqueConstraint;
+
+import org.hibernate.AnnotationException;
+import org.hibernate.AssertionFailure;
+import org.hibernate.EntityMode;
+import org.hibernate.MappingException;
+import org.hibernate.annotations.AccessType;
+import org.hibernate.annotations.BatchSize;
+import org.hibernate.annotations.Cache;
+import org.hibernate.annotations.CacheConcurrencyStrategy;
+import org.hibernate.annotations.FetchMode;
+import org.hibernate.annotations.ForceDiscriminator;
+import org.hibernate.annotations.Immutable;
+import org.hibernate.annotations.Loader;
+import org.hibernate.annotations.OptimisticLockType;
+import org.hibernate.annotations.Persister;
+import org.hibernate.annotations.PolymorphismType;
+import org.hibernate.annotations.Proxy;
+import org.hibernate.annotations.SQLDelete;
+import org.hibernate.annotations.SQLDeleteAll;
+import org.hibernate.annotations.SQLInsert;
+import org.hibernate.annotations.SQLUpdate;
+import org.hibernate.annotations.Tables;
+import org.hibernate.annotations.Tuplizer;
+import org.hibernate.annotations.Tuplizers;
+import org.hibernate.annotations.Where;
+import org.hibernate.annotations.common.reflection.XAnnotatedElement;
+import org.hibernate.annotations.common.reflection.XClass;
+import org.hibernate.cfg.AnnotationBinder;
+import org.hibernate.cfg.BinderHelper;
+import org.hibernate.cfg.Ejb3JoinColumn;
+import org.hibernate.cfg.ExtendedMappings;
+import org.hibernate.cfg.InheritanceState;
+import org.hibernate.cfg.PropertyHolder;
+import org.hibernate.engine.ExecuteUpdateResultCheckStyle;
+import org.hibernate.engine.FilterDefinition;
+import org.hibernate.engine.Versioning;
+import org.hibernate.mapping.DependantValue;
+import org.hibernate.mapping.Join;
+import org.hibernate.mapping.PersistentClass;
+import org.hibernate.mapping.RootClass;
+import org.hibernate.mapping.SimpleValue;
+import org.hibernate.mapping.Table;
+import org.hibernate.mapping.TableOwner;
+import org.hibernate.mapping.Value;
+import org.hibernate.util.ReflectHelper;
+import org.hibernate.util.StringHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Stateful holder and processor for binding Entity information
+ *
+ * @author Emmanuel Bernard
+ */
+public class EntityBinder {
+ private String name;
+ private XClass annotatedClass;
+ private PersistentClass persistentClass;
+ private ExtendedMappings mappings;
+ private Logger log = LoggerFactory.getLogger( EntityBinder.class );
+ private String discriminatorValue = "";
+ private boolean isPropertyAnnotated = false;
+ private boolean dynamicInsert;
+ private boolean dynamicUpdate;
+ private boolean explicitHibernateEntityAnnotation;
+ private OptimisticLockType optimisticLockType;
+ private PolymorphismType polymorphismType;
+ private boolean selectBeforeUpdate;
+ private int batchSize;
+ private boolean lazy;
+ private XClass proxyClass;
+ private String where;
+ private java.util.Map<String, Join> secondaryTables = new HashMap<String, Join>();
+ private java.util.Map<String, Object> secondaryTableJoins = new HashMap<String, Object>();
+ private String cacheConcurrentStrategy;
+ private String cacheRegion;
+ private java.util.Map<String, String> filters = new HashMap<String, String>();
+ private InheritanceState inheritanceState;
+ private boolean ignoreIdAnnotations;
+ private boolean cacheLazyProperty;
+ private String propertyAccessor;
+
+ public boolean isPropertyAnnotated() {
+ return isPropertyAnnotated;
+ }
+
+ /**
+ * Use as a fake one for Collection of elements
+ */
+ public EntityBinder() {
+ }
+
+ public EntityBinder(
+ Entity ejb3Ann, org.hibernate.annotations.Entity hibAnn,
+ XClass annotatedClass, PersistentClass persistentClass,
+ ExtendedMappings mappings
+ ) {
+ this.mappings = mappings;
+ this.persistentClass = persistentClass;
+ this.annotatedClass = annotatedClass;
+ bindEjb3Annotation( ejb3Ann );
+ bindHibernateAnnotation( hibAnn );
+ }
+
+ private void bindHibernateAnnotation(org.hibernate.annotations.Entity hibAnn) {
+ if ( hibAnn != null ) {
+ dynamicInsert = hibAnn.dynamicInsert();
+ dynamicUpdate = hibAnn.dynamicUpdate();
+ optimisticLockType = hibAnn.optimisticLock();
+ selectBeforeUpdate = hibAnn.selectBeforeUpdate();
+ polymorphismType = hibAnn.polymorphism();
+ explicitHibernateEntityAnnotation = true;
+ //persister handled in bind
+ }
+ else {
+ //default values when the annotation is not there
+ dynamicInsert = false;
+ dynamicUpdate = false;
+ optimisticLockType = OptimisticLockType.VERSION;
+ polymorphismType = PolymorphismType.IMPLICIT;
+ selectBeforeUpdate = false;
+ }
+ }
+
+ private void bindEjb3Annotation(Entity ejb3Ann) {
+ if ( ejb3Ann == null ) throw new AssertionFailure( "@Entity should always be not null" );
+ if ( BinderHelper.isDefault( ejb3Ann.name() ) ) {
+ name = StringHelper.unqualify( annotatedClass.getName() );
+ }
+ else {
+ name = ejb3Ann.name();
+ }
+ }
+
+ public void setDiscriminatorValue(String discriminatorValue) {
+ this.discriminatorValue = discriminatorValue;
+ }
+
+ public void bindEntity() {
+ persistentClass.setAbstract( annotatedClass.isAbstract() );
+ persistentClass.setClassName( annotatedClass.getName() );
+ persistentClass.setNodeName( name );
+ //persistentClass.setDynamic(false); //no longer needed with the Entity name refactoring?
+ persistentClass.setEntityName( annotatedClass.getName() );
+ bindDiscriminatorValue();
+
+ persistentClass.setLazy( lazy );
+ if ( proxyClass != null ) {
+ persistentClass.setProxyInterfaceName( proxyClass.getName() );
+ }
+ persistentClass.setDynamicInsert( dynamicInsert );
+ persistentClass.setDynamicUpdate( dynamicUpdate );
+
+ if ( persistentClass instanceof RootClass ) {
+ RootClass rootClass = (RootClass) persistentClass;
+ boolean mutable = true;
+ //priority on @Immutable, then @Entity.mutable()
+ if ( annotatedClass.isAnnotationPresent( Immutable.class ) ) {
+ mutable = false;
+ }
+ else {
+ org.hibernate.annotations.Entity entityAnn =
+ annotatedClass.getAnnotation( org.hibernate.annotations.Entity.class );
+ if ( entityAnn != null ) {
+ mutable = entityAnn.mutable();
+ }
+ }
+ rootClass.setMutable( mutable );
+ rootClass.setExplicitPolymorphism( isExplicitPolymorphism( polymorphismType ) );
+ if ( StringHelper.isNotEmpty( where ) ) rootClass.setWhere( where );
+ if ( cacheConcurrentStrategy != null ) {
+ rootClass.setCacheConcurrencyStrategy( cacheConcurrentStrategy );
+ rootClass.setCacheRegionName( cacheRegion );
+ rootClass.setLazyPropertiesCacheable( cacheLazyProperty );
+ }
+ rootClass.setForceDiscriminator( annotatedClass.isAnnotationPresent( ForceDiscriminator.class ) );
+ }
+ else {
+ if ( explicitHibernateEntityAnnotation ) {
+ log.warn( "@org.hibernate.annotations.Entity used on a non root entity: ignored for {}",
+ annotatedClass.getName() );
+ }
+ if ( annotatedClass.isAnnotationPresent( Immutable.class ) ) {
+ log.warn( "@Immutable used on a non root entity: ignored for {}",
+ annotatedClass.getName() );
+ }
+ }
+ persistentClass.setOptimisticLockMode( getVersioning( optimisticLockType ) );
+ persistentClass.setSelectBeforeUpdate( selectBeforeUpdate );
+
+ //set persister if needed
+ //@Persister has precedence over @Entity.persister
+ Persister persisterAnn = annotatedClass.getAnnotation( Persister.class );
+ Class persister = null;
+ if ( persisterAnn != null ) {
+ persister = persisterAnn.impl();
+ }
+ else {
+ org.hibernate.annotations.Entity entityAnn = annotatedClass.getAnnotation( org.hibernate.annotations.Entity.class );
+ if ( entityAnn != null && !BinderHelper.isDefault( entityAnn.persister() ) ) {
+ try {
+ persister = ReflectHelper.classForName( entityAnn.persister() );
+ }
+ catch (ClassNotFoundException cnfe) {
+ throw new AnnotationException( "Could not find persister class: " + persister );
+ }
+ }
+ }
+ if ( persister != null ) persistentClass.setEntityPersisterClass( persister );
+
+ persistentClass.setBatchSize( batchSize );
+
+ //SQL overriding
+ SQLInsert sqlInsert = annotatedClass.getAnnotation( SQLInsert.class );
+ SQLUpdate sqlUpdate = annotatedClass.getAnnotation( SQLUpdate.class );
+ SQLDelete sqlDelete = annotatedClass.getAnnotation( SQLDelete.class );
+ SQLDeleteAll sqlDeleteAll = annotatedClass.getAnnotation( SQLDeleteAll.class );
+ Loader loader = annotatedClass.getAnnotation( Loader.class );
+ if ( sqlInsert != null ) {
+ persistentClass.setCustomSQLInsert( sqlInsert.sql().trim(), sqlInsert.callable(),
+ ExecuteUpdateResultCheckStyle.parse( sqlInsert.check().toString().toLowerCase() )
+ );
+
+ }
+ if ( sqlUpdate != null ) {
+ persistentClass.setCustomSQLUpdate( sqlUpdate.sql(), sqlUpdate.callable(),
+ ExecuteUpdateResultCheckStyle.parse( sqlUpdate.check().toString().toLowerCase() )
+ );
+ }
+ if ( sqlDelete != null ) {
+ persistentClass.setCustomSQLDelete( sqlDelete.sql(), sqlDelete.callable(),
+ ExecuteUpdateResultCheckStyle.parse( sqlDelete.check().toString().toLowerCase() )
+ );
+ }
+ if ( sqlDeleteAll != null ) {
+ persistentClass.setCustomSQLDelete( sqlDeleteAll.sql(), sqlDeleteAll.callable(),
+ ExecuteUpdateResultCheckStyle.parse( sqlDeleteAll.check().toString().toLowerCase() )
+ );
+ }
+ if ( loader != null ) {
+ persistentClass.setLoaderName( loader.namedQuery() );
+ }
+
+ //tuplizers
+ if ( annotatedClass.isAnnotationPresent( Tuplizers.class ) ) {
+ for (Tuplizer tuplizer : annotatedClass.getAnnotation( Tuplizers.class ).value()) {
+ EntityMode mode = EntityMode.parse( tuplizer.entityMode() );
+ persistentClass.addTuplizer( mode, tuplizer.impl().getName() );
+ }
+ }
+ if ( annotatedClass.isAnnotationPresent( Tuplizer.class ) ) {
+ Tuplizer tuplizer = annotatedClass.getAnnotation( Tuplizer.class );
+ EntityMode mode = EntityMode.parse( tuplizer.entityMode() );
+ persistentClass.addTuplizer( mode, tuplizer.impl().getName() );
+ }
+
+ if ( !inheritanceState.hasParents ) {
+ Iterator<Map.Entry<String, String>> iter = filters.entrySet().iterator();
+ while ( iter.hasNext() ) {
+ Map.Entry<String, String> filter = iter.next();
+ String filterName = filter.getKey();
+ String cond = filter.getValue();
+ if ( BinderHelper.isDefault( cond ) ) {
+ FilterDefinition definition = mappings.getFilterDefinition( filterName );
+ cond = definition == null ? null : definition.getDefaultFilterCondition();
+ if ( StringHelper.isEmpty( cond ) ) {
+ throw new AnnotationException(
+ "no filter condition found for filter " + filterName + " in " + this.name
+ );
+ }
+ }
+ persistentClass.addFilter( filterName, cond );
+ }
+ }
+ else {
+ if ( filters.size() > 0 ) {
+ log.warn( "@Filter not allowed on subclasses (ignored): {}", persistentClass.getEntityName() );
+ }
+ }
+ log.debug( "Import with entity name {}", name );
+ try {
+ mappings.addImport( persistentClass.getEntityName(), name );
+ String entityName = persistentClass.getEntityName();
+ if ( !entityName.equals( name ) ) {
+ mappings.addImport( entityName, entityName );
+ }
+ }
+ catch (MappingException me) {
+ throw new AnnotationException( "Use of the same entity name twice: " + name, me );
+ }
+ }
+
+ public void bindDiscriminatorValue() {
+ if ( StringHelper.isEmpty( discriminatorValue ) ) {
+ Value discriminator = persistentClass.getDiscriminator();
+ if ( discriminator == null ) {
+ persistentClass.setDiscriminatorValue( name );
+ }
+ else if ( "character".equals( discriminator.getType().getName() ) ) {
+ throw new AnnotationException(
+ "Using default @DiscriminatorValue for a discriminator of type CHAR is not safe"
+ );
+ }
+ else if ( "integer".equals( discriminator.getType().getName() ) ) {
+ persistentClass.setDiscriminatorValue( String.valueOf( name.hashCode() ) );
+ }
+ else {
+ persistentClass.setDiscriminatorValue( name ); //Spec compliant
+ }
+ }
+ else {
+ //persistentClass.getDiscriminator()
+ persistentClass.setDiscriminatorValue( discriminatorValue );
+ }
+ }
+
+ int getVersioning(OptimisticLockType type) {
+ switch ( type ) {
+ case VERSION:
+ return Versioning.OPTIMISTIC_LOCK_VERSION;
+ case NONE:
+ return Versioning.OPTIMISTIC_LOCK_NONE;
+ case DIRTY:
+ return Versioning.OPTIMISTIC_LOCK_DIRTY;
+ case ALL:
+ return Versioning.OPTIMISTIC_LOCK_ALL;
+ default:
+ throw new AssertionFailure( "optimistic locking not supported: " + type );
+ }
+ }
+
+ private boolean isExplicitPolymorphism(PolymorphismType type) {
+ switch ( type ) {
+ case IMPLICIT:
+ return false;
+ case EXPLICIT:
+ return true;
+ default:
+ throw new AssertionFailure( "Unknown polymorphism type: " + type );
+ }
+ }
+
+ public void setBatchSize(BatchSize sizeAnn) {
+ if ( sizeAnn != null ) {
+ batchSize = sizeAnn.size();
+ }
+ else {
+ batchSize = -1;
+ }
+ }
+
+ public void setProxy(Proxy proxy) {
+ if ( proxy != null ) {
+ lazy = proxy.lazy();
+ if ( !lazy ) {
+ proxyClass = null;
+ }
+ else {
+ if ( AnnotationBinder.isDefault(
+ mappings.getReflectionManager().toXClass( proxy.proxyClass() ), mappings
+ ) ) {
+ proxyClass = annotatedClass;
+ }
+ else {
+ proxyClass = mappings.getReflectionManager().toXClass( proxy.proxyClass() );
+ }
+ }
+ }
+ else {
+ lazy = true; //needed to allow association lazy loading.
+ proxyClass = annotatedClass;
+ }
+ }
+
+ public void setWhere(Where whereAnn) {
+ if ( whereAnn != null ) {
+ where = whereAnn.clause();
+ }
+ }
+
+ private String getClassTableName(String tableName) {
+ if ( StringHelper.isEmpty( tableName ) ) {
+ return mappings.getNamingStrategy().classToTableName( name );
+ }
+ else {
+ return mappings.getNamingStrategy().tableName( tableName );
+ }
+ }
+
+ public void bindTable(
+ String schema, String catalog,
+ String tableName, List uniqueConstraints,
+ String constraints, Table denormalizedSuperclassTable
+ ) {
+ String logicalName = StringHelper.isNotEmpty( tableName ) ?
+ tableName :
+ StringHelper.unqualify( name );
+ Table table = TableBinder.fillTable(
+ schema, catalog,
+ getClassTableName( tableName ),
+ logicalName,
+ persistentClass.isAbstract(), uniqueConstraints, constraints,
+ denormalizedSuperclassTable, mappings
+ );
+
+ if ( persistentClass instanceof TableOwner ) {
+ log.info( "Bind entity {} on table {}", persistentClass.getEntityName(), table.getName() );
+ ( (TableOwner) persistentClass ).setTable( table );
+ }
+ else {
+ throw new AssertionFailure( "binding a table for a subclass" );
+ }
+ }
+
+ public void finalSecondaryTableBinding(PropertyHolder propertyHolder) {
+ /*
+ * Those operations has to be done after the id definition of the persistence class.
+ * ie after the properties parsing
+ */
+ Iterator joins = secondaryTables.values().iterator();
+ Iterator joinColumns = secondaryTableJoins.values().iterator();
+
+ while ( joins.hasNext() ) {
+ Object uncastedColumn = joinColumns.next();
+ Join join = (Join) joins.next();
+ createPrimaryColumnsToSecondaryTable( uncastedColumn, propertyHolder, join );
+ }
+ mappings.addJoins( persistentClass, secondaryTables );
+ }
+
+ private void createPrimaryColumnsToSecondaryTable(Object uncastedColumn, PropertyHolder propertyHolder, Join join) {
+ Ejb3JoinColumn[] ejb3JoinColumns;
+ PrimaryKeyJoinColumn[] pkColumnsAnn = null;
+ JoinColumn[] joinColumnsAnn = null;
+ if ( uncastedColumn instanceof PrimaryKeyJoinColumn[] ) {
+ pkColumnsAnn = (PrimaryKeyJoinColumn[]) uncastedColumn;
+ }
+ if ( uncastedColumn instanceof JoinColumn[] ) {
+ joinColumnsAnn = (JoinColumn[]) uncastedColumn;
+ }
+ if ( pkColumnsAnn == null && joinColumnsAnn == null ) {
+ ejb3JoinColumns = new Ejb3JoinColumn[1];
+ ejb3JoinColumns[0] = Ejb3JoinColumn.buildJoinColumn(
+ null,
+ null,
+ persistentClass.getIdentifier(),
+ secondaryTables,
+ propertyHolder, mappings
+ );
+ }
+ else {
+ int nbrOfJoinColumns = pkColumnsAnn != null ?
+ pkColumnsAnn.length :
+ joinColumnsAnn.length;
+ if ( nbrOfJoinColumns == 0 ) {
+ ejb3JoinColumns = new Ejb3JoinColumn[1];
+ ejb3JoinColumns[0] = Ejb3JoinColumn.buildJoinColumn(
+ null,
+ null,
+ persistentClass.getIdentifier(),
+ secondaryTables,
+ propertyHolder, mappings
+ );
+ }
+ else {
+ ejb3JoinColumns = new Ejb3JoinColumn[nbrOfJoinColumns];
+ if ( pkColumnsAnn != null ) {
+ for (int colIndex = 0; colIndex < nbrOfJoinColumns; colIndex++) {
+ ejb3JoinColumns[colIndex] = Ejb3JoinColumn.buildJoinColumn(
+ pkColumnsAnn[colIndex],
+ null,
+ persistentClass.getIdentifier(),
+ secondaryTables,
+ propertyHolder, mappings
+ );
+ }
+ }
+ else {
+ for (int colIndex = 0; colIndex < nbrOfJoinColumns; colIndex++) {
+ ejb3JoinColumns[colIndex] = Ejb3JoinColumn.buildJoinColumn(
+ null,
+ joinColumnsAnn[colIndex],
+ persistentClass.getIdentifier(),
+ secondaryTables,
+ propertyHolder, mappings
+ );
+ }
+ }
+ }
+ }
+
+ for (Ejb3JoinColumn joinColumn : ejb3JoinColumns) {
+ joinColumn.forceNotNull();
+ }
+ bindJoinToPersistentClass( join, ejb3JoinColumns );
+ }
+
+ private void bindJoinToPersistentClass(
+ Join join, Ejb3JoinColumn[] ejb3JoinColumns
+ ) {
+ SimpleValue key = new DependantValue( join.getTable(), persistentClass.getIdentifier() );
+ join.setKey( key );
+ setFKNameIfDefined( join );
+ key.setCascadeDeleteEnabled( false );
+ TableBinder.bindFk( persistentClass, null, ejb3JoinColumns, key, false, mappings );
+ join.createPrimaryKey();
+ join.createForeignKey();
+ persistentClass.addJoin( join );
+ }
+
+ private void setFKNameIfDefined(Join join) {
+ org.hibernate.annotations.Table matchingTable = findMatchingComplimentTableAnnotation( join );
+ if ( matchingTable != null && !BinderHelper.isDefault( matchingTable.foreignKey().name() ) ) {
+ ( (SimpleValue) join.getKey() ).setForeignKeyName( matchingTable.foreignKey().name() );
+ }
+ }
+
+ private org.hibernate.annotations.Table findMatchingComplimentTableAnnotation(Join join) {
+ String tableName = join.getTable().getQuotedName();
+ org.hibernate.annotations.Table table = annotatedClass.getAnnotation( org.hibernate.annotations.Table.class );
+ org.hibernate.annotations.Table matchingTable = null;
+ if ( table != null && tableName.equals( table.appliesTo() ) ) {
+ matchingTable = table;
+ }
+ else {
+ Tables tables = annotatedClass.getAnnotation( Tables.class );
+ if ( tables != null ) {
+ for (org.hibernate.annotations.Table current : tables.value()) {
+ if ( tableName.equals( current.appliesTo() ) ) {
+ matchingTable = current;
+ break;
+ }
+ }
+ }
+ }
+ return matchingTable;
+ }
+
+ public void firstLevelSecondaryTablesBinding(
+ SecondaryTable secTable, SecondaryTables secTables
+ ) {
+ if ( secTables != null ) {
+ //loop through it
+ for (SecondaryTable tab : secTables.value()) {
+ addJoin( tab, null, null, false );
+ }
+ }
+ else {
+ if ( secTable != null ) addJoin( secTable, null, null, false );
+ }
+ }
+
+ //Used for @*ToMany @JoinTable
+ public Join addJoin(JoinTable joinTable, PropertyHolder holder, boolean noDelayInPkColumnCreation) {
+ return addJoin( null, joinTable, holder, noDelayInPkColumnCreation );
+ }
+
+ /**
+ * A non null propertyHolder means than we process the Pk creation without delay
+ */
+ private Join addJoin(
+ SecondaryTable secondaryTable, JoinTable joinTable, PropertyHolder propertyHolder,
+ boolean noDelayInPkColumnCreation
+ ) {
+ Join join = new Join();
+ join.setPersistentClass( persistentClass );
+ String schema;
+ String catalog;
+ String table;
+ String realTable;
+ UniqueConstraint[] uniqueConstraintsAnn;
+ if ( secondaryTable != null ) {
+ schema = secondaryTable.schema();
+ catalog = secondaryTable.catalog();
+ table = secondaryTable.name();
+ realTable = mappings.getNamingStrategy().tableName( table ); //always an explicit table name
+ uniqueConstraintsAnn = secondaryTable.uniqueConstraints();
+ }
+ else if ( joinTable != null ) {
+ schema = joinTable.schema();
+ catalog = joinTable.catalog();
+ table = joinTable.name();
+ realTable = mappings.getNamingStrategy().tableName( table ); //always an explicit table name
+ uniqueConstraintsAnn = joinTable.uniqueConstraints();
+ }
+ else {
+ throw new AssertionFailure( "Both JoinTable and SecondaryTable are null" );
+ }
+ List uniqueConstraints = new ArrayList( uniqueConstraintsAnn == null ?
+ 0 :
+ uniqueConstraintsAnn.length );
+ if ( uniqueConstraintsAnn != null && uniqueConstraintsAnn.length != 0 ) {
+ for (UniqueConstraint uc : uniqueConstraintsAnn) {
+ uniqueConstraints.add( uc.columnNames() );
+ }
+ }
+ Table tableMapping = TableBinder.fillTable(
+ schema,
+ catalog,
+ realTable,
+ table, false, uniqueConstraints, null, null, mappings
+ );
+ //no check constraints available on joins
+ join.setTable( tableMapping );
+
+ //somehow keep joins() for later.
+ //Has to do the work later because it needs persistentClass id!
+ Object joinColumns = null;
+ //get the appropriate pk columns
+ if ( secondaryTable != null ) {
+ joinColumns = secondaryTable.pkJoinColumns();
+ }
+ else if ( joinTable != null ) {
+ joinColumns = joinTable.joinColumns();
+ }
+ log.info(
+ "Adding secondary table to entity {} -> {}", persistentClass.getEntityName(), join.getTable().getName()
+ );
+
+ org.hibernate.annotations.Table matchingTable = findMatchingComplimentTableAnnotation( join );
+ if ( matchingTable != null ) {
+ join.setSequentialSelect( FetchMode.JOIN != matchingTable.fetch() );
+ join.setInverse( matchingTable.inverse() );
+ join.setOptional( matchingTable.optional() );
+ if ( !BinderHelper.isDefault( matchingTable.sqlInsert().sql() ) ) {
+ join.setCustomSQLInsert( matchingTable.sqlInsert().sql().trim(),
+ matchingTable.sqlInsert().callable(),
+ ExecuteUpdateResultCheckStyle.parse( matchingTable.sqlInsert().check().toString().toLowerCase() )
+ );
+ }
+ if ( !BinderHelper.isDefault( matchingTable.sqlUpdate().sql() ) ) {
+ join.setCustomSQLUpdate( matchingTable.sqlUpdate().sql().trim(),
+ matchingTable.sqlUpdate().callable(),
+ ExecuteUpdateResultCheckStyle.parse( matchingTable.sqlUpdate().check().toString().toLowerCase() )
+ );
+ }
+ if ( !BinderHelper.isDefault( matchingTable.sqlDelete().sql() ) ) {
+ join.setCustomSQLDelete( matchingTable.sqlDelete().sql().trim(),
+ matchingTable.sqlDelete().callable(),
+ ExecuteUpdateResultCheckStyle.parse( matchingTable.sqlDelete().check().toString().toLowerCase() )
+ );
+ }
+ }
+ else {
+ //default
+ join.setSequentialSelect( false );
+ join.setInverse( false );
+ join.setOptional( true ); //perhaps not quite per-spec, but a Good Thing anyway
+ }
+
+ if ( noDelayInPkColumnCreation ) {
+ createPrimaryColumnsToSecondaryTable( joinColumns, propertyHolder, join );
+ }
+ else {
+ secondaryTables.put( realTable, join );
+ secondaryTableJoins.put( realTable, joinColumns );
+ }
+ return join;
+ }
+
+ public java.util.Map<String, Join> getSecondaryTables() {
+ return secondaryTables;
+ }
+
+ public void setCache(Cache cacheAnn) {
+ if ( cacheAnn != null ) {
+ cacheRegion = BinderHelper.isDefault( cacheAnn.region() ) ?
+ null :
+ cacheAnn.region();
+ cacheConcurrentStrategy = getCacheConcurrencyStrategy( cacheAnn.usage() );
+ if ( "all".equalsIgnoreCase( cacheAnn.include() ) ) {
+ cacheLazyProperty = true;
+ }
+ else if ( "non-lazy".equalsIgnoreCase( cacheAnn.include() ) ) {
+ cacheLazyProperty = false;
+ }
+ else {
+ throw new AnnotationException( "Unknown lazy property annotations: " + cacheAnn.include() );
+ }
+ }
+ else {
+ cacheConcurrentStrategy = null;
+ cacheRegion = null;
+ cacheLazyProperty = true;
+ }
+ }
+
+ public static String getCacheConcurrencyStrategy(CacheConcurrencyStrategy strategy) {
+ switch ( strategy ) {
+ case NONE:
+ return null;
+ case READ_ONLY:
+ return org.hibernate.cache.access.AccessType.READ_ONLY.getName();
+ case READ_WRITE:
+ return org.hibernate.cache.access.AccessType.READ_WRITE.getName();
+ case NONSTRICT_READ_WRITE:
+ return org.hibernate.cache.access.AccessType.NONSTRICT_READ_WRITE.getName();
+ case TRANSACTIONAL:
+ return org.hibernate.cache.access.AccessType.TRANSACTIONAL.getName();
+ default:
+ throw new AssertionFailure( "CacheConcurrencyStrategy unknown: " + strategy );
+ }
+ }
+
+ public void addFilter(String name, String condition) {
+ filters.put( name, condition );
+ }
+
+ public void setInheritanceState(InheritanceState inheritanceState) {
+ this.inheritanceState = inheritanceState;
+ }
+
+ public boolean isIgnoreIdAnnotations() {
+ return ignoreIdAnnotations;
+ }
+
+ public void setIgnoreIdAnnotations(boolean ignoreIdAnnotations) {
+ this.ignoreIdAnnotations = ignoreIdAnnotations;
+ }
+
+ public void processComplementaryTableDefinitions(org.hibernate.annotations.Table table) {
+ //comment and index are processed here
+ if ( table == null ) return;
+ String appliedTable = table.appliesTo();
+ Iterator tables = persistentClass.getTableClosureIterator();
+ Table hibTable = null;
+ while ( tables.hasNext() ) {
+ Table pcTable = (Table) tables.next();
+ if ( pcTable.getQuotedName().equals( appliedTable ) ) {
+ //we are in the correct table to find columns
+ hibTable = pcTable;
+ break;
+ }
+ hibTable = null;
+ }
+ if ( hibTable == null ) {
+ //maybe a join/secondary table
+ for ( Join join : secondaryTables.values() ) {
+ if ( join.getTable().getQuotedName().equals( appliedTable ) ) {
+ hibTable = join.getTable();
+ break;
+ }
+ }
+ }
+ if ( hibTable == null ) {
+ throw new AnnotationException(
+ "@org.hibernate.annotations.Table references an unknown table: " + appliedTable
+ );
+ }
+ if ( !BinderHelper.isDefault( table.comment() ) ) hibTable.setComment( table.comment() );
+ TableBinder.addIndexes( hibTable, table.indexes(), mappings );
+ }
+
+ public void processComplementaryTableDefinitions(Tables tables) {
+ if ( tables == null ) return;
+ for (org.hibernate.annotations.Table table : tables.value()) {
+ processComplementaryTableDefinitions( table );
+ }
+ }
+
+ public void setPropertyAnnotated(boolean propertyAnnotated) {
+ this.isPropertyAnnotated = propertyAnnotated;
+ }
+
+ public String getPropertyAccessor() {
+ return propertyAccessor;
+ }
+
+ public void setPropertyAccessor(String propertyAccessor) {
+ this.propertyAccessor = propertyAccessor;
+ }
+
+ public boolean isPropertyAnnotated(XAnnotatedElement element) {
+ AccessType access = element.getAnnotation( AccessType.class );
+ if ( access == null ) return isPropertyAnnotated;
+ String propertyAccessor = access.value();
+ if ( "property".equals( propertyAccessor ) ) {
+ return Boolean.TRUE;
+ }
+ else if ( "field".equals( propertyAccessor ) ) {
+ return Boolean.FALSE;
+ }
+ else {
+ return isPropertyAnnotated;
+ }
+ }
+
+ public String getPropertyAccessor(XAnnotatedElement element) {
+ AccessType access = element.getAnnotation( AccessType.class );
+ if ( access == null ) return propertyAccessor;
+ return access.value();
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/IdBagBinder.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/IdBagBinder.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/IdBagBinder.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,89 @@
+//$Id: IdBagBinder.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.cfg.annotations;
+
+import java.util.Collections;
+import java.util.Map;
+
+import org.hibernate.AnnotationException;
+import org.hibernate.annotations.CollectionId;
+import org.hibernate.annotations.Type;
+import org.hibernate.annotations.common.reflection.XClass;
+import org.hibernate.annotations.common.reflection.XProperty;
+import org.hibernate.cfg.BinderHelper;
+import org.hibernate.cfg.Ejb3Column;
+import org.hibernate.cfg.Ejb3JoinColumn;
+import org.hibernate.cfg.ExtendedMappings;
+import org.hibernate.cfg.PropertyData;
+import org.hibernate.cfg.PropertyInferredData;
+import org.hibernate.cfg.WrappedInferredData;
+import org.hibernate.mapping.Collection;
+import org.hibernate.mapping.IdentifierCollection;
+import org.hibernate.mapping.PersistentClass;
+import org.hibernate.mapping.SimpleValue;
+import org.hibernate.mapping.Table;
+import org.hibernate.util.StringHelper;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class IdBagBinder extends BagBinder {
+ protected Collection createCollection(PersistentClass persistentClass) {
+ return new org.hibernate.mapping.IdentifierBag( persistentClass );
+ }
+
+ @Override
+ protected boolean bindStarToManySecondPass(
+ Map persistentClasses, XClass collType, Ejb3JoinColumn[] fkJoinColumns, Ejb3JoinColumn[] keyColumns,
+ Ejb3JoinColumn[] inverseColumns, Ejb3Column[] elementColumns, boolean isEmbedded, XProperty property,
+ boolean unique, TableBinder associationTableBinder, boolean ignoreNotFound, ExtendedMappings mappings
+ ) {
+ boolean result = super.bindStarToManySecondPass(
+ persistentClasses, collType, fkJoinColumns, keyColumns, inverseColumns, elementColumns, isEmbedded,
+ property, unique, associationTableBinder, ignoreNotFound, mappings
+ );
+ CollectionId collectionIdAnn = property.getAnnotation( CollectionId.class );
+ if ( collectionIdAnn != null ) {
+ SimpleValueBinder simpleValue = new SimpleValueBinder();
+
+ PropertyData propertyData = new WrappedInferredData(
+ new PropertyInferredData( property, null, //default access should not be useful
+ mappings.getReflectionManager() ),
+ "id" );
+ Ejb3Column[] idColumns = Ejb3Column.buildColumnFromAnnotation(
+ collectionIdAnn.columns(),
+ null,
+ Nullability.FORCED_NOT_NULL,
+ propertyHolder,
+ propertyData,
+ Collections.EMPTY_MAP,
+ mappings
+ );
+ Table table = collection.getCollectionTable();
+ simpleValue.setTable( table );
+ simpleValue.setColumns( idColumns );
+ Type typeAnn = collectionIdAnn.type();
+ if ( typeAnn != null && !BinderHelper.isDefault( typeAnn.type() ) ) {
+ simpleValue.setExplicitType( typeAnn );
+ }
+ else {
+ throw new AnnotationException( "@CollectionId is missing type: "
+ + StringHelper.qualify( propertyHolder.getPath(), propertyName ) );
+ }
+ simpleValue.setMappings( mappings );
+ SimpleValue id = simpleValue.make();
+ ( (IdentifierCollection) collection ).setIdentifier( id );
+ String generator = collectionIdAnn.generator();
+ String generatorType;
+ if ( "identity".equals( generator ) || "assigned".equals( generator )
+ || "sequence".equals( generator ) || "native".equals( generator ) ) {
+ generatorType = generator;
+ generator = "";
+ }
+ else {
+ generatorType = null;
+ }
+ BinderHelper.makeIdGenerator( id, generatorType, generator, mappings, localGenerators );
+ }
+ return result;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/ListBinder.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/ListBinder.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/ListBinder.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,115 @@
+package org.hibernate.cfg.annotations;
+
+import java.util.Map;
+
+import org.hibernate.AnnotationException;
+import org.hibernate.MappingException;
+import org.hibernate.annotations.OrderBy;
+import org.hibernate.annotations.Sort;
+import org.hibernate.annotations.common.reflection.XClass;
+import org.hibernate.annotations.common.reflection.XProperty;
+import org.hibernate.annotations.common.util.StringHelper;
+import org.hibernate.cfg.CollectionSecondPass;
+import org.hibernate.cfg.Ejb3Column;
+import org.hibernate.cfg.Ejb3JoinColumn;
+import org.hibernate.cfg.ExtendedMappings;
+import org.hibernate.cfg.PropertyHolder;
+import org.hibernate.cfg.PropertyHolderBuilder;
+import org.hibernate.cfg.SecondPass;
+import org.hibernate.mapping.Collection;
+import org.hibernate.mapping.IndexBackref;
+import org.hibernate.mapping.List;
+import org.hibernate.mapping.OneToMany;
+import org.hibernate.mapping.PersistentClass;
+import org.hibernate.mapping.SimpleValue;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Bind a list to the underlying Hibernate configuration
+ *
+ * @author Matthew Inger
+ * @author Emmanuel Bernard
+ */
+@SuppressWarnings({"unchecked", "serial"})
+public class ListBinder extends CollectionBinder {
+ private Logger log = LoggerFactory.getLogger( ListBinder.class );
+
+ public ListBinder() {
+ }
+
+ protected Collection createCollection(PersistentClass persistentClass) {
+ return new org.hibernate.mapping.List( persistentClass );
+ }
+
+ public void setSqlOrderBy(OrderBy orderByAnn) {
+ if ( orderByAnn != null ) log.warn( "@OrderBy not allowed for a indexed collection, annotation ignored." );
+ }
+
+ public void setSort(Sort sortAnn) {
+ if ( sortAnn != null ) log.warn( "@Sort not allowed for a indexed collection, annotation ignored." );
+ }
+
+ @Override
+ public SecondPass getSecondPass(
+ final Ejb3JoinColumn[] fkJoinColumns, final Ejb3JoinColumn[] keyColumns,
+ final Ejb3JoinColumn[] inverseColumns,
+ final Ejb3Column[] elementColumns,
+ Ejb3Column[] mapKeyColumns, final Ejb3JoinColumn[] mapKeyManyToManyColumns, final boolean isEmbedded,
+ final XProperty property, final XClass collType,
+ final boolean ignoreNotFound, final boolean unique,
+ final TableBinder assocTableBinder, final ExtendedMappings mappings
+ ) {
+ return new CollectionSecondPass( mappings, ListBinder.this.collection ) {
+ public void secondPass(Map persistentClasses, Map inheritedMetas)
+ throws MappingException {
+ bindStarToManySecondPass(
+ persistentClasses, collType, fkJoinColumns, keyColumns, inverseColumns, elementColumns,
+ isEmbedded, property, unique, assocTableBinder, ignoreNotFound, mappings
+ );
+ bindIndex( mappings );
+ }
+ };
+ }
+
+ private void bindIndex(final ExtendedMappings mappings) {
+ if ( indexColumn.isImplicit() == false ) {
+ PropertyHolder valueHolder = PropertyHolderBuilder.buildPropertyHolder(
+ this.collection,
+ StringHelper.qualify( this.collection.getRole(), "key" ),
+ (XClass) null,
+ (XProperty) null, propertyHolder, mappings
+ );
+ List list = (List) this.collection;
+ if ( !list.isOneToMany() ) indexColumn.forceNotNull();
+ indexColumn.setPropertyHolder( valueHolder );
+ SimpleValueBinder value = new SimpleValueBinder();
+ value.setColumns( new Ejb3Column[] { indexColumn } );
+ value.setExplicitType( "integer" );
+ value.setMappings( mappings );
+ SimpleValue indexValue = value.make();
+ indexColumn.linkWithValue( indexValue );
+ list.setIndex( indexValue );
+ list.setBaseIndex( indexColumn.getBase() );
+ if ( list.isOneToMany() && !list.getKey().isNullable() && !list.isInverse() ) {
+ String entityName = ( (OneToMany) list.getElement() ).getReferencedEntityName();
+ PersistentClass referenced = mappings.getClass( entityName );
+ IndexBackref ib = new IndexBackref();
+ ib.setName( '_' + propertyName + "IndexBackref" );
+ ib.setUpdateable( false );
+ ib.setSelectable( false );
+ ib.setCollectionRole( list.getRole() );
+ ib.setEntityName( list.getOwner().getEntityName() );
+ ib.setValue( list.getIndex() );
+ referenced.addProperty( ib );
+ }
+ }
+ else {
+ Collection coll = this.collection;
+ throw new AnnotationException(
+ "List/array has to be annotated with an @IndexColumn: "
+ + coll.getRole()
+ );
+ }
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/MapBinder.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/MapBinder.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/MapBinder.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,388 @@
+//$Id: MapBinder.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.cfg.annotations;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Random;
+import javax.persistence.AttributeOverride;
+import javax.persistence.AttributeOverrides;
+
+import org.hibernate.AnnotationException;
+import org.hibernate.AssertionFailure;
+import org.hibernate.FetchMode;
+import org.hibernate.MappingException;
+import org.hibernate.annotations.MapKeyManyToMany;
+import org.hibernate.annotations.MapKey;
+import org.hibernate.annotations.common.reflection.XClass;
+import org.hibernate.annotations.common.reflection.XProperty;
+import org.hibernate.cfg.AnnotatedClassType;
+import org.hibernate.cfg.AnnotationBinder;
+import org.hibernate.cfg.BinderHelper;
+import org.hibernate.cfg.CollectionSecondPass;
+import org.hibernate.cfg.Ejb3Column;
+import org.hibernate.cfg.Ejb3JoinColumn;
+import org.hibernate.cfg.ExtendedMappings;
+import org.hibernate.cfg.PropertyData;
+import org.hibernate.cfg.PropertyHolder;
+import org.hibernate.cfg.PropertyHolderBuilder;
+import org.hibernate.cfg.PropertyPreloadedData;
+import org.hibernate.cfg.SecondPass;
+import org.hibernate.dialect.HSQLDialect;
+import org.hibernate.mapping.Collection;
+import org.hibernate.mapping.Column;
+import org.hibernate.mapping.Component;
+import org.hibernate.mapping.DependantValue;
+import org.hibernate.mapping.Formula;
+import org.hibernate.mapping.Join;
+import org.hibernate.mapping.ManyToOne;
+import org.hibernate.mapping.OneToMany;
+import org.hibernate.mapping.PersistentClass;
+import org.hibernate.mapping.Property;
+import org.hibernate.mapping.SimpleValue;
+import org.hibernate.mapping.ToOne;
+import org.hibernate.mapping.Value;
+import org.hibernate.sql.Template;
+import org.hibernate.util.StringHelper;
+
+/**
+ * Implementation to bind a Map
+ *
+ * @author Emmanuel Bernard
+ */
+public class MapBinder extends CollectionBinder {
+ public MapBinder(boolean sorted) {
+ super( sorted );
+ }
+
+ public MapBinder() {
+ super();
+ }
+
+ protected Collection createCollection(PersistentClass persistentClass) {
+ return new org.hibernate.mapping.Map( persistentClass );
+ }
+
+ @Override
+ public SecondPass getSecondPass(
+ final Ejb3JoinColumn[] fkJoinColumns, final Ejb3JoinColumn[] keyColumns,
+ final Ejb3JoinColumn[] inverseColumns,
+ final Ejb3Column[] elementColumns,
+ final Ejb3Column[] mapKeyColumns, final Ejb3JoinColumn[] mapKeyManyToManyColumns, final boolean isEmbedded,
+ final XProperty property, final XClass collType,
+ final boolean ignoreNotFound, final boolean unique,
+ final TableBinder assocTableBinder, final ExtendedMappings mappings
+ ) {
+ return new CollectionSecondPass( mappings, MapBinder.this.collection ) {
+ public void secondPass(Map persistentClasses, Map inheritedMetas)
+ throws MappingException {
+ bindStarToManySecondPass(
+ persistentClasses, collType, fkJoinColumns, keyColumns, inverseColumns, elementColumns,
+ isEmbedded, property, unique, assocTableBinder, ignoreNotFound, mappings
+ );
+ bindKeyFromAssociationTable(
+ collType, persistentClasses, mapKeyPropertyName, property, isEmbedded, mappings,
+ mapKeyColumns, mapKeyManyToManyColumns,
+ inverseColumns != null ? inverseColumns[0].getPropertyName() : null
+ );
+ }
+ };
+ }
+
+ private void bindKeyFromAssociationTable(
+ XClass collType, Map persistentClasses, String mapKeyPropertyName, XProperty property,
+ boolean isEmbedded, ExtendedMappings mappings, Ejb3Column[] mapKeyColumns,
+ Ejb3JoinColumn[] mapKeyManyToManyColumns, String targetPropertyName
+ ) {
+ if ( mapKeyPropertyName != null ) {
+ //this is an EJB3 @MapKey
+ PersistentClass associatedClass = (PersistentClass) persistentClasses.get( collType.getName() );
+ if ( associatedClass == null ) throw new AnnotationException( "Associated class not found: " + collType );
+ Property mapProperty = BinderHelper.findPropertyByName( associatedClass, mapKeyPropertyName );
+ if ( mapProperty == null ) {
+ throw new AnnotationException(
+ "Map key property not found: " + collType + "." + mapKeyPropertyName
+ );
+ }
+ org.hibernate.mapping.Map map = (org.hibernate.mapping.Map) this.collection;
+ Value indexValue = createFormulatedValue( mapProperty.getValue(), map, targetPropertyName, associatedClass );
+ map.setIndex( indexValue );
+ }
+ else {
+ //this is a true Map mapping
+ //TODO ugly copy/pastle from CollectionBinder.bindManyToManySecondPass
+ String mapKeyType;
+ Class target = void.class;
+ /*
+ * target has priority over reflection for the map key type
+ */
+ if ( property.isAnnotationPresent( org.hibernate.annotations.MapKey.class ) ) {
+ target = property.getAnnotation( org.hibernate.annotations.MapKey.class ).targetElement();
+ }
+ else if ( property.isAnnotationPresent( MapKeyManyToMany.class ) ) {
+ target = property.getAnnotation( MapKeyManyToMany.class ).targetEntity();
+ }
+ if ( !void.class.equals( target ) ) {
+ mapKeyType = target.getName();
+ }
+ else {
+ mapKeyType = property.getMapKey().getName();
+ }
+ PersistentClass collectionEntity = (PersistentClass) persistentClasses.get( mapKeyType );
+ boolean isIndexOfEntities = collectionEntity != null;
+ ManyToOne element = null;
+ org.hibernate.mapping.Map mapValue = (org.hibernate.mapping.Map) this.collection;
+ if ( isIndexOfEntities ) {
+ element = new ManyToOne( mapValue.getCollectionTable() );
+ mapValue.setIndex( element );
+ element.setReferencedEntityName( mapKeyType );
+ //element.setFetchMode( fetchMode );
+ //element.setLazy( fetchMode != FetchMode.JOIN );
+ //make the second join non lazy
+ element.setFetchMode( FetchMode.JOIN );
+ element.setLazy( false );
+ //does not make sense for a map key element.setIgnoreNotFound( ignoreNotFound );
+ }
+ else {
+ XClass elementClass;
+ AnnotatedClassType classType;
+ // Map<String, javax.persistence.Column[]> columnOverrides = PropertyHolderBuilder.buildColumnOverride(
+ // property, StringHelper.qualify( collValue.getRole(), "element" )
+ // );
+ //FIXME the "element" is lost
+ PropertyHolder holder = null;
+ if ( BinderHelper.PRIMITIVE_NAMES.contains( mapKeyType ) ) {
+ classType = AnnotatedClassType.NONE;
+ elementClass = null;
+ }
+ else {
+ try {
+ elementClass = mappings.getReflectionManager().classForName( mapKeyType, MapBinder.class );
+ }
+ catch (ClassNotFoundException e) {
+ throw new AnnotationException( "Unable to find class: " + mapKeyType, e );
+ }
+ classType = mappings.getClassType( elementClass );
+
+ holder = PropertyHolderBuilder.buildPropertyHolder(
+ mapValue,
+ StringHelper.qualify( mapValue.getRole(), "mapkey" ),
+ elementClass,
+ property, propertyHolder, mappings
+ );
+ //force in case of attribute override
+ boolean attributeOverride = property.isAnnotationPresent( AttributeOverride.class )
+ || property.isAnnotationPresent( AttributeOverrides.class );
+ if ( isEmbedded || attributeOverride ) {
+ classType = AnnotatedClassType.EMBEDDABLE;
+ }
+ }
+
+ if ( AnnotatedClassType.EMBEDDABLE.equals( classType ) ) {
+ EntityBinder entityBinder = new EntityBinder();
+ PersistentClass owner = mapValue.getOwner();
+ boolean isPropertyAnnotated;
+ //FIXME support @Access for collection of elements
+ //String accessType = access != null ? access.value() : null;
+ if ( owner.getIdentifierProperty() != null ) {
+ isPropertyAnnotated = owner.getIdentifierProperty()
+ .getPropertyAccessorName()
+ .equals( "property" );
+ }
+ else
+ if ( owner.getIdentifierMapper() != null && owner.getIdentifierMapper().getPropertySpan() > 0 ) {
+ Property prop = (Property) owner.getIdentifierMapper().getPropertyIterator().next();
+ isPropertyAnnotated = prop.getPropertyAccessorName().equals( "property" );
+ }
+ else {
+ throw new AssertionFailure( "Unable to guess collection property accessor name" );
+ }
+
+ //boolean propertyAccess = embeddable == null || AccessType.PROPERTY.equals( embeddable.access() );
+ //FIXME "index" is it right?
+ PropertyData inferredData = new PropertyPreloadedData( "property", "index", elementClass );
+ //TODO be smart with isNullable
+ Component component = AnnotationBinder.fillComponent(
+ holder, inferredData, isPropertyAnnotated, isPropertyAnnotated ? "property" : "field", true,
+ entityBinder, false, false,
+ true, mappings
+ );
+ mapValue.setIndex( component );
+ }
+ else {
+ SimpleValueBinder elementBinder = new SimpleValueBinder();
+ elementBinder.setMappings( mappings );
+ elementBinder.setReturnedClassName( mapKeyType );
+
+ Ejb3Column[] elementColumns = mapKeyColumns;
+ if ( elementColumns == null || elementColumns.length == 0 ) {
+ elementColumns = new Ejb3Column[1];
+ Ejb3Column column = new Ejb3Column();
+ column.setImplicit( false );
+ column.setNullable( true );
+ column.setLength( Ejb3Column.DEFAULT_COLUMN_LENGTH );
+ column.setLogicalColumnName( Collection.DEFAULT_KEY_COLUMN_NAME );
+ //TODO create an EMPTY_JOINS collection
+ column.setJoins( new HashMap<String, Join>() );
+ column.setMappings( mappings );
+ column.bind();
+ elementColumns[0] = column;
+ }
+ //override the table
+ for (Ejb3Column column : elementColumns) {
+ column.setTable( mapValue.getCollectionTable() );
+ }
+ elementBinder.setColumns( elementColumns );
+ //do not call setType as it extract the type from @Type
+ //the algorithm generally does not apply for map key anyway
+ MapKey mapKeyAnn = property.getAnnotation( org.hibernate.annotations.MapKey.class );
+ if (mapKeyAnn != null && ! BinderHelper.isDefault( mapKeyAnn.type().type() ) ) {
+ elementBinder.setExplicitType( mapKeyAnn.type() );
+ }
+ mapValue.setIndex( elementBinder.make() );
+ }
+ }
+ //FIXME pass the Index Entity JoinColumns
+ if ( !collection.isOneToMany() ) {
+ //index column shoud not be null
+ for (Ejb3JoinColumn col : mapKeyManyToManyColumns) {
+ col.forceNotNull();
+ }
+ }
+ if ( isIndexOfEntities ) {
+ bindManytoManyInverseFk(
+ collectionEntity,
+ mapKeyManyToManyColumns,
+ element,
+ false, //a map key column has no unique constraint
+ mappings
+ );
+ }
+ }
+ }
+
+ protected Value createFormulatedValue(
+ Value value, Collection collection, String targetPropertyName, PersistentClass associatedClass
+ ) {
+ Value element = collection.getElement();
+ String fromAndWhere = null;
+ if ( !( element instanceof OneToMany ) ) {
+ String referencedPropertyName = null;
+ if ( element instanceof ToOne ) {
+ referencedPropertyName = ( (ToOne) element ).getReferencedPropertyName();
+ }
+ else if ( element instanceof DependantValue ) {
+ //TODO this never happen I think
+ if ( propertyName != null ) {
+ referencedPropertyName = collection.getReferencedPropertyName();
+ }
+ else {
+ throw new AnnotationException( "SecondaryTable JoinColumn cannot reference a non primary key" );
+ }
+ }
+ Iterator referencedEntityColumns;
+ if ( referencedPropertyName == null ) {
+ referencedEntityColumns = associatedClass.getIdentifier().getColumnIterator();
+ }
+ else {
+ Property referencedProperty = associatedClass.getRecursiveProperty( referencedPropertyName );
+ referencedEntityColumns = referencedProperty.getColumnIterator();
+ }
+ String alias = "$alias$";
+ StringBuilder fromAndWhereSb = new StringBuilder( " from " )
+ .append( associatedClass.getTable().getName() )
+ //.append(" as ") //Oracle doesn't support it in subqueries
+ .append( " " )
+ .append( alias ).append( " where " );
+ Iterator collectionTableColumns = element.getColumnIterator();
+ while ( collectionTableColumns.hasNext() ) {
+ Column colColumn = (Column) collectionTableColumns.next();
+ Column refColumn = (Column) referencedEntityColumns.next();
+ fromAndWhereSb.append( alias ).append( '.' ).append( refColumn.getQuotedName() )
+ .append( '=' ).append( colColumn.getQuotedName() ).append( " and " );
+ }
+ fromAndWhere = fromAndWhereSb.substring( 0, fromAndWhereSb.length() - 5 );
+ }
+
+ if ( value instanceof Component ) {
+ Component component = (Component) value;
+ Iterator properties = component.getPropertyIterator();
+ Component indexComponent = new Component( collection );
+ indexComponent.setComponentClassName( component.getComponentClassName() );
+ //TODO I don't know if this is appropriate
+ indexComponent.setNodeName( "index" );
+ while ( properties.hasNext() ) {
+ Property current = (Property) properties.next();
+ Property newProperty = new Property();
+ newProperty.setCascade( current.getCascade() );
+ newProperty.setGeneration( current.getGeneration() );
+ newProperty.setInsertable( false );
+ newProperty.setUpdateable( false );
+ newProperty.setMetaAttributes( current.getMetaAttributes() );
+ newProperty.setName( current.getName() );
+ newProperty.setNodeName( current.getNodeName() );
+ newProperty.setNaturalIdentifier( false );
+ //newProperty.setOptimisticLocked( false );
+ newProperty.setOptional( false );
+ newProperty.setPersistentClass( current.getPersistentClass() );
+ newProperty.setPropertyAccessorName( current.getPropertyAccessorName() );
+ newProperty.setSelectable( current.isSelectable() );
+ newProperty.setValue( createFormulatedValue( current.getValue(), collection, targetPropertyName,
+ associatedClass
+ ) );
+ indexComponent.addProperty( newProperty );
+ }
+ return indexComponent;
+ }
+ else if ( value instanceof SimpleValue ) {
+ SimpleValue sourceValue = (SimpleValue) value;
+ SimpleValue targetValue;
+ if ( value instanceof ManyToOne ) {
+ ManyToOne sourceManyToOne = (ManyToOne) sourceValue;
+ ManyToOne targetManyToOne = new ManyToOne( collection.getCollectionTable() );
+ targetManyToOne.setFetchMode( FetchMode.DEFAULT );
+ targetManyToOne.setLazy( true );
+ //targetValue.setIgnoreNotFound( ); does not make sense for a map key
+ targetManyToOne.setReferencedEntityName( sourceManyToOne.getReferencedEntityName() );
+ targetValue = targetManyToOne;
+ }
+ else {
+ targetValue = new SimpleValue( collection.getCollectionTable() );
+ targetValue.setTypeName( sourceValue.getTypeName() );
+ targetValue.setTypeParameters( sourceValue.getTypeParameters() );
+ }
+ Iterator columns = sourceValue.getColumnIterator();
+ Random random = new Random();
+ while ( columns.hasNext() ) {
+ Object current = columns.next();
+ Formula formula = new Formula();
+ String formulaString;
+ if ( current instanceof Column ) {
+ formulaString = ( (Column) current ).getQuotedName();
+ }
+ else if ( current instanceof Formula ) {
+ formulaString = ( (Formula) current ).getFormula();
+ }
+ else {
+ throw new AssertionFailure( "Unknown element in column iterator: " + current.getClass() );
+ }
+ if ( fromAndWhere != null ) {
+ formulaString = Template.renderWhereStringTemplate( formulaString, "$alias$", new HSQLDialect() );
+ formulaString = "(select " + formulaString + fromAndWhere + ")";
+ formulaString = StringHelper.replace(
+ formulaString,
+ "$alias$",
+ "a" + random.nextInt( 16 )
+ );
+ }
+ formula.setFormula( formulaString );
+ targetValue.addFormula( formula );
+
+ }
+ return targetValue;
+ }
+ else {
+ throw new AssertionFailure( "Unknown type encounters for map key: " + value.getClass() );
+ }
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/Nullability.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/Nullability.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/Nullability.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,12 @@
+package org.hibernate.cfg.annotations;
+
+/**
+ * Are the columns forced to null, not null or not forced
+ *
+ * @author Emmanuel Bernard
+ */
+public enum Nullability {
+ FORCED_NULL,
+ FORCED_NOT_NULL,
+ NO_CONSTRAINT
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/PrimitiveArrayBinder.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/PrimitiveArrayBinder.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/PrimitiveArrayBinder.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,16 @@
+//$Id: PrimitiveArrayBinder.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.cfg.annotations;
+
+import org.hibernate.mapping.Collection;
+import org.hibernate.mapping.PersistentClass;
+import org.hibernate.mapping.PrimitiveArray;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class PrimitiveArrayBinder extends ArrayBinder {
+ @Override
+ protected Collection createCollection(PersistentClass persistentClass) {
+ return new PrimitiveArray( persistentClass );
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/PropertyBinder.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/PropertyBinder.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/PropertyBinder.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,195 @@
+//$Id: PropertyBinder.java 14801 2008-06-24 19:03:32Z hardy.ferentschik $
+package org.hibernate.cfg.annotations;
+
+import javax.persistence.EmbeddedId;
+import javax.persistence.Id;
+
+import org.hibernate.AnnotationException;
+import org.hibernate.annotations.Generated;
+import org.hibernate.annotations.GenerationTime;
+import org.hibernate.annotations.Immutable;
+import org.hibernate.annotations.NaturalId;
+import org.hibernate.annotations.OptimisticLock;
+import org.hibernate.annotations.common.reflection.XClass;
+import org.hibernate.annotations.common.reflection.XProperty;
+import org.hibernate.cfg.Ejb3Column;
+import org.hibernate.cfg.ExtendedMappings;
+import org.hibernate.cfg.PropertyHolder;
+import org.hibernate.mapping.Property;
+import org.hibernate.mapping.PropertyGeneration;
+import org.hibernate.mapping.SimpleValue;
+import org.hibernate.mapping.Value;
+import org.hibernate.util.StringHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class PropertyBinder {
+ private Logger log = LoggerFactory.getLogger( PropertyBinder.class );
+ private String name;
+ private String returnedClassName;
+ private boolean lazy;
+ private String propertyAccessorName;
+ private Ejb3Column[] columns;
+ private PropertyHolder holder;
+ private ExtendedMappings mappings;
+ private Value value;
+ private boolean insertable = true;
+ private boolean updatable = true;
+ private String cascade;
+ /*
+ * property can be null
+ * prefer propertyName to property.getName() since some are overloaded
+ */
+ private XProperty property;
+ private XClass returnedClass;
+
+ public void setInsertable(boolean insertable) {
+ this.insertable = insertable;
+ }
+
+ public void setUpdatable(boolean updatable) {
+ this.updatable = updatable;
+ }
+
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public void setReturnedClassName(String returnedClassName) {
+ this.returnedClassName = returnedClassName;
+ }
+
+ public void setLazy(boolean lazy) {
+ this.lazy = lazy;
+ }
+
+ public void setPropertyAccessorName(String propertyAccessorName) {
+ this.propertyAccessorName = propertyAccessorName;
+ }
+
+ public void setColumns(Ejb3Column[] columns) {
+ insertable = columns[0].isInsertable();
+ updatable = columns[0].isUpdatable();
+ //consistency is checked later when we know the property name
+ this.columns = columns;
+ }
+
+ public void setHolder(PropertyHolder holder) {
+ this.holder = holder;
+ }
+
+ public void setValue(Value value) {
+ this.value = value;
+ }
+
+ public void setCascade(String cascadeStrategy) {
+ this.cascade = cascadeStrategy;
+ }
+
+ public void setMappings(ExtendedMappings mappings) {
+ this.mappings = mappings;
+ }
+
+ private void validateBind() {
+ if (property.isAnnotationPresent(Immutable.class)) {
+ throw new AnnotationException("@Immutable on property not allowed. " +
+ "Only allowed on entity level or on a collection.");
+ }
+ }
+
+ private void validateMake() {
+ //TODO check necessary params for a make
+ }
+
+ public Property bind() {
+ validateBind();
+ log.debug( "binding property {} with lazy={}", name, lazy );
+ String containerClassName = holder == null ?
+ null :
+ holder.getClassName();
+ SimpleValueBinder value = new SimpleValueBinder();
+ value.setMappings( mappings );
+ value.setPropertyName( name );
+ value.setReturnedClassName( returnedClassName );
+ value.setColumns( columns );
+ value.setPersistentClassName( containerClassName );
+ value.setType( property, returnedClass );
+ value.setMappings( mappings );
+ SimpleValue propertyValue = value.make();
+ setValue( propertyValue );
+ Property prop = make();
+ holder.addProperty( prop, columns );
+ return prop;
+ }
+
+ public Property make() {
+ validateMake();
+ log.debug( "Building property " + name );
+ Property prop = new Property();
+ prop.setName( name );
+ prop.setNodeName( name );
+ prop.setValue( value );
+ prop.setLazy( lazy );
+ prop.setCascade( cascade );
+ prop.setPropertyAccessorName( propertyAccessorName );
+ Generated ann = property != null ?
+ property.getAnnotation( Generated.class ) :
+ null;
+ GenerationTime generated = ann != null ?
+ ann.value() :
+ null;
+ if ( generated != null ) {
+ if ( !GenerationTime.NEVER.equals( generated ) ) {
+ if ( property.isAnnotationPresent( javax.persistence.Version.class )
+ && GenerationTime.INSERT.equals( generated ) ) {
+ throw new AnnotationException( "@Generated(INSERT) on a @Version property not allowed, use ALWAYS: "
+ + StringHelper.qualify( holder.getPath(), name ) );
+ }
+ insertable = false;
+ if ( GenerationTime.ALWAYS.equals( generated ) ) {
+ updatable = false;
+ }
+ prop.setGeneration( PropertyGeneration.parse( generated.toString().toLowerCase() ) );
+ }
+ }
+ NaturalId naturalId = property != null ?
+ property.getAnnotation( NaturalId.class ) :
+ null;
+ if ( naturalId != null ) {
+ if ( !naturalId.mutable() ) {
+ updatable = false;
+ }
+ prop.setNaturalIdentifier( true );
+ }
+ prop.setInsertable( insertable );
+ prop.setUpdateable( updatable );
+ OptimisticLock lockAnn = property != null ?
+ property.getAnnotation( OptimisticLock.class ) :
+ null;
+ if ( lockAnn != null ) {
+ prop.setOptimisticLocked( !lockAnn.excluded() );
+ //TODO this should go to the core as a mapping validation checking
+ if ( lockAnn.excluded() && (
+ property.isAnnotationPresent( javax.persistence.Version.class )
+ || property.isAnnotationPresent( Id.class )
+ || property.isAnnotationPresent( EmbeddedId.class ) ) ) {
+ throw new AnnotationException( "@OptimisticLock.exclude=true incompatible with @Id, @EmbeddedId and @Version: "
+ + StringHelper.qualify( holder.getPath(), name ) );
+ }
+ }
+ log.trace( "Cascading " + name + " with " + cascade );
+ return prop;
+ }
+
+ public void setProperty(XProperty property) {
+ this.property = property;
+ }
+
+ public void setReturnedClass(XClass returnedClass) {
+ this.returnedClass = returnedClass;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/QueryBinder.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/QueryBinder.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/QueryBinder.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,388 @@
+//$Id: QueryBinder.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.cfg.annotations;
+
+import java.util.HashMap;
+import javax.persistence.NamedNativeQueries;
+import javax.persistence.NamedNativeQuery;
+import javax.persistence.NamedQueries;
+import javax.persistence.NamedQuery;
+import javax.persistence.QueryHint;
+import javax.persistence.SqlResultSetMapping;
+import javax.persistence.SqlResultSetMappings;
+
+import org.hibernate.AnnotationException;
+import org.hibernate.AssertionFailure;
+import org.hibernate.CacheMode;
+import org.hibernate.FlushMode;
+import org.hibernate.LockMode;
+import org.hibernate.annotations.CacheModeType;
+import org.hibernate.annotations.FlushModeType;
+import org.hibernate.cfg.BinderHelper;
+import org.hibernate.cfg.ExtendedMappings;
+import org.hibernate.cfg.NotYetImplementedException;
+import org.hibernate.engine.NamedQueryDefinition;
+import org.hibernate.engine.NamedSQLQueryDefinition;
+import org.hibernate.engine.query.sql.NativeSQLQueryReturn;
+import org.hibernate.engine.query.sql.NativeSQLQueryRootReturn;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Query binder
+ *
+ * @author Emmanuel Bernard
+ */
+public abstract class QueryBinder {
+ private static final Logger log = LoggerFactory.getLogger( QueryBinder.class );
+
+ public static void bindQuery(NamedQuery queryAnn, ExtendedMappings mappings, boolean isDefault) {
+ if ( queryAnn == null ) return;
+ if ( BinderHelper.isDefault( queryAnn.name() ) ) {
+ throw new AnnotationException( "A named query must have a name when used in class or package level" );
+ }
+ //EJBQL Query
+ QueryHint[] hints = queryAnn.hints();
+ String queryName = queryAnn.query();
+ NamedQueryDefinition query = new NamedQueryDefinition(
+ queryName,
+ getBoolean( queryName, "org.hibernate.cacheable", hints ),
+ getString( queryName, "org.hibernate.cacheRegion", hints ),
+ getInteger( queryName, "org.hibernate.timeout", hints ),
+ getInteger( queryName, "org.hibernate.fetchSize", hints ),
+ getFlushMode( queryName, hints ),
+ getCacheMode( queryName, hints ),
+ getBoolean( queryName, "org.hibernate.readOnly", hints ),
+ getString( queryName, "org.hibernate.comment", hints ),
+ null
+ );
+ if ( isDefault ) {
+ mappings.addDefaultQuery( queryAnn.name(), query );
+ }
+ else {
+ mappings.addQuery( queryAnn.name(), query );
+ }
+ log.info( "Binding Named query: {} => {}", queryAnn.name(), queryAnn.query() );
+ }
+
+
+ public static void bindNativeQuery(NamedNativeQuery queryAnn, ExtendedMappings mappings, boolean isDefault) {
+ if ( queryAnn == null ) return;
+ //ResultSetMappingDefinition mappingDefinition = mappings.getResultSetMapping( queryAnn.resultSetMapping() );
+ if ( BinderHelper.isDefault( queryAnn.name() ) ) {
+ throw new AnnotationException( "A named query must have a name when used in class or package level" );
+ }
+ NamedSQLQueryDefinition query;
+ String resultSetMapping = queryAnn.resultSetMapping();
+ QueryHint[] hints = queryAnn.hints();
+ String queryName = queryAnn.query();
+ if ( !BinderHelper.isDefault( resultSetMapping ) ) {
+ //sql result set usage
+ query = new NamedSQLQueryDefinition(
+ queryName,
+ resultSetMapping,
+ null,
+ getBoolean( queryName, "org.hibernate.cacheable", hints ),
+ getString( queryName, "org.hibernate.cacheRegion", hints ),
+ getInteger( queryName, "org.hibernate.timeout", hints ),
+ getInteger( queryName, "org.hibernate.fetchSize", hints ),
+ getFlushMode( queryName, hints ),
+ getCacheMode( queryName, hints ),
+ getBoolean( queryName, "org.hibernate.readOnly", hints ),
+ getString( queryName, "org.hibernate.comment", hints ),
+ null,
+ getBoolean( queryName, "org.hibernate.callable", hints )
+ );
+ }
+ else if ( !void.class.equals( queryAnn.resultClass() ) ) {
+ //class mapping usage
+ //FIXME should be done in a second pass due to entity name?
+ final NativeSQLQueryRootReturn entityQueryReturn =
+ new NativeSQLQueryRootReturn( "alias1", queryAnn.resultClass().getName(), new HashMap(), LockMode.READ );
+ query = new NamedSQLQueryDefinition(
+ queryName,
+ new NativeSQLQueryReturn[] { entityQueryReturn },
+ null,
+ getBoolean( queryName, "org.hibernate.cacheable", hints ),
+ getString( queryName, "org.hibernate.cacheRegion", hints ),
+ getInteger( queryName, "org.hibernate.timeout", hints ),
+ getInteger( queryName, "org.hibernate.fetchSize", hints ),
+ getFlushMode( queryName, hints ),
+ getCacheMode( queryName, hints ),
+ getBoolean( queryName, "org.hibernate.readOnly", hints ),
+ getString( queryName, "org.hibernate.comment", hints ),
+ null,
+ getBoolean( queryName, "org.hibernate.callable", hints )
+ );
+ }
+ else {
+ throw new NotYetImplementedException( "Pure native scalar queries are not yet supported" );
+ }
+ if ( isDefault ) {
+ mappings.addDefaultSQLQuery( queryAnn.name(), query );
+ }
+ else {
+ mappings.addSQLQuery( queryAnn.name(), query );
+ }
+ log.info( "Binding named native query: {} => {}", queryAnn.name(), queryAnn.query() );
+ }
+
+ public static void bindNativeQuery(org.hibernate.annotations.NamedNativeQuery queryAnn, ExtendedMappings mappings) {
+ if ( queryAnn == null ) return;
+ //ResultSetMappingDefinition mappingDefinition = mappings.getResultSetMapping( queryAnn.resultSetMapping() );
+ if ( BinderHelper.isDefault( queryAnn.name() ) ) {
+ throw new AnnotationException( "A named query must have a name when used in class or package level" );
+ }
+ NamedSQLQueryDefinition query;
+ String resultSetMapping = queryAnn.resultSetMapping();
+ if ( !BinderHelper.isDefault( resultSetMapping ) ) {
+ //sql result set usage
+ query = new NamedSQLQueryDefinition(
+ queryAnn.query(),
+ resultSetMapping,
+ null,
+ queryAnn.cacheable(),
+ BinderHelper.isDefault( queryAnn.cacheRegion() ) ? null : queryAnn.cacheRegion(),
+ queryAnn.timeout() < 0 ? null : queryAnn.timeout(),
+ queryAnn.fetchSize() < 0 ? null : queryAnn.fetchSize(),
+ getFlushMode( queryAnn.flushMode() ),
+ getCacheMode( queryAnn.cacheMode() ),
+ queryAnn.readOnly(),
+ BinderHelper.isDefault( queryAnn.comment() ) ? null : queryAnn.comment(),
+ null,
+ queryAnn.callable()
+ );
+ }
+ else if ( !void.class.equals( queryAnn.resultClass() ) ) {
+ //class mapping usage
+ //FIXME should be done in a second pass due to entity name?
+ final NativeSQLQueryRootReturn entityQueryReturn =
+ new NativeSQLQueryRootReturn( "alias1", queryAnn.resultClass().getName(), new HashMap(), LockMode.READ );
+ query = new NamedSQLQueryDefinition(
+ queryAnn.query(),
+ new NativeSQLQueryReturn[] { entityQueryReturn },
+ null,
+ queryAnn.cacheable(),
+ BinderHelper.isDefault( queryAnn.cacheRegion() ) ? null : queryAnn.cacheRegion(),
+ queryAnn.timeout() < 0 ? null : queryAnn.timeout(),
+ queryAnn.fetchSize() < 0 ? null : queryAnn.fetchSize(),
+ getFlushMode( queryAnn.flushMode() ),
+ getCacheMode( queryAnn.cacheMode() ),
+ queryAnn.readOnly(),
+ BinderHelper.isDefault( queryAnn.comment() ) ? null : queryAnn.comment(),
+ null,
+ queryAnn.callable()
+ );
+ }
+ else {
+ throw new NotYetImplementedException( "Pure native scalar queries are not yet supported" );
+ }
+ mappings.addSQLQuery( queryAnn.name(), query );
+ log.info( "Binding named native query: {} => {}", queryAnn.name(), queryAnn.query() );
+ }
+
+ public static void bindQueries(NamedQueries queriesAnn, ExtendedMappings mappings, boolean isDefault) {
+ if ( queriesAnn == null ) return;
+ for (NamedQuery q : queriesAnn.value()) {
+ bindQuery( q, mappings, isDefault );
+ }
+ }
+
+ public static void bindNativeQueries(NamedNativeQueries queriesAnn, ExtendedMappings mappings, boolean isDefault) {
+ if ( queriesAnn == null ) return;
+ for (NamedNativeQuery q : queriesAnn.value()) {
+ bindNativeQuery( q, mappings, isDefault );
+ }
+ }
+
+ public static void bindNativeQueries(
+ org.hibernate.annotations.NamedNativeQueries queriesAnn, ExtendedMappings mappings
+ ) {
+ if ( queriesAnn == null ) return;
+ for (org.hibernate.annotations.NamedNativeQuery q : queriesAnn.value()) {
+ bindNativeQuery( q, mappings );
+ }
+ }
+
+ public static void bindQuery(org.hibernate.annotations.NamedQuery queryAnn, ExtendedMappings mappings) {
+ if ( queryAnn == null ) return;
+ if ( BinderHelper.isDefault( queryAnn.name() ) ) {
+ throw new AnnotationException( "A named query must have a name when used in class or package level" );
+ }
+
+ FlushMode flushMode;
+ flushMode = getFlushMode( queryAnn.flushMode() );
+
+ NamedQueryDefinition query = new NamedQueryDefinition(
+ queryAnn.query(),
+ queryAnn.cacheable(),
+ BinderHelper.isDefault( queryAnn.cacheRegion() ) ? null : queryAnn.cacheRegion(),
+ queryAnn.timeout() < 0 ? null : queryAnn.timeout(),
+ queryAnn.fetchSize() < 0 ? null : queryAnn.fetchSize(),
+ flushMode,
+ getCacheMode( queryAnn.cacheMode() ),
+ queryAnn.readOnly(),
+ BinderHelper.isDefault( queryAnn.comment() ) ? null : queryAnn.comment(),
+ null
+ );
+
+ mappings.addQuery( queryAnn.name(), query );
+ if ( log.isInfoEnabled() ) log.info( "Binding named query: " + queryAnn.name() + " => " + queryAnn.query() );
+ }
+
+ private static FlushMode getFlushMode(FlushModeType flushModeType) {
+ FlushMode flushMode;
+ switch ( flushModeType ) {
+ case ALWAYS:
+ flushMode = FlushMode.ALWAYS;
+ break;
+ case AUTO:
+ flushMode = FlushMode.AUTO;
+ break;
+ case COMMIT:
+ flushMode = FlushMode.COMMIT;
+ break;
+ case NEVER:
+ flushMode = FlushMode.MANUAL;
+ break;
+ case MANUAL:
+ flushMode = FlushMode.MANUAL;
+ break;
+ case PERSISTENCE_CONTEXT:
+ flushMode = null;
+ break;
+ default:
+ throw new AssertionFailure( "Unknown flushModeType: " + flushModeType );
+ }
+ return flushMode;
+ }
+
+ private static CacheMode getCacheMode(CacheModeType cacheModeType) {
+ switch ( cacheModeType ) {
+ case GET:
+ return CacheMode.GET;
+ case IGNORE:
+ return CacheMode.IGNORE;
+ case NORMAL:
+ return CacheMode.NORMAL;
+ case PUT:
+ return CacheMode.PUT;
+ case REFRESH:
+ return CacheMode.REFRESH;
+ default:
+ throw new AssertionFailure( "Unknown cacheModeType: " + cacheModeType );
+ }
+ }
+
+
+ public static void bindQueries(org.hibernate.annotations.NamedQueries queriesAnn, ExtendedMappings mappings) {
+ if ( queriesAnn == null ) return;
+ for (org.hibernate.annotations.NamedQuery q : queriesAnn.value()) {
+ bindQuery( q, mappings );
+ }
+ }
+
+ public static void bindSqlResultsetMappings(SqlResultSetMappings ann, ExtendedMappings mappings, boolean isDefault) {
+ if ( ann == null ) return;
+ for (SqlResultSetMapping rs : ann.value()) {
+ //no need to handle inSecondPass
+ mappings.addSecondPass( new ResultsetMappingSecondPass( rs, mappings, true ) );
+ }
+ }
+
+ public static void bindSqlResultsetMapping(SqlResultSetMapping ann, ExtendedMappings mappings, boolean isDefault) {
+ //no need to handle inSecondPass
+ mappings.addSecondPass( new ResultsetMappingSecondPass( ann, mappings, isDefault ) );
+ }
+
+ private static CacheMode getCacheMode(String query, QueryHint[] hints) {
+ for (QueryHint hint : hints) {
+ if ( "org.hibernate.cacheMode".equals( hint.name() ) ) {
+ if ( hint.value().equalsIgnoreCase( CacheMode.GET.toString() ) ) {
+ return CacheMode.GET;
+ }
+ else if ( hint.value().equalsIgnoreCase( CacheMode.IGNORE.toString() ) ) {
+ return CacheMode.IGNORE;
+ }
+ else if ( hint.value().equalsIgnoreCase( CacheMode.NORMAL.toString() ) ) {
+ return CacheMode.NORMAL;
+ }
+ else if ( hint.value().equalsIgnoreCase( CacheMode.PUT.toString() ) ) {
+ return CacheMode.PUT;
+ }
+ else if ( hint.value().equalsIgnoreCase( CacheMode.REFRESH.toString() ) ) {
+ return CacheMode.REFRESH;
+ }
+ else {
+ throw new AnnotationException( "Unknown CacheMode in hint: " + query + ":" + hint.name() );
+ }
+ }
+ }
+ return null;
+ }
+
+ private static FlushMode getFlushMode(String query, QueryHint[] hints) {
+ for (QueryHint hint : hints) {
+ if ( "org.hibernate.flushMode".equals( hint.name() ) ) {
+ if ( hint.value().equalsIgnoreCase( FlushMode.ALWAYS.toString() ) ) {
+ return FlushMode.ALWAYS;
+ }
+ else if ( hint.value().equalsIgnoreCase( FlushMode.AUTO.toString() ) ) {
+ return FlushMode.AUTO;
+ }
+ else if ( hint.value().equalsIgnoreCase( FlushMode.COMMIT.toString() ) ) {
+ return FlushMode.COMMIT;
+ }
+ else if ( hint.value().equalsIgnoreCase( FlushMode.NEVER.toString() ) ) {
+ return FlushMode.MANUAL;
+ }
+ else if ( hint.value().equalsIgnoreCase( FlushMode.MANUAL.toString() ) ) {
+ return FlushMode.MANUAL;
+ }
+ else {
+ throw new AnnotationException( "Unknown FlushMode in hint: " + query + ":" + hint.name() );
+ }
+ }
+ }
+ return null;
+ }
+
+ private static boolean getBoolean(String query, String hintName, QueryHint[] hints) {
+ for (QueryHint hint : hints) {
+ if ( hintName.equals( hint.name() ) ) {
+ if ( hint.value().equalsIgnoreCase( "true" ) ) {
+ return true;
+ }
+ else if ( hint.value().equalsIgnoreCase( "false" ) ) {
+ return false;
+ }
+ else {
+ throw new AnnotationException( "Not a boolean in hint: " + query + ":" + hint.name() );
+ }
+ }
+ }
+ return false;
+ }
+
+ private static String getString(String query, String hintName, QueryHint[] hints) {
+ for (QueryHint hint : hints) {
+ if ( hintName.equals( hint.name() ) ) {
+ return hint.value();
+ }
+ }
+ return null;
+ }
+
+ private static Integer getInteger(String query, String hintName, QueryHint[] hints) {
+ for (QueryHint hint : hints) {
+ if ( hintName.equals( hint.name() ) ) {
+ try {
+ return Integer.decode( hint.value() );
+ }
+ catch (NumberFormatException nfe) {
+ throw new AnnotationException( "Not an integer in hint: " + query + ":" + hint.name(), nfe );
+ }
+ }
+ }
+ return null;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/ResultsetMappingSecondPass.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/ResultsetMappingSecondPass.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/ResultsetMappingSecondPass.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,231 @@
+//$Id: ResultsetMappingSecondPass.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.cfg.annotations;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.persistence.ColumnResult;
+import javax.persistence.EntityResult;
+import javax.persistence.FieldResult;
+import javax.persistence.SqlResultSetMapping;
+
+import org.hibernate.LockMode;
+import org.hibernate.MappingException;
+import org.hibernate.cfg.BinderHelper;
+import org.hibernate.cfg.ExtendedMappings;
+import org.hibernate.cfg.QuerySecondPass;
+import org.hibernate.engine.ResultSetMappingDefinition;
+import org.hibernate.engine.query.sql.NativeSQLQueryRootReturn;
+import org.hibernate.engine.query.sql.NativeSQLQueryScalarReturn;
+import org.hibernate.mapping.Component;
+import org.hibernate.mapping.PersistentClass;
+import org.hibernate.mapping.Property;
+import org.hibernate.mapping.ToOne;
+import org.hibernate.mapping.Value;
+import org.hibernate.util.CollectionHelper;
+import org.hibernate.util.StringHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class ResultsetMappingSecondPass implements QuerySecondPass {
+ private Logger log = LoggerFactory.getLogger( ResultsetMappingSecondPass.class );
+ private SqlResultSetMapping ann;
+ private ExtendedMappings mappings;
+ private boolean isDefault;
+
+ public ResultsetMappingSecondPass(SqlResultSetMapping ann, ExtendedMappings mappings, boolean isDefault) {
+ this.ann = ann;
+ this.mappings = mappings;
+ this.isDefault = isDefault;
+ }
+
+ public void doSecondPass(Map persistentClasses) throws MappingException {
+ //TODO add parameters checkings
+ if ( ann == null ) return;
+ ResultSetMappingDefinition definition = new ResultSetMappingDefinition( ann.name() );
+ log.info( "Binding resultset mapping: {}", definition.getName() );
+
+ int entityAliasIndex = 0;
+
+ for (EntityResult entity : ann.entities()) {
+ //TODO parameterize lock mode?
+ List properties = new ArrayList();
+ List propertyNames = new ArrayList();
+ Map propertyresults = new HashMap();
+ for (FieldResult field : entity.fields()) {
+ //use an ArrayList cause we might have several columns per root property
+ String name = field.name();
+ if ( name.indexOf( '.' ) == -1 ) {
+ //regular property
+ properties.add( field );
+ propertyNames.add( name );
+ }
+ else {
+ /**
+ * Reorder properties
+ * 1. get the parent property
+ * 2. list all the properties following the expected one in the parent property
+ * 3. calculate the lowest index and insert the property
+ */
+ PersistentClass pc = mappings.getClass( entity.entityClass().getName() );
+ if ( pc == null ) {
+ throw new MappingException(
+ "Entity not found " + entity.entityClass().getName()
+ + " in SqlResultsetMapping " + ann.name()
+ );
+ }
+ int dotIndex = name.lastIndexOf( '.' );
+ String reducedName = name.substring( 0, dotIndex );
+ Iterator parentPropIter = getSubPropertyIterator( pc, reducedName );
+ List followers = getFollowers( parentPropIter, reducedName, name );
+
+ int index = propertyNames.size();
+ int followersSize = followers.size();
+ for (int loop = 0; loop < followersSize; loop++) {
+ String follower = (String) followers.get( loop );
+ int currentIndex = getIndexOfFirstMatchingProperty( propertyNames, follower );
+ index = currentIndex != -1 && currentIndex < index ? currentIndex : index;
+ }
+ propertyNames.add( index, name );
+ properties.add( index, field );
+ }
+ }
+
+ Set uniqueReturnProperty = new HashSet();
+ Iterator iterator = properties.iterator();
+ while ( iterator.hasNext() ) {
+ FieldResult propertyresult = (FieldResult) iterator.next();
+ String name = propertyresult.name();
+ if ( "class".equals( name ) ) {
+ throw new MappingException(
+ "class is not a valid property name to use in a @FieldResult, use @Entity(discriminatorColumn) instead"
+ );
+ }
+ ArrayList allResultColumns = new ArrayList();
+ allResultColumns.add( propertyresult.column() );
+
+ if ( uniqueReturnProperty.contains( name ) ) {
+ throw new MappingException(
+ "duplicate @FieldResult for property " + name +
+ " on @Entity " + entity.entityClass().getName() + " in " + ann.name()
+ );
+ }
+ uniqueReturnProperty.add( name );
+ String key = StringHelper.root( name );
+ ArrayList intermediateResults = (ArrayList) propertyresults.get( key );
+ if ( intermediateResults == null ) {
+ propertyresults.put( key, allResultColumns );
+ }
+ else {
+ intermediateResults.addAll( allResultColumns );
+ }
+ }
+ Iterator entries = propertyresults.entrySet().iterator();
+ while ( entries.hasNext() ) {
+ Map.Entry entry = (Map.Entry) entries.next();
+ if ( entry.getValue() instanceof ArrayList ) {
+ ArrayList list = (ArrayList) entry.getValue();
+ entry.setValue( list.toArray( new String[list.size()] ) );
+ }
+ }
+
+ if ( !BinderHelper.isDefault( entity.discriminatorColumn() ) ) {
+ propertyresults.put( "class", new String[] { entity.discriminatorColumn() } );
+ }
+
+ propertyresults = propertyresults.isEmpty() ? CollectionHelper.EMPTY_MAP : propertyresults;
+ NativeSQLQueryRootReturn result =
+ new NativeSQLQueryRootReturn(
+ "alias" + entityAliasIndex++, entity.entityClass().getName(), propertyresults, LockMode.READ
+ );
+ definition.addQueryReturn( result );
+ }
+
+ for (ColumnResult column : ann.columns()) {
+ definition.addQueryReturn( new NativeSQLQueryScalarReturn( column.name(), null ) );
+ }
+
+ if ( isDefault ) {
+ mappings.addDefaultResultSetMapping( definition );
+ }
+ else {
+ mappings.addResultSetMapping( definition );
+ }
+ }
+
+ private List getFollowers(Iterator parentPropIter, String reducedName, String name) {
+ boolean hasFollowers = false;
+ List followers = new ArrayList();
+ while ( parentPropIter.hasNext() ) {
+ String currentPropertyName = ( (Property) parentPropIter.next() ).getName();
+ String currentName = reducedName + '.' + currentPropertyName;
+ if ( hasFollowers ) {
+ followers.add( currentName );
+ }
+ if ( name.equals( currentName ) ) hasFollowers = true;
+ }
+ return followers;
+ }
+
+ private Iterator getSubPropertyIterator(PersistentClass pc, String reducedName) {
+ Value value = pc.getRecursiveProperty( reducedName ).getValue();
+ Iterator parentPropIter;
+ if ( value instanceof Component ) {
+ Component comp = (Component) value;
+ parentPropIter = comp.getPropertyIterator();
+ }
+ else if ( value instanceof ToOne ) {
+ ToOne toOne = (ToOne) value;
+ PersistentClass referencedPc = mappings.getClass( toOne.getReferencedEntityName() );
+ if ( toOne.getReferencedPropertyName() != null ) {
+ try {
+ parentPropIter = ( (Component) referencedPc.getRecursiveProperty(
+ toOne.getReferencedPropertyName()
+ ).getValue() ).getPropertyIterator();
+ }
+ catch (ClassCastException e) {
+ throw new MappingException(
+ "dotted notation reference neither a component nor a many/one to one", e
+ );
+ }
+ }
+ else {
+ try {
+ if ( referencedPc.getIdentifierMapper() == null ) {
+ parentPropIter = ( (Component) referencedPc.getIdentifierProperty()
+ .getValue() ).getPropertyIterator();
+ }
+ else {
+ parentPropIter = referencedPc.getIdentifierMapper().getPropertyIterator();
+ }
+ }
+ catch (ClassCastException e) {
+ throw new MappingException(
+ "dotted notation reference neither a component nor a many/one to one", e
+ );
+ }
+ }
+ }
+ else {
+ throw new MappingException( "dotted notation reference neither a component nor a many/one to one" );
+ }
+ return parentPropIter;
+ }
+
+ private static int getIndexOfFirstMatchingProperty(List propertyNames, String follower) {
+ int propertySize = propertyNames.size();
+ for (int propIndex = 0; propIndex < propertySize; propIndex++) {
+ if ( ( (String) propertyNames.get( propIndex ) ).startsWith( follower ) ) {
+ return propIndex;
+ }
+ }
+ return -1;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/SetBinder.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/SetBinder.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/SetBinder.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,39 @@
+package org.hibernate.cfg.annotations;
+
+import org.hibernate.annotations.OrderBy;
+import org.hibernate.cfg.Environment;
+import org.hibernate.mapping.Collection;
+import org.hibernate.mapping.PersistentClass;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Bind a set.
+ *
+ * @author Matthew Inger
+ */
+public class SetBinder extends CollectionBinder {
+ private final Logger log = LoggerFactory.getLogger( SetBinder.class );
+
+ public SetBinder() {
+ }
+
+ public SetBinder(boolean sorted) {
+ super( sorted );
+ }
+
+ protected Collection createCollection(PersistentClass persistentClass) {
+ return new org.hibernate.mapping.Set( persistentClass );
+ }
+
+ public void setSqlOrderBy(OrderBy orderByAnn) {
+ if ( orderByAnn != null ) {
+ if ( Environment.jvmSupportsLinkedHashCollections() ) {
+ super.setSqlOrderBy( orderByAnn );
+ }
+ else {
+ log.warn( "Attribute \"order-by\" ignored in JDK1.3 or less" );
+ }
+ }
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/SimpleValueBinder.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/SimpleValueBinder.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/SimpleValueBinder.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,248 @@
+//$Id: SimpleValueBinder.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.cfg.annotations;
+
+import java.io.Serializable;
+import java.sql.Types;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.Properties;
+import javax.persistence.Enumerated;
+import javax.persistence.Lob;
+import javax.persistence.Temporal;
+
+import org.hibernate.AnnotationException;
+import org.hibernate.AssertionFailure;
+import org.hibernate.annotations.Parameter;
+import org.hibernate.annotations.Type;
+import org.hibernate.annotations.common.reflection.XClass;
+import org.hibernate.annotations.common.reflection.XProperty;
+import org.hibernate.cfg.BinderHelper;
+import org.hibernate.cfg.Ejb3Column;
+import org.hibernate.cfg.ExtendedMappings;
+import org.hibernate.cfg.NotYetImplementedException;
+import org.hibernate.mapping.SimpleValue;
+import org.hibernate.mapping.Table;
+import org.hibernate.type.ByteArrayBlobType;
+import org.hibernate.type.CharacterArrayClobType;
+import org.hibernate.type.EnumType;
+import org.hibernate.type.PrimitiveByteArrayBlobType;
+import org.hibernate.type.PrimitiveCharacterArrayClobType;
+import org.hibernate.type.SerializableToBlobType;
+import org.hibernate.type.StringClobType;
+import org.hibernate.util.StringHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class SimpleValueBinder {
+ private Logger log = LoggerFactory.getLogger( SimpleValueBinder.class );
+ private String propertyName;
+ private String returnedClassName;
+ private Ejb3Column[] columns;
+ private String persistentClassName;
+ private String explicitType = "";
+ private Properties typeParameters = new Properties();
+ private ExtendedMappings mappings;
+ private Table table;
+
+ public void setPropertyName(String propertyName) {
+ this.propertyName = propertyName;
+ }
+
+ public void setReturnedClassName(String returnedClassName) {
+ this.returnedClassName = returnedClassName;
+ }
+
+ public void setTable(Table table) {
+ this.table = table;
+ }
+
+ public void setColumns(Ejb3Column[] columns) {
+ this.columns = columns;
+ }
+
+
+ public void setPersistentClassName(String persistentClassName) {
+ this.persistentClassName = persistentClassName;
+ }
+
+ //TODO execute it lazily to be order safe
+ public void setType(XProperty property, XClass returnedClass) {
+ if ( returnedClass == null ) return; //we cannot guess anything
+ XClass returnedClassOrElement = returnedClass;
+ boolean isArray = false;
+ if ( property.isArray() ) {
+ returnedClassOrElement = property.getElementClass();
+ isArray = true;
+ }
+ Properties typeParameters = this.typeParameters;
+ typeParameters.clear();
+ String type = BinderHelper.ANNOTATION_STRING_DEFAULT;
+ if ( property.isAnnotationPresent( Temporal.class ) ) {
+ Temporal ann = property.getAnnotation( Temporal.class );
+ boolean isDate;
+ if ( mappings.getReflectionManager().equals( returnedClassOrElement, Date.class ) ) {
+ isDate = true;
+ }
+ else if ( mappings.getReflectionManager().equals( returnedClassOrElement, Calendar.class ) ) {
+ isDate = false;
+ }
+ else {
+ throw new AnnotationException(
+ "@Temporal should only be set on a java.util.Date or java.util.Calendar property: "
+ + StringHelper.qualify( persistentClassName, propertyName )
+ );
+ }
+
+ switch ( ann.value() ) {
+ case DATE:
+ type = isDate ? "date" : "calendar_date";
+ break;
+ case TIME:
+ type = "time";
+ if ( !isDate ) {
+ throw new NotYetImplementedException(
+ "Calendar cannot persist TIME only"
+ + StringHelper.qualify( persistentClassName, propertyName )
+ );
+ }
+ break;
+ case TIMESTAMP:
+ type = isDate ? "timestamp" : "calendar";
+ break;
+ default:
+ throw new AssertionFailure( "Unknown temporal type: " + ann.value() );
+ }
+ }
+ else if ( property.isAnnotationPresent( Lob.class ) ) {
+
+ if ( mappings.getReflectionManager().equals( returnedClassOrElement, java.sql.Clob.class ) ) {
+ type = "clob";
+ }
+ else if ( mappings.getReflectionManager().equals( returnedClassOrElement, java.sql.Blob.class ) ) {
+ type = "blob";
+ }
+ else if ( mappings.getReflectionManager().equals( returnedClassOrElement, String.class ) ) {
+ type = StringClobType.class.getName();
+ }
+ else if ( mappings.getReflectionManager().equals( returnedClassOrElement, Character.class ) && isArray ) {
+ type = CharacterArrayClobType.class.getName();
+ }
+ else if ( mappings.getReflectionManager().equals( returnedClassOrElement, char.class ) && isArray ) {
+ type = PrimitiveCharacterArrayClobType.class.getName();
+ }
+ else if ( mappings.getReflectionManager().equals( returnedClassOrElement, Byte.class ) && isArray ) {
+ type = ByteArrayBlobType.class.getName();
+ }
+ else if ( mappings.getReflectionManager().equals( returnedClassOrElement, byte.class ) && isArray ) {
+ type = PrimitiveByteArrayBlobType.class.getName();
+ }
+ else if ( mappings.getReflectionManager()
+ .toXClass( Serializable.class )
+ .isAssignableFrom( returnedClassOrElement ) ) {
+ type = SerializableToBlobType.class.getName();
+ //typeParameters = new Properties();
+ typeParameters.setProperty(
+ SerializableToBlobType.CLASS_NAME,
+ returnedClassOrElement.getName()
+ );
+ }
+ else {
+ type = "blob";
+ }
+ }
+ //implicit type will check basic types and Serializable classes
+ if ( columns == null ) {
+ throw new AssertionFailure( "SimpleValueBinder.setColumns should be set before SimpleValueBinder.setType" );
+ }
+ if ( BinderHelper.ANNOTATION_STRING_DEFAULT.equals( type ) ) {
+ if ( returnedClassOrElement.isEnum() ) {
+ type = EnumType.class.getName();
+ typeParameters = new Properties();
+ typeParameters.setProperty( EnumType.ENUM, returnedClassOrElement.getName() );
+ String schema = columns[0].getTable().getSchema();
+ schema = schema == null ? "" : schema;
+ String catalog = columns[0].getTable().getCatalog();
+ catalog = catalog == null ? "" : catalog;
+ typeParameters.setProperty( EnumType.SCHEMA, schema );
+ typeParameters.setProperty( EnumType.CATALOG, catalog );
+ typeParameters.setProperty( EnumType.TABLE, columns[0].getTable().getName() );
+ typeParameters.setProperty( EnumType.COLUMN, columns[0].getName() );
+ Enumerated enumAnn = property.getAnnotation( Enumerated.class );
+ if ( enumAnn != null ) {
+ javax.persistence.EnumType enumType = enumAnn.value();
+ if ( javax.persistence.EnumType.ORDINAL.equals( enumType ) ) {
+ typeParameters.setProperty( EnumType.TYPE, String.valueOf( Types.INTEGER ) );
+ }
+ else if ( javax.persistence.EnumType.STRING.equals( enumType ) ) {
+ typeParameters.setProperty( EnumType.TYPE, String.valueOf( Types.VARCHAR ) );
+ }
+ else {
+ throw new AssertionFailure( "Unknown EnumType: " + enumType );
+ }
+ }
+ }
+ }
+ explicitType = type;
+ this.typeParameters = typeParameters;
+ Type annType = (Type) property.getAnnotation( Type.class );
+ setExplicitType( annType );
+ }
+
+ public void setExplicitType(String explicitType) {
+ this.explicitType = explicitType;
+ }
+
+ //FIXME raise an assertion failure if setExplicitType(String) and setExplicitType(Type) are use at the same time
+ public void setExplicitType(Type typeAnn) {
+ if ( typeAnn != null ) {
+ explicitType = typeAnn.type();
+ typeParameters.clear();
+ for (Parameter param : typeAnn.parameters()) {
+ typeParameters.setProperty( param.name(), param.value() );
+ }
+ }
+ }
+
+ public void setMappings(ExtendedMappings mappings) {
+ this.mappings = mappings;
+ }
+
+ private void validate() {
+ //TODO check necessary params
+ Ejb3Column.checkPropertyConsistency( columns, propertyName );
+ }
+
+ public SimpleValue make() {
+ validate();
+ log.debug( "building SimpleValue for {}", propertyName );
+ if ( table == null ) {
+ table = columns[0].getTable();
+ }
+ SimpleValue simpleValue = new SimpleValue( table );
+ return fillSimpleValue( simpleValue );
+ }
+
+ public SimpleValue fillSimpleValue(SimpleValue simpleValue) {
+ String type = BinderHelper.isDefault( explicitType ) ? returnedClassName : explicitType;
+ org.hibernate.mapping.TypeDef typeDef = mappings.getTypeDef( type );
+ if ( typeDef != null ) {
+ type = typeDef.getTypeClass();
+ simpleValue.setTypeParameters( typeDef.getParameters() );
+ }
+ if ( typeParameters != null && typeParameters.size() != 0 ) {
+ //explicit type params takes precedence over type def params
+ simpleValue.setTypeParameters( typeParameters );
+ }
+ simpleValue.setTypeName( type );
+ if ( persistentClassName != null ) {
+ simpleValue.setTypeUsingReflection( persistentClassName, propertyName );
+ }
+ for (Ejb3Column column : columns) {
+ column.linkWithValue( simpleValue );
+ }
+ return simpleValue;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/TableBinder.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/TableBinder.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/TableBinder.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,386 @@
+//$Id: TableBinder.java 14761 2008-06-11 13:51:06Z hardy.ferentschik $
+package org.hibernate.cfg.annotations;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import javax.persistence.UniqueConstraint;
+
+import org.hibernate.AnnotationException;
+import org.hibernate.AssertionFailure;
+import org.hibernate.annotations.Index;
+import org.hibernate.annotations.common.util.StringHelper;
+import org.hibernate.cfg.BinderHelper;
+import org.hibernate.cfg.Ejb3JoinColumn;
+import org.hibernate.cfg.ExtendedMappings;
+import org.hibernate.cfg.IndexOrUniqueKeySecondPass;
+import org.hibernate.mapping.Collection;
+import org.hibernate.mapping.Column;
+import org.hibernate.mapping.DependantValue;
+import org.hibernate.mapping.JoinedSubclass;
+import org.hibernate.mapping.PersistentClass;
+import org.hibernate.mapping.Property;
+import org.hibernate.mapping.SimpleValue;
+import org.hibernate.mapping.Table;
+import org.hibernate.mapping.ToOne;
+import org.hibernate.mapping.Value;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Table related operations
+ *
+ * @author Emmanuel Bernard
+ */
+@SuppressWarnings("unchecked")
+public class TableBinder {
+ //TODO move it to a getter/setter strategy
+ private static Logger log = LoggerFactory.getLogger( TableBinder.class );
+ private String schema;
+ private String catalog;
+ private String name;
+ private boolean isAbstract;
+ private List<String[]> uniqueConstraints;
+ String constraints;
+ Table denormalizedSuperTable;
+ ExtendedMappings mappings;
+ private String ownerEntityTable;
+ private String associatedEntityTable;
+ private String propertyName;
+ private String ownerEntity;
+ private String associatedEntity;
+
+ public void setSchema(String schema) {
+ this.schema = schema;
+ }
+
+ public void setCatalog(String catalog) {
+ this.catalog = catalog;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public void setAbstract(boolean anAbstract) {
+ isAbstract = anAbstract;
+ }
+
+ public void setUniqueConstraints(UniqueConstraint[] uniqueConstraints) {
+ this.uniqueConstraints = TableBinder.buildUniqueConstraints( uniqueConstraints );
+ }
+
+ public void setConstraints(String constraints) {
+ this.constraints = constraints;
+ }
+
+ public void setDenormalizedSuperTable(Table denormalizedSuperTable) {
+ this.denormalizedSuperTable = denormalizedSuperTable;
+ }
+
+ public void setMappings(ExtendedMappings mappings) {
+ this.mappings = mappings;
+ }
+
+ // only bind association table currently
+ public Table bind() {
+ //logicalName only accurate for assoc table...
+ String unquotedOwnerTable = StringHelper.unquote( ownerEntityTable );
+ String unquotedAssocTable = StringHelper.unquote( associatedEntityTable );
+
+ String logicalName = mappings.getNamingStrategy()
+ .logicalCollectionTableName(
+ name,
+ unquotedOwnerTable,
+ unquotedAssocTable,
+ propertyName );
+ if ( StringHelper.isQuoted( ownerEntityTable ) || StringHelper.isQuoted( associatedEntityTable ) ) {
+ logicalName = StringHelper.quote( logicalName );
+ }
+ String extendedName;
+ if ( name != null ) {
+ extendedName = mappings.getNamingStrategy().tableName( name );
+ }
+ else {
+ extendedName = mappings.getNamingStrategy()
+ .collectionTableName(
+ ownerEntity,
+ unquotedOwnerTable,
+ associatedEntity,
+ unquotedAssocTable,
+ propertyName
+ );
+ if ( StringHelper.isQuoted( ownerEntityTable ) || StringHelper.isQuoted( associatedEntityTable ) ) {
+ extendedName = StringHelper.quote( extendedName );
+ }
+ }
+ return fillTable(
+ schema, catalog,
+ extendedName, logicalName, isAbstract, uniqueConstraints, constraints,
+ denormalizedSuperTable, mappings
+ );
+ }
+
+ public static Table fillTable(
+ String schema, String catalog, String realTableName, String logicalName, boolean isAbstract,
+ List uniqueConstraints, String constraints, Table denormalizedSuperTable, ExtendedMappings mappings
+ ) {
+ schema = BinderHelper.isDefault( schema ) ? mappings.getSchemaName() : schema;
+ catalog = BinderHelper.isDefault( catalog ) ? mappings.getCatalogName() : catalog;
+ Table table;
+ if ( denormalizedSuperTable != null ) {
+ table = mappings.addDenormalizedTable(
+ schema,
+ catalog,
+ realTableName,
+ isAbstract,
+ null, //subselect
+ denormalizedSuperTable
+ );
+ }
+ else {
+ table = mappings.addTable(
+ schema,
+ catalog,
+ realTableName,
+ null, //subselect
+ isAbstract
+ );
+ }
+ if ( uniqueConstraints != null && uniqueConstraints.size() > 0 ) {
+ mappings.addUniqueConstraints( table, uniqueConstraints );
+ }
+ if ( constraints != null ) table.addCheckConstraint( constraints );
+ //logicalName is null if we are in the second pass
+ if ( logicalName != null ) {
+ mappings.addTableBinding( schema, catalog, logicalName, realTableName, denormalizedSuperTable );
+ }
+ return table;
+ }
+
+ public static void bindFk(
+ PersistentClass referencedEntity, PersistentClass destinationEntity, Ejb3JoinColumn[] columns,
+ SimpleValue value,
+ boolean unique, ExtendedMappings mappings
+ ) {
+ PersistentClass associatedClass;
+ if ( destinationEntity != null ) {
+ //overidden destination
+ associatedClass = destinationEntity;
+ }
+ else {
+ associatedClass = columns[0].getPropertyHolder() == null ? null : columns[0].getPropertyHolder()
+ .getPersistentClass();
+ }
+ final String mappedByProperty = columns[0].getMappedBy();
+ if ( StringHelper.isNotEmpty( mappedByProperty ) ) {
+ /**
+ * Get the columns of the mapped-by property
+ * copy them and link the copy to the actual value
+ */
+ log.debug("Retrieving property {}.{}", associatedClass.getEntityName(), mappedByProperty);
+
+ final Property property = associatedClass.getRecursiveProperty( columns[0].getMappedBy() );
+ Iterator mappedByColumns;
+ if ( property.getValue() instanceof Collection ) {
+ Collection collection = ( (Collection) property.getValue() );
+ Value element = collection.getElement();
+ if ( element == null ) {
+ throw new AnnotationException(
+ "Illegal use of mappedBy on both sides of the relationship: "
+ + associatedClass.getEntityName() + "." + mappedByProperty
+ );
+ }
+ mappedByColumns = element.getColumnIterator();
+ }
+ else {
+ mappedByColumns = property.getValue().getColumnIterator();
+ }
+ while ( mappedByColumns.hasNext() ) {
+ Column column = (Column) mappedByColumns.next();
+ columns[0].overrideFromReferencedColumnIfNecessary( column );
+ columns[0].linkValueUsingAColumnCopy( column, value );
+ }
+ }
+ else if ( columns[0].isImplicit() ) {
+ /**
+ * if columns are implicit, then create the columns based on the
+ * referenced entity id columns
+ */
+ Iterator idColumns;
+ if ( referencedEntity instanceof JoinedSubclass ) {
+ idColumns = ( (JoinedSubclass) referencedEntity ).getKey().getColumnIterator();
+ }
+ else {
+ idColumns = referencedEntity.getIdentifier().getColumnIterator();
+ }
+ while ( idColumns.hasNext() ) {
+ Column column = (Column) idColumns.next();
+ columns[0].overrideFromReferencedColumnIfNecessary( column );
+ columns[0].linkValueUsingDefaultColumnNaming( column, referencedEntity, value );
+ }
+ }
+ else {
+ int fkEnum = Ejb3JoinColumn.checkReferencedColumnsType( columns, referencedEntity, mappings );
+
+ if ( Ejb3JoinColumn.NON_PK_REFERENCE == fkEnum ) {
+ String referencedPropertyName;
+ if ( value instanceof ToOne ) {
+ referencedPropertyName = ( (ToOne) value ).getReferencedPropertyName();
+ }
+ else if ( value instanceof DependantValue ) {
+ String propertyName = columns[0].getPropertyName();
+ if ( propertyName != null ) {
+ Collection collection = (Collection) referencedEntity.getRecursiveProperty( propertyName )
+ .getValue();
+ referencedPropertyName = collection.getReferencedPropertyName();
+ }
+ else {
+ throw new AnnotationException( "SecondaryTable JoinColumn cannot reference a non primary key" );
+ }
+
+ }
+ else {
+ throw new AssertionFailure(
+ "Do a property ref on an unexpected Value type: "
+ + value.getClass().getName()
+ );
+ }
+ if ( referencedPropertyName == null ) {
+ throw new AssertionFailure(
+ "No property ref found while expected"
+ );
+ }
+ Property synthProp = referencedEntity.getRecursiveProperty( referencedPropertyName );
+ if ( synthProp == null ) {
+ throw new AssertionFailure(
+ "Cannot find synthProp: " + referencedEntity.getEntityName() + "." + referencedPropertyName
+ );
+ }
+ linkJoinColumnWithValueOverridingNameIfImplicit(
+ referencedEntity, synthProp.getColumnIterator(), columns, value
+ );
+
+ }
+ else {
+ if ( Ejb3JoinColumn.NO_REFERENCE == fkEnum ) {
+ //implicit case, we hope PK and FK columns are in the same order
+ if ( columns.length != referencedEntity.getIdentifier().getColumnSpan() ) {
+ throw new AnnotationException(
+ "A Foreign key refering " + referencedEntity.getEntityName()
+ + " from " + associatedClass.getEntityName()
+ + " has the wrong number of column. should be " + referencedEntity.getIdentifier()
+ .getColumnSpan()
+ );
+ }
+ linkJoinColumnWithValueOverridingNameIfImplicit(
+ referencedEntity,
+ referencedEntity.getIdentifier().getColumnIterator(),
+ columns,
+ value
+ );
+ }
+ else {
+ //explicit referencedColumnName
+ Iterator idColItr = referencedEntity.getKey().getColumnIterator();
+ org.hibernate.mapping.Column col;
+ Table table = referencedEntity.getTable(); //works cause the pk has to be on the primary table
+ if ( !idColItr.hasNext() ) log.debug( "No column in the identifier!" );
+ while ( idColItr.hasNext() ) {
+ boolean match = false;
+ //for each PK column, find the associated FK column.
+ col = (org.hibernate.mapping.Column) idColItr.next();
+ for (Ejb3JoinColumn joinCol : columns) {
+ String referencedColumn = joinCol.getReferencedColumn();
+ referencedColumn = mappings.getPhysicalColumnName( referencedColumn, table );
+ if ( referencedColumn.equals( col.getName() ) ) {
+ //proper join column
+ if ( joinCol.isNameDeferred() ) {
+ joinCol.linkValueUsingDefaultColumnNaming(
+ col, referencedEntity, value
+ );
+ }
+ else {
+ joinCol.linkWithValue( value );
+ }
+ joinCol.overrideFromReferencedColumnIfNecessary( col );
+ match = true;
+ break;
+ }
+ }
+ if ( !match ) {
+ throw new AnnotationException(
+ "Column name " + col.getName() + " of "
+ + referencedEntity.getEntityName() + " not found in JoinColumns.referencedColumnName"
+ );
+ }
+ }
+ }
+ }
+ }
+ value.createForeignKey();
+ if ( unique == true ) {
+ createUniqueConstraint( value );
+ }
+ }
+
+ private static void linkJoinColumnWithValueOverridingNameIfImplicit(
+ PersistentClass referencedEntity, Iterator columnIterator, Ejb3JoinColumn[] columns, SimpleValue value
+ ) {
+ for (Ejb3JoinColumn joinCol : columns) {
+ Column synthCol = (Column) columnIterator.next();
+ if ( joinCol.isNameDeferred() ) {
+ //this has to be the default value
+ joinCol.linkValueUsingDefaultColumnNaming( synthCol, referencedEntity, value );
+ }
+ else {
+ joinCol.linkWithValue( value );
+ joinCol.overrideFromReferencedColumnIfNecessary( synthCol );
+ }
+ }
+ }
+
+ public static void createUniqueConstraint(Value value) {
+ Iterator iter = value.getColumnIterator();
+ ArrayList cols = new ArrayList();
+ while ( iter.hasNext() ) {
+ cols.add( iter.next() );
+ }
+ value.getTable().createUniqueKey( cols );
+ }
+
+ public static void addIndexes(Table hibTable, Index[] indexes, ExtendedMappings mappings) {
+ for (Index index : indexes) {
+ //no need to handle inSecondPass here since it is only called from EntityBinder
+ mappings.addSecondPass(
+ new IndexOrUniqueKeySecondPass( hibTable, index.name(), index.columnNames(), mappings )
+ );
+ }
+ }
+
+ public static List<String[]> buildUniqueConstraints(UniqueConstraint[] constraintsArray) {
+ List<String[]> result = new ArrayList<String[]>();
+ if ( constraintsArray.length != 0 ) {
+ for (UniqueConstraint uc : constraintsArray) {
+ result.add( uc.columnNames() );
+ }
+ }
+ return result;
+ }
+
+ public void setDefaultName(
+ String ownerEntity, String ownerEntityTable, String associatedEntity, String associatedEntityTable,
+ String propertyName
+ ) {
+ this.ownerEntity = ownerEntity;
+ this.ownerEntityTable = ownerEntityTable;
+ this.associatedEntity = associatedEntity;
+ this.associatedEntityTable = associatedEntityTable;
+ this.propertyName = propertyName;
+ this.name = null;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/Version.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/Version.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/Version.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,20 @@
+//$Id: Version.java 15098 2008-08-18 17:54:58Z hardy.ferentschik $
+package org.hibernate.cfg.annotations;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class Version {
+ public static final String VERSION = "3.4.0.GA";
+ private static Logger log = LoggerFactory.getLogger( Version.class );
+
+ static {
+ log.info( "Hibernate Annotations {}", VERSION );
+ }
+
+ public static void touch() {
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/reflection/EJB3OverridenAnnotationReader.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/reflection/EJB3OverridenAnnotationReader.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/reflection/EJB3OverridenAnnotationReader.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,2081 @@
+package org.hibernate.cfg.annotations.reflection;
+
+import java.beans.Introspector;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.AccessibleObject;
+import java.lang.reflect.AnnotatedElement;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.persistence.AssociationOverride;
+import javax.persistence.AssociationOverrides;
+import javax.persistence.AttributeOverride;
+import javax.persistence.AttributeOverrides;
+import javax.persistence.Basic;
+import javax.persistence.CascadeType;
+import javax.persistence.Column;
+import javax.persistence.ColumnResult;
+import javax.persistence.DiscriminatorColumn;
+import javax.persistence.DiscriminatorType;
+import javax.persistence.DiscriminatorValue;
+import javax.persistence.Embeddable;
+import javax.persistence.Embedded;
+import javax.persistence.EmbeddedId;
+import javax.persistence.Entity;
+import javax.persistence.EntityListeners;
+import javax.persistence.EntityResult;
+import javax.persistence.EnumType;
+import javax.persistence.Enumerated;
+import javax.persistence.ExcludeDefaultListeners;
+import javax.persistence.ExcludeSuperclassListeners;
+import javax.persistence.FetchType;
+import javax.persistence.FieldResult;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.IdClass;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinColumns;
+import javax.persistence.JoinTable;
+import javax.persistence.Lob;
+import javax.persistence.ManyToMany;
+import javax.persistence.ManyToOne;
+import javax.persistence.MapKey;
+import javax.persistence.MappedSuperclass;
+import javax.persistence.NamedNativeQueries;
+import javax.persistence.NamedNativeQuery;
+import javax.persistence.NamedQueries;
+import javax.persistence.NamedQuery;
+import javax.persistence.OneToMany;
+import javax.persistence.OneToOne;
+import javax.persistence.OrderBy;
+import javax.persistence.PostLoad;
+import javax.persistence.PostPersist;
+import javax.persistence.PostRemove;
+import javax.persistence.PostUpdate;
+import javax.persistence.PrePersist;
+import javax.persistence.PreRemove;
+import javax.persistence.PreUpdate;
+import javax.persistence.PrimaryKeyJoinColumn;
+import javax.persistence.PrimaryKeyJoinColumns;
+import javax.persistence.QueryHint;
+import javax.persistence.SecondaryTable;
+import javax.persistence.SecondaryTables;
+import javax.persistence.SequenceGenerator;
+import javax.persistence.SqlResultSetMapping;
+import javax.persistence.SqlResultSetMappings;
+import javax.persistence.Table;
+import javax.persistence.TableGenerator;
+import javax.persistence.Temporal;
+import javax.persistence.TemporalType;
+import javax.persistence.Transient;
+import javax.persistence.UniqueConstraint;
+import javax.persistence.Version;
+
+import org.dom4j.Attribute;
+import org.dom4j.Element;
+import org.hibernate.AnnotationException;
+import org.hibernate.annotations.AccessType;
+import org.hibernate.annotations.CollectionOfElements;
+import org.hibernate.annotations.Columns;
+import org.hibernate.annotations.common.annotationfactory.AnnotationDescriptor;
+import org.hibernate.annotations.common.annotationfactory.AnnotationFactory;
+import org.hibernate.annotations.common.reflection.AnnotationReader;
+import org.hibernate.annotations.common.reflection.Filter;
+import org.hibernate.annotations.common.reflection.ReflectionUtil;
+import org.hibernate.util.ReflectHelper;
+import org.hibernate.util.StringHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Encapsulates the overriding of Java annotations from an EJB 3.0 descriptor.
+ *
+ * @author Paolo Perrotta
+ * @author Davide Marchignoli
+ * @author Emmanuel Bernard
+ */
+@SuppressWarnings("unchecked")
+public class EJB3OverridenAnnotationReader implements AnnotationReader {
+ private Logger log = LoggerFactory.getLogger( EJB3OverridenAnnotationReader.class );
+ private static final Map<Class, String> annotationToXml;
+ private static final String SCHEMA_VALIDATION = "Activate schema validation for more informations";
+ private static final Filter FILTER = new Filter() {
+ public boolean returnStatic() {
+ return false;
+ }
+
+ public boolean returnTransient() {
+ return false;
+ }
+ };
+
+ static {
+ annotationToXml = new HashMap<Class, String>();
+ annotationToXml.put( Entity.class, "entity" );
+ annotationToXml.put( MappedSuperclass.class, "mapped-superclass" );
+ annotationToXml.put( Embeddable.class, "embeddable" );
+ annotationToXml.put( Table.class, "table" );
+ annotationToXml.put( SecondaryTable.class, "secondary-table" );
+ annotationToXml.put( SecondaryTables.class, "secondary-table" );
+ annotationToXml.put( PrimaryKeyJoinColumn.class, "primary-key-join-column" );
+ annotationToXml.put( PrimaryKeyJoinColumns.class, "primary-key-join-column" );
+ annotationToXml.put( IdClass.class, "id-class" );
+ annotationToXml.put( Inheritance.class, "inheritance" );
+ annotationToXml.put( DiscriminatorValue.class, "discriminator-value" );
+ annotationToXml.put( DiscriminatorColumn.class, "discriminator-column" );
+ annotationToXml.put( SequenceGenerator.class, "sequence-generator" );
+ annotationToXml.put( TableGenerator.class, "table-generator" );
+ annotationToXml.put( NamedQuery.class, "named-query" );
+ annotationToXml.put( NamedQueries.class, "named-query" );
+ annotationToXml.put( NamedNativeQuery.class, "named-native-query" );
+ annotationToXml.put( NamedNativeQueries.class, "named-native-query" );
+ annotationToXml.put( SqlResultSetMapping.class, "sql-result-set-mapping" );
+ annotationToXml.put( SqlResultSetMappings.class, "sql-result-set-mapping" );
+ annotationToXml.put( ExcludeDefaultListeners.class, "exclude-default-listeners" );
+ annotationToXml.put( ExcludeSuperclassListeners.class, "exclude-superclass-listeners" );
+ annotationToXml.put( AccessType.class, "access" );
+ annotationToXml.put( AttributeOverride.class, "attribute-override" );
+ annotationToXml.put( AttributeOverrides.class, "attribute-override" );
+ annotationToXml.put( AttributeOverride.class, "association-override" );
+ annotationToXml.put( AttributeOverrides.class, "association-override" );
+ annotationToXml.put( Id.class, "id" );
+ annotationToXml.put( EmbeddedId.class, "embedded-id" );
+ annotationToXml.put( GeneratedValue.class, "generated-value" );
+ annotationToXml.put( Column.class, "column" );
+ annotationToXml.put( Columns.class, "column" );
+ annotationToXml.put( Temporal.class, "temporal" );
+ annotationToXml.put( Lob.class, "lob" );
+ annotationToXml.put( Enumerated.class, "enumerated" );
+ annotationToXml.put( Version.class, "version" );
+ annotationToXml.put( Transient.class, "transient" );
+ annotationToXml.put( Basic.class, "basic" );
+ annotationToXml.put( Embedded.class, "embedded" );
+ annotationToXml.put( ManyToOne.class, "many-to-one" );
+ annotationToXml.put( OneToOne.class, "one-to-one" );
+ annotationToXml.put( OneToMany.class, "one-to-many" );
+ annotationToXml.put( ManyToMany.class, "many-to-many" );
+ annotationToXml.put( JoinTable.class, "join-table" );
+ annotationToXml.put( JoinColumn.class, "join-column" );
+ annotationToXml.put( JoinColumns.class, "join-column" );
+ annotationToXml.put( MapKey.class, "map-key" );
+ annotationToXml.put( OrderBy.class, "order-by" );
+ annotationToXml.put( EntityListeners.class, "entity-listeners" );
+ annotationToXml.put( PrePersist.class, "pre-persist" );
+ annotationToXml.put( PreRemove.class, "pre-remove" );
+ annotationToXml.put( PreUpdate.class, "pre-update" );
+ annotationToXml.put( PostPersist.class, "post-persist" );
+ annotationToXml.put( PostRemove.class, "post-remove" );
+ annotationToXml.put( PostUpdate.class, "post-update" );
+ annotationToXml.put( PostLoad.class, "post-load" );
+ }
+
+ private XMLContext xmlContext;
+ private String className;
+ private String propertyName;
+ private PropertyType propertyType;
+ private transient Annotation[] annotations;
+ private transient Map<Class, Annotation> annotationsMap;
+ private static final String WORD_SEPARATOR = "-";
+ private transient List<Element> elementsForProperty;
+ private AccessibleObject mirroredAttribute;
+ private final AnnotatedElement element;
+
+ private enum PropertyType {
+ PROPERTY,
+ FIELD,
+ METHOD
+ }
+
+ public EJB3OverridenAnnotationReader(AnnotatedElement el, XMLContext xmlContext) {
+ this.element = el;
+ this.xmlContext = xmlContext;
+ if ( el instanceof Class ) {
+ Class clazz = (Class) el;
+ className = clazz.getName();
+ }
+ else if ( el instanceof Field ) {
+ Field field = (Field) el;
+ className = field.getDeclaringClass().getName();
+ propertyName = field.getName();
+ propertyType = PropertyType.FIELD;
+ String expectedGetter = "get" + Character.toUpperCase( propertyName.charAt( 0 ) ) + propertyName.substring(
+ 1
+ );
+ try {
+ mirroredAttribute = field.getDeclaringClass().getDeclaredMethod( expectedGetter );
+ }
+ catch (NoSuchMethodException e) {
+ //no method
+ }
+ }
+ else if ( el instanceof Method ) {
+ Method method = (Method) el;
+ className = method.getDeclaringClass().getName();
+ propertyName = method.getName();
+ if ( ReflectionUtil.isProperty(
+ method,
+ null, //this is yukky!! we'd rather get the TypeEnvironment()
+ FILTER
+ ) ) {
+ if ( propertyName.startsWith( "get" ) ) {
+ propertyName = Introspector.decapitalize( propertyName.substring( "get".length() ) );
+ }
+ else if ( propertyName.startsWith( "is" ) ) {
+ propertyName = Introspector.decapitalize( propertyName.substring( "is".length() ) );
+ }
+ else {
+ throw new RuntimeException( "Method " + propertyName + " is not a property getter" );
+ }
+ propertyType = PropertyType.PROPERTY;
+ try {
+ mirroredAttribute = method.getDeclaringClass().getDeclaredField( propertyName );
+ }
+ catch (NoSuchFieldException e) {
+ //no method
+ }
+ }
+ else {
+ propertyType = PropertyType.METHOD;
+ }
+ }
+ else {
+ className = null;
+ propertyName = null;
+ }
+ }
+
+ public <T extends Annotation> T getAnnotation(Class<T> annotationType) {
+ initAnnotations();
+ return (T) annotationsMap.get( annotationType );
+ }
+
+ public <T extends Annotation> boolean isAnnotationPresent(Class<T> annotationType) {
+ initAnnotations();
+ return (T) annotationsMap.get( annotationType ) != null;
+ }
+
+ public Annotation[] getAnnotations() {
+ initAnnotations();
+ return annotations;
+ }
+
+ private void initAnnotations() {
+ if ( annotations == null ) {
+ XMLContext.Default defaults = xmlContext.getDefault( className );
+ if ( className != null && propertyName == null ) {
+ //is a class
+ Element tree = xmlContext.getXMLTree( className, null );
+ Annotation[] annotations = getJavaAnnotations();
+ List<Annotation> annotationList = new ArrayList<Annotation>( annotations.length + 5 );
+ annotationsMap = new HashMap<Class, Annotation>( annotations.length + 5 );
+ for (Annotation annotation : annotations) {
+ if ( !annotationToXml.containsKey( annotation.annotationType() ) ) {
+ //unknown annotations are left over
+ annotationList.add( annotation );
+ }
+ }
+ addIfNotNull( annotationList, getEntity( tree, defaults ) );
+ addIfNotNull( annotationList, getMappedSuperclass( tree, defaults ) );
+ addIfNotNull( annotationList, getEmbeddable( tree, defaults ) );
+ addIfNotNull( annotationList, getTable( tree, defaults ) );
+ addIfNotNull( annotationList, getSecondaryTables( tree, defaults ) );
+ addIfNotNull( annotationList, getPrimaryKeyJoinColumns( tree, defaults ) );
+ addIfNotNull( annotationList, getIdClass( tree, defaults ) );
+ addIfNotNull( annotationList, getInheritance( tree, defaults ) );
+ addIfNotNull( annotationList, getDiscriminatorValue( tree, defaults ) );
+ addIfNotNull( annotationList, getDiscriminatorColumn( tree, defaults ) );
+ addIfNotNull( annotationList, getSequenceGenerator( tree, defaults ) );
+ addIfNotNull( annotationList, getTableGenerator( tree, defaults ) );
+ addIfNotNull( annotationList, getNamedQueries( tree, defaults ) );
+ addIfNotNull( annotationList, getNamedNativeQueries( tree, defaults ) );
+ addIfNotNull( annotationList, getSqlResultSetMappings( tree, defaults ) );
+ addIfNotNull( annotationList, getExcludeDefaultListeners( tree, defaults ) );
+ addIfNotNull( annotationList, getExcludeSuperclassListeners( tree, defaults ) );
+ addIfNotNull( annotationList, getAccessType( tree, defaults ) );
+ addIfNotNull( annotationList, getAttributeOverrides( tree, defaults ) );
+ addIfNotNull( annotationList, getAssociationOverrides( tree, defaults ) );
+ addIfNotNull( annotationList, getEntityListeners( tree, defaults ) );
+ //FIXME use annotationsMap rather than annotationList this will be faster since the annotation type is usually known at put() time
+ this.annotations = annotationList.toArray( new Annotation[annotationList.size()] );
+ for (Annotation ann : this.annotations) {
+ annotationsMap.put( ann.annotationType(), ann );
+ }
+ checkForOrphanProperties( tree );
+ }
+ else if ( className != null ) { //&& propertyName != null ) { //always true but less confusing
+ Element tree = xmlContext.getXMLTree( className, propertyName );
+ Annotation[] annotations = getJavaAnnotations();
+ List<Annotation> annotationList = new ArrayList<Annotation>( annotations.length + 5 );
+ annotationsMap = new HashMap<Class, Annotation>( annotations.length + 5 );
+ for (Annotation annotation : annotations) {
+ if ( !annotationToXml.containsKey( annotation.annotationType() ) ) {
+ //unknown annotations are left over
+ annotationList.add( annotation );
+ }
+ }
+ preCalculateElementsForProperty( tree );
+ Transient transientAnn = getTransient( defaults );
+ if ( transientAnn != null ) {
+ annotationList.add( transientAnn );
+ }
+ else {
+ if ( defaults.canUseJavaAnnotations() ) {
+ Annotation annotation = getJavaAnnotation( AccessType.class );
+ addIfNotNull( annotationList, annotation );
+ }
+ getId( annotationList, defaults );
+ getEmbeddedId( annotationList, defaults );
+ getEmbedded( annotationList, defaults );
+ getBasic( annotationList, defaults );
+ getVersion( annotationList, defaults );
+ getAssociation( ManyToOne.class, annotationList, defaults );
+ getAssociation( OneToOne.class, annotationList, defaults );
+ getAssociation( OneToMany.class, annotationList, defaults );
+ getAssociation( ManyToMany.class, annotationList, defaults );
+ addIfNotNull( annotationList, getSequenceGenerator( elementsForProperty, defaults ) );
+ addIfNotNull( annotationList, getTableGenerator( elementsForProperty, defaults ) );
+ addIfNotNull( annotationList, getAttributeOverrides( elementsForProperty, defaults ) );
+
+ }
+ processEventAnnotations( annotationList, defaults );
+ //FIXME use annotationsMap rather than annotationList this will be faster since the annotation type is usually known at put() time
+ this.annotations = annotationList.toArray( new Annotation[annotationList.size()] );
+ for (Annotation ann : this.annotations) {
+ annotationsMap.put( ann.annotationType(), ann );
+ }
+ }
+ else {
+ this.annotations = getJavaAnnotations();
+ annotationsMap = new HashMap<Class, Annotation>( annotations.length + 5 );
+ for (Annotation ann : this.annotations) {
+ annotationsMap.put( ann.annotationType(), ann );
+ }
+ }
+ }
+ }
+
+ private void checkForOrphanProperties(Element tree) {
+ Class clazz;
+ try {
+ clazz = ReflectHelper.classForName( className, this.getClass() );
+ }
+ catch (ClassNotFoundException e) {
+ return; //a primitive type most likely
+ }
+ Element element = tree != null ? tree.element( "attributes" ) : null;
+ //put entity.attributes elements
+ if ( element != null ) {
+ //precompute the list of properties
+ //TODO is it really useful...
+ Set<String> properties = new HashSet<String>();
+ for (Field field : clazz.getFields()) {
+ properties.add( field.getName() );
+ }
+ for (Method method : clazz.getMethods()) {
+ String name = method.getName();
+ if ( name.startsWith( "get" ) ) {
+ properties.add( Introspector.decapitalize( name.substring( "get".length() ) ) );
+ }
+ else if ( name.startsWith( "is" ) ) {
+ properties.add( Introspector.decapitalize( name.substring( "is".length() ) ) );
+ }
+ }
+ for (Element subelement : (List<Element>) element.elements()) {
+ String propertyName = subelement.attributeValue( "name" );
+ if ( !properties.contains( propertyName ) ) {
+ log.warn( "Property {} not found in class"
+ + " but described in <mapping-file/> (possible typo error)",
+ StringHelper.qualify( className, propertyName ) );
+ }
+ }
+ }
+ }
+
+ /**
+ * Addes the Annotation to the list (only if it's not null) and then returns it.
+ */
+ private Annotation addIfNotNull(List<Annotation> annotationList, Annotation element) {
+ if ( element != null ) {
+ annotationList.add( element );
+ }
+ return element;
+ }
+
+ //TODO mutualize the next 2 methods
+ private Annotation getTableGenerator(List<Element> elementsForProperty, XMLContext.Default defaults) {
+ for (Element element : elementsForProperty) {
+ Element subelement = element != null ? element.element( annotationToXml.get( TableGenerator.class ) ) : null;
+ if ( subelement != null ) {
+ return buildTableGeneratorAnnotation( subelement, defaults );
+ }
+ }
+ if ( elementsForProperty.size() == 0 && defaults.canUseJavaAnnotations() ) {
+ return getJavaAnnotation( TableGenerator.class );
+ }
+ else {
+ return null;
+ }
+ }
+
+
+ private Annotation getSequenceGenerator(List<Element> elementsForProperty, XMLContext.Default defaults) {
+ for (Element element : elementsForProperty) {
+ Element subelement = element != null ? element.element( annotationToXml.get( SequenceGenerator.class ) ) : null;
+ if ( subelement != null ) {
+ return buildSequenceGeneratorAnnotation( subelement );
+ }
+ }
+ if ( elementsForProperty.size() == 0 && defaults.canUseJavaAnnotations() ) {
+ return getJavaAnnotation( SequenceGenerator.class );
+ }
+ else {
+ return null;
+ }
+ }
+
+ private void processEventAnnotations(List<Annotation> annotationList, XMLContext.Default defaults) {
+ boolean eventElement = false;
+ for (Element element : elementsForProperty) {
+ String elementName = element.getName();
+ if ( "pre-persist".equals( elementName ) ) {
+ AnnotationDescriptor ad = new AnnotationDescriptor( PrePersist.class );
+ annotationList.add( AnnotationFactory.create( ad ) );
+ eventElement = true;
+ }
+ else if ( "pre-remove".equals( elementName ) ) {
+ AnnotationDescriptor ad = new AnnotationDescriptor( PreRemove.class );
+ annotationList.add( AnnotationFactory.create( ad ) );
+ eventElement = true;
+ }
+ else if ( "pre-update".equals( elementName ) ) {
+ AnnotationDescriptor ad = new AnnotationDescriptor( PreUpdate.class );
+ annotationList.add( AnnotationFactory.create( ad ) );
+ eventElement = true;
+ }
+ else if ( "post-persist".equals( elementName ) ) {
+ AnnotationDescriptor ad = new AnnotationDescriptor( PostPersist.class );
+ annotationList.add( AnnotationFactory.create( ad ) );
+ eventElement = true;
+ }
+ else if ( "post-remove".equals( elementName ) ) {
+ AnnotationDescriptor ad = new AnnotationDescriptor( PostRemove.class );
+ annotationList.add( AnnotationFactory.create( ad ) );
+ eventElement = true;
+ }
+ else if ( "post-update".equals( elementName ) ) {
+ AnnotationDescriptor ad = new AnnotationDescriptor( PostUpdate.class );
+ annotationList.add( AnnotationFactory.create( ad ) );
+ eventElement = true;
+ }
+ else if ( "post-load".equals( elementName ) ) {
+ AnnotationDescriptor ad = new AnnotationDescriptor( PostLoad.class );
+ annotationList.add( AnnotationFactory.create( ad ) );
+ eventElement = true;
+ }
+ }
+ if ( !eventElement && defaults.canUseJavaAnnotations() ) {
+ Annotation ann = getJavaAnnotation( PrePersist.class );
+ addIfNotNull( annotationList, ann );
+ ann = getJavaAnnotation( PreRemove.class );
+ addIfNotNull( annotationList, ann );
+ ann = getJavaAnnotation( PreUpdate.class );
+ addIfNotNull( annotationList, ann );
+ ann = getJavaAnnotation( PostPersist.class );
+ addIfNotNull( annotationList, ann );
+ ann = getJavaAnnotation( PostRemove.class );
+ addIfNotNull( annotationList, ann );
+ ann = getJavaAnnotation( PostUpdate.class );
+ addIfNotNull( annotationList, ann );
+ ann = getJavaAnnotation( PostLoad.class );
+ addIfNotNull( annotationList, ann );
+ }
+ }
+
+ private EntityListeners getEntityListeners(Element tree, XMLContext.Default defaults) {
+ Element element = tree != null ? tree.element( "entity-listeners" ) : null;
+ if ( element != null ) {
+ List<Class> entityListenerClasses = new ArrayList<Class>();
+ for (Element subelement : (List<Element>) element.elements( "entity-listener" )) {
+ String className = subelement.attributeValue( "class" );
+ try {
+ entityListenerClasses.add(
+ ReflectHelper.classForName(
+ XMLContext.buildSafeClassName( className, defaults ),
+ this.getClass()
+ )
+ );
+ }
+ catch (ClassNotFoundException e) {
+ throw new AnnotationException(
+ "Unable to find " + element.getPath() + ".class: " + className, e
+ );
+ }
+ }
+ AnnotationDescriptor ad = new AnnotationDescriptor( EntityListeners.class );
+ ad.setValue( "value", entityListenerClasses.toArray( new Class[entityListenerClasses.size()] ) );
+ return AnnotationFactory.create( ad );
+ }
+ else if ( defaults.canUseJavaAnnotations() ) {
+ return getJavaAnnotation( EntityListeners.class );
+ }
+ else {
+ return null;
+ }
+ }
+
+ private JoinTable overridesDefaultsInJoinTable(Annotation annotation, XMLContext.Default defaults) {
+ //no element but might have some default or some annotation
+ boolean defaultToJoinTable = !( isJavaAnnotationPresent( JoinColumn.class )
+ || isJavaAnnotationPresent( JoinColumns.class ) );
+ final Class<? extends Annotation> annotationClass = annotation.annotationType();
+ defaultToJoinTable = defaultToJoinTable &&
+ ( ( annotationClass == ManyToMany.class && StringHelper.isEmpty( ( (ManyToMany) annotation ).mappedBy() ) )
+ || ( annotationClass == OneToMany.class && StringHelper.isEmpty( ( (OneToMany) annotation ).mappedBy() ) )
+ || ( annotationClass == CollectionOfElements.class )
+ );
+ final Class<JoinTable> annotationType = JoinTable.class;
+ if ( defaultToJoinTable
+ && ( StringHelper.isNotEmpty( defaults.getCatalog() )
+ || StringHelper.isNotEmpty( defaults.getSchema() ) ) ) {
+ AnnotationDescriptor ad = new AnnotationDescriptor( annotationType );
+ if ( defaults.canUseJavaAnnotations() ) {
+ JoinTable table = getJavaAnnotation( annotationType );
+ if ( table != null ) {
+ ad.setValue( "name", table.name() );
+ ad.setValue( "schema", table.schema() );
+ ad.setValue( "catalog", table.catalog() );
+ ad.setValue( "uniqueConstraints", table.uniqueConstraints() );
+ ad.setValue( "joinColumns", table.joinColumns() );
+ ad.setValue( "inverseJoinColumns", table.inverseJoinColumns() );
+ }
+ }
+ if ( StringHelper.isEmpty( (String) ad.valueOf( "schema" ) )
+ && StringHelper.isNotEmpty( defaults.getSchema() ) ) {
+ ad.setValue( "schema", defaults.getSchema() );
+ }
+ if ( StringHelper.isEmpty( (String) ad.valueOf( "catalog" ) )
+ && StringHelper.isNotEmpty( defaults.getCatalog() ) ) {
+ ad.setValue( "catalog", defaults.getCatalog() );
+ }
+ return AnnotationFactory.create( ad );
+ }
+ else if ( defaults.canUseJavaAnnotations() ) {
+ return getJavaAnnotation( annotationType );
+ }
+ else {
+ return null;
+ }
+ }
+
+ /*
+ * no partial overriding possible
+ */
+ private void getJoinTable(List<Annotation> annotationList, Element tree, XMLContext.Default defaults) {
+ Element subelement = tree == null ? null : tree.element( "join-table" );
+ final Class<JoinTable> annotationType = JoinTable.class;
+ if ( subelement != null ) {
+ //ignore java annotation, an element is defined
+ AnnotationDescriptor annotation = new AnnotationDescriptor( annotationType );
+ copyStringAttribute( annotation, subelement, "name", false );
+ copyStringAttribute( annotation, subelement, "catalog", false );
+ if ( StringHelper.isNotEmpty( defaults.getCatalog() )
+ && StringHelper.isEmpty( (String) annotation.valueOf( "catalog" ) ) ) {
+ annotation.setValue( "catalog", defaults.getCatalog() );
+ }
+ copyStringAttribute( annotation, subelement, "schema", false );
+ if ( StringHelper.isNotEmpty( defaults.getSchema() )
+ && StringHelper.isEmpty( (String) annotation.valueOf( "schema" ) ) ) {
+ annotation.setValue( "schema", defaults.getSchema() );
+ }
+ buildUniqueConstraints( annotation, subelement );
+ annotation.setValue( "joinColumns", getJoinColumns( subelement, false ) );
+ annotation.setValue( "inverseJoinColumns", getJoinColumns( subelement, true ) );
+ annotationList.add( AnnotationFactory.create( annotation ) );
+ }
+ }
+
+ private void getAssociation(
+ Class<? extends Annotation> annotationType, List<Annotation> annotationList, XMLContext.Default defaults
+ ) {
+ String xmlName = annotationToXml.get( annotationType );
+ for (Element element : elementsForProperty) {
+ if ( xmlName.equals( element.getName() ) ) {
+ AnnotationDescriptor ad = new AnnotationDescriptor( annotationType );
+ String className = element.attributeValue( "target-entity" );
+ if ( className != null ) {
+ Class clazz;
+ try {
+ clazz = ReflectHelper.classForName(
+ XMLContext.buildSafeClassName( className, defaults ),
+ this.getClass()
+ );
+ }
+ catch (ClassNotFoundException e) {
+ throw new AnnotationException(
+ "Unable to find " + element.getPath() + "target-entity: " + className, e
+ );
+ }
+ ad.setValue( "targetEntity", clazz );
+ }
+ getFetchType( ad, element );
+ getCascades( ad, element, defaults );
+ getJoinTable( annotationList, element, defaults );
+ buildJoinColumns( annotationList, element, defaults );
+ Annotation annotation = getPrimaryKeyJoinColumns( element, defaults );
+ addIfNotNull( annotationList, annotation );
+ copyBooleanAttribute( ad, element, "optional" );
+ copyStringAttribute( ad, element, "mapped-by", false );
+ getOrderBy( annotationList, element, defaults );
+ getMapKey( annotationList, element, defaults );
+ annotationList.add( AnnotationFactory.create( ad ) );
+ }
+ }
+ if ( elementsForProperty.size() == 0 && defaults.canUseJavaAnnotations() ) {
+ Annotation annotation = getJavaAnnotation( annotationType );
+ if ( annotation != null ) {
+ annotationList.add( annotation );
+ annotation = overridesDefaultsInJoinTable( annotation, defaults );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( JoinColumn.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( JoinColumns.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( PrimaryKeyJoinColumn.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( PrimaryKeyJoinColumns.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( MapKey.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( OrderBy.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( AttributeOverride.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( AttributeOverrides.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( AssociationOverride.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( AssociationOverrides.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( Lob.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( Enumerated.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( Temporal.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( Column.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( Columns.class );
+ addIfNotNull( annotationList, annotation );
+ }
+ else if ( isJavaAnnotationPresent( CollectionOfElements.class ) ) {
+ annotation = overridesDefaultsInJoinTable( getJavaAnnotation( CollectionOfElements.class ), defaults );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( JoinColumn.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( JoinColumns.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( PrimaryKeyJoinColumn.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( PrimaryKeyJoinColumns.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( MapKey.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( OrderBy.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( AttributeOverride.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( AttributeOverrides.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( AssociationOverride.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( AssociationOverrides.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( Lob.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( Enumerated.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( Temporal.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( Column.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( Columns.class );
+ addIfNotNull( annotationList, annotation );
+ }
+ }
+ }
+
+ private void getOrderBy(List<Annotation> annotationList, Element element, XMLContext.Default defaults) {
+ Element subelement = element != null ? element.element( "order-by" ) : null;
+ if ( subelement != null ) {
+ String orderByString = subelement.getTextTrim();
+ AnnotationDescriptor ad = new AnnotationDescriptor( OrderBy.class );
+ if ( StringHelper.isNotEmpty( orderByString ) ) ad.setValue( "value", orderByString );
+ annotationList.add( AnnotationFactory.create( ad ) );
+ }
+ }
+
+ private void getMapKey(List<Annotation> annotationList, Element element, XMLContext.Default defaults) {
+ Element subelement = element != null ? element.element( "map-key" ) : null;
+ if ( subelement != null ) {
+ String mapKeyString = subelement.attributeValue( "name" );
+ AnnotationDescriptor ad = new AnnotationDescriptor( MapKey.class );
+ if ( StringHelper.isNotEmpty( mapKeyString ) ) ad.setValue( "name", mapKeyString );
+ annotationList.add( AnnotationFactory.create( ad ) );
+ }
+ }
+
+ private void buildJoinColumns(List<Annotation> annotationList, Element element, XMLContext.Default defaults) {
+ JoinColumn[] joinColumns = getJoinColumns( element, false );
+ if ( joinColumns.length > 0 ) {
+ AnnotationDescriptor ad = new AnnotationDescriptor( JoinColumns.class );
+ ad.setValue( "value", joinColumns );
+ annotationList.add( AnnotationFactory.create( ad ) );
+ }
+ }
+
+ private void getCascades(AnnotationDescriptor ad, Element element, XMLContext.Default defaults) {
+ List<Element> elements = element != null ? element.elements( "cascade" ) : new ArrayList<Element>( 0 );
+ List<CascadeType> cascades = new ArrayList<CascadeType>();
+ for (Element subelement : elements) {
+ if ( subelement.element( "cascade-all" ) != null ) cascades.add( CascadeType.ALL );
+ if ( subelement.element( "cascade-persist" ) != null ) cascades.add( CascadeType.PERSIST );
+ if ( subelement.element( "cascade-merge" ) != null ) cascades.add( CascadeType.MERGE );
+ if ( subelement.element( "cascade-remove" ) != null ) cascades.add( CascadeType.REMOVE );
+ if ( subelement.element( "cascade-refresh" ) != null ) cascades.add( CascadeType.REFRESH );
+ }
+ if ( Boolean.TRUE.equals( defaults.getCascadePersist() )
+ && !cascades.contains( CascadeType.ALL ) && !cascades.contains( CascadeType.PERSIST ) ) {
+ cascades.add( CascadeType.PERSIST );
+ }
+ if ( cascades.size() > 0 ) {
+ ad.setValue( "cascade", cascades.toArray( new CascadeType[cascades.size()] ) );
+ }
+ }
+
+ private void getEmbedded(List<Annotation> annotationList, XMLContext.Default defaults) {
+ for (Element element : elementsForProperty) {
+ if ( "embedded".equals( element.getName() ) ) {
+ AnnotationDescriptor ad = new AnnotationDescriptor( Embedded.class );
+ annotationList.add( AnnotationFactory.create( ad ) );
+ }
+ }
+ if ( elementsForProperty.size() == 0 && defaults.canUseJavaAnnotations() ) {
+ Annotation annotation = getJavaAnnotation( Embedded.class );
+ if ( annotation != null ) {
+ annotationList.add( annotation );
+ annotation = getJavaAnnotation( AttributeOverride.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( AttributeOverrides.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( AssociationOverride.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( AssociationOverrides.class );
+ addIfNotNull( annotationList, annotation );
+ }
+ }
+ }
+
+ private Transient getTransient(XMLContext.Default defaults) {
+ for (Element element : elementsForProperty) {
+ if ( "transient".equals( element.getName() ) ) {
+ AnnotationDescriptor ad = new AnnotationDescriptor( Transient.class );
+ return AnnotationFactory.create( ad );
+ }
+ }
+ if ( elementsForProperty.size() == 0 && defaults.canUseJavaAnnotations() ) {
+ return getJavaAnnotation( Transient.class );
+ }
+ else {
+ return null;
+ }
+ }
+
+ private void getVersion(List<Annotation> annotationList, XMLContext.Default defaults) {
+ for (Element element : elementsForProperty) {
+ if ( "version".equals( element.getName() ) ) {
+ Annotation annotation = buildColumns( element );
+ addIfNotNull( annotationList, annotation );
+ getTemporal( annotationList, element );
+ AnnotationDescriptor basic = new AnnotationDescriptor( Version.class );
+ annotationList.add( AnnotationFactory.create( basic ) );
+ }
+ }
+ if ( elementsForProperty.size() == 0 && defaults.canUseJavaAnnotations() ) {
+ //we have nothing, so Java annotations might occurs
+ Annotation annotation = getJavaAnnotation( Version.class );
+ if ( annotation != null ) {
+ annotationList.add( annotation );
+ annotation = getJavaAnnotation( Column.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( Columns.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( Temporal.class );
+ addIfNotNull( annotationList, annotation );
+ }
+ }
+ }
+
+ private void getBasic(List<Annotation> annotationList, XMLContext.Default defaults) {
+ for (Element element : elementsForProperty) {
+ if ( "basic".equals( element.getName() ) ) {
+ Annotation annotation = buildColumns( element );
+ addIfNotNull( annotationList, annotation );
+ getTemporal( annotationList, element );
+ getLob( annotationList, element );
+ getEnumerated( annotationList, element );
+ AnnotationDescriptor basic = new AnnotationDescriptor( Basic.class );
+ getFetchType( basic, element );
+ copyBooleanAttribute( basic, element, "optional" );
+ annotationList.add( AnnotationFactory.create( basic ) );
+ }
+ }
+ if ( elementsForProperty.size() == 0 && defaults.canUseJavaAnnotations() ) {
+ //no annotation presence constraint, basic is the default
+ Annotation annotation = getJavaAnnotation( Basic.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( Lob.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( Enumerated.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( Temporal.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( Column.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( Columns.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( AttributeOverride.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( AttributeOverrides.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( AssociationOverride.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( AssociationOverrides.class );
+ addIfNotNull( annotationList, annotation );
+ }
+ }
+
+ private void getEnumerated(List<Annotation> annotationList, Element element) {
+ Element subElement = element != null ? element.element( "enumerated" ) : null;
+ if ( subElement != null ) {
+ AnnotationDescriptor ad = new AnnotationDescriptor( Enumerated.class );
+ String enumerated = subElement.getTextTrim();
+ if ( "ORDINAL".equalsIgnoreCase( enumerated ) ) {
+ ad.setValue( "value", EnumType.ORDINAL );
+ }
+ else if ( "STRING".equalsIgnoreCase( enumerated ) ) {
+ ad.setValue( "value", EnumType.STRING );
+ }
+ else if ( StringHelper.isNotEmpty( enumerated ) ) {
+ throw new AnnotationException( "Unknown EnumType: " + enumerated + ". " + SCHEMA_VALIDATION );
+ }
+ annotationList.add( AnnotationFactory.create( ad ) );
+ }
+ }
+
+ private void getLob(List<Annotation> annotationList, Element element) {
+ Element subElement = element != null ? element.element( "lob" ) : null;
+ if ( subElement != null ) {
+ annotationList.add( AnnotationFactory.create( new AnnotationDescriptor( Lob.class ) ) );
+ }
+ }
+
+ private void getFetchType(AnnotationDescriptor descriptor, Element element) {
+ String fetchString = element != null ? element.attributeValue( "fetch" ) : null;
+ if ( fetchString != null ) {
+ if ( "eager".equalsIgnoreCase( fetchString ) ) {
+ descriptor.setValue( "fetch", FetchType.EAGER );
+ }
+ else if ( "lazy".equalsIgnoreCase( fetchString ) ) {
+ descriptor.setValue( "fetch", FetchType.LAZY );
+ }
+ }
+ }
+
+ private void getEmbeddedId(List<Annotation> annotationList, XMLContext.Default defaults) {
+ for (Element element : elementsForProperty) {
+ if ( "embedded-id".equals( element.getName() ) ) {
+ if ( isProcessingId( defaults ) ) {
+ Annotation annotation = getAttributeOverrides( element, defaults );
+ addIfNotNull( annotationList, annotation );
+ annotation = getAssociationOverrides( element, defaults );
+ addIfNotNull( annotationList, annotation );
+ AnnotationDescriptor ad = new AnnotationDescriptor( EmbeddedId.class );
+ annotationList.add( AnnotationFactory.create( ad ) );
+ }
+// else {
+// if ( defaults.canUseJavaAnnotations() ) {
+// if ( ! properOverridingOnMetadataNonComplete ) {
+// //check that id exists on the other attribute
+// //TODO Id too?
+// if ( mirroredAttribute == null || ! mirroredAttribute.isAnnotationPresent(
+// EmbeddedId.class
+// ) ) {
+// throw new AnnotationException(
+// "Cannot override an property with <embedded-id> not having an @EmbeddedId already"
+// );
+// }
+// }
+// }
+// }
+ }
+ }
+ if ( elementsForProperty.size() == 0 && defaults.canUseJavaAnnotations() ) {
+ Annotation annotation = getJavaAnnotation( EmbeddedId.class );
+ if ( annotation != null ) {
+ annotationList.add( annotation );
+ annotation = getJavaAnnotation( Column.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( Columns.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( GeneratedValue.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( Temporal.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( TableGenerator.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( SequenceGenerator.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( AttributeOverride.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( AttributeOverrides.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( AssociationOverride.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( AssociationOverrides.class );
+ addIfNotNull( annotationList, annotation );
+ }
+ }
+ }
+
+ private void preCalculateElementsForProperty(Element tree) {
+ elementsForProperty = new ArrayList<Element>();
+ Element element = tree != null ? tree.element( "attributes" ) : null;
+ //put entity.attributes elements
+ if ( element != null ) {
+ for (Element subelement : (List<Element>) element.elements()) {
+ if ( propertyName.equals( subelement.attributeValue( "name" ) ) ) {
+ elementsForProperty.add( subelement );
+ }
+ }
+ }
+ //add pre-* etc from entity and pure entity listener classes
+ if ( tree != null ) {
+ for (Element subelement : (List<Element>) tree.elements()) {
+ if ( propertyName.equals( subelement.attributeValue( "method-name" ) ) ) {
+ elementsForProperty.add( subelement );
+ }
+ }
+ }
+ }
+
+ private void getId(List<Annotation> annotationList, XMLContext.Default defaults) {
+ for (Element element : elementsForProperty) {
+ if ( "id".equals( element.getName() ) ) {
+ boolean processId = isProcessingId( defaults );
+ if ( processId ) {
+ Annotation annotation = buildColumns( element );
+ addIfNotNull( annotationList, annotation );
+ annotation = buildGeneratedValue( element );
+ addIfNotNull( annotationList, annotation );
+ getTemporal( annotationList, element );
+ //FIXME: fix the priority of xml over java for generator names
+ annotation = getTableGenerator( element, defaults );
+ addIfNotNull( annotationList, annotation );
+ annotation = getSequenceGenerator( element, defaults );
+ addIfNotNull( annotationList, annotation );
+ AnnotationDescriptor id = new AnnotationDescriptor( Id.class );
+ annotationList.add( AnnotationFactory.create( id ) );
+ }
+// else {
+// if ( defaults.canUseJavaAnnotations() ) {
+// if ( ! properOverridingOnMetadataNonComplete ) {
+// //check that id exists on the other attribute
+// //TODO EmbeddedId too?
+// if ( mirroredAttribute == null || ! mirroredAttribute.isAnnotationPresent( Id.class ) ) {
+// throw new AnnotationException(
+// "Cannot override a property with <id> it does not have an @Id already"
+// );
+// }
+// }
+// }
+// }
+ }
+ }
+ if ( elementsForProperty.size() == 0 && defaults.canUseJavaAnnotations() ) {
+ Annotation annotation = getJavaAnnotation( Id.class );
+ if ( annotation != null ) {
+ annotationList.add( annotation );
+ annotation = getJavaAnnotation( Column.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( Columns.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( GeneratedValue.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( Temporal.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( TableGenerator.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( SequenceGenerator.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( AttributeOverride.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( AttributeOverrides.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( AssociationOverride.class );
+ addIfNotNull( annotationList, annotation );
+ annotation = getJavaAnnotation( AssociationOverrides.class );
+ addIfNotNull( annotationList, annotation );
+ }
+ }
+ }
+
+ private boolean isProcessingId(XMLContext.Default defaults) {
+ boolean isExplicit = defaults.getAccess() != null;
+ boolean correctAccess =
+ ( PropertyType.PROPERTY.equals( propertyType ) && "property".equals( defaults.getAccess() ) )
+ || ( PropertyType.FIELD.equals( propertyType ) && "field".equals( defaults.getAccess() ) );
+ boolean hasId = defaults.canUseJavaAnnotations()
+ && ( isJavaAnnotationPresent( Id.class ) || isJavaAnnotationPresent( EmbeddedId.class ) );
+ //if ( properAccessOnMetadataComplete || properOverridingOnMetadataNonComplete ) {
+ boolean mirrorAttributeIsId = defaults.canUseJavaAnnotations() &&
+ ( mirroredAttribute != null &&
+ ( mirroredAttribute.isAnnotationPresent( Id.class )
+ || mirroredAttribute.isAnnotationPresent( EmbeddedId.class ) ) );
+ boolean propertyIsDefault = PropertyType.PROPERTY.equals( propertyType )
+ && !mirrorAttributeIsId;
+ return correctAccess || ( !isExplicit && hasId ) || ( !isExplicit && propertyIsDefault );
+ }
+
+ private Columns buildColumns(Element element) {
+ List<Element> subelements = element.elements( "column" );
+ List<Column> columns = new ArrayList<Column>( subelements.size() );
+ for (Element subelement : subelements) {
+ columns.add( getColumn( subelement, false, element ) );
+ }
+ if ( columns.size() > 0 ) {
+ AnnotationDescriptor columnsDescr = new AnnotationDescriptor( Columns.class );
+ columnsDescr.setValue( "columns", columns.toArray( new Column[columns.size()] ) );
+ return AnnotationFactory.create( columnsDescr );
+ }
+ else {
+ return null;
+ }
+ }
+
+ private GeneratedValue buildGeneratedValue(Element element) {
+ Element subElement = element != null ? element.element( "generated-value" ) : null;
+ if ( subElement != null ) {
+ AnnotationDescriptor ad = new AnnotationDescriptor( GeneratedValue.class );
+ String strategy = subElement.attributeValue( "strategy" );
+ if ( "TABLE".equalsIgnoreCase( strategy ) ) {
+ ad.setValue( "strategy", GenerationType.TABLE );
+ }
+ else if ( "SEQUENCE".equalsIgnoreCase( strategy ) ) {
+ ad.setValue( "strategy", GenerationType.SEQUENCE );
+ }
+ else if ( "IDENTITY".equalsIgnoreCase( strategy ) ) {
+ ad.setValue( "strategy", GenerationType.IDENTITY );
+ }
+ else if ( "AUTO".equalsIgnoreCase( strategy ) ) {
+ ad.setValue( "strategy", GenerationType.AUTO );
+ }
+ else if ( StringHelper.isNotEmpty( strategy ) ) {
+ throw new AnnotationException( "Unknown GenerationType: " + strategy + ". " + SCHEMA_VALIDATION );
+ }
+ copyStringAttribute( ad, subElement, "generator", false );
+ return AnnotationFactory.create( ad );
+ }
+ else {
+ return null;
+ }
+ }
+
+ private void getTemporal(List<Annotation> annotationList, Element element) {
+ Element subElement = element != null ? element.element( "temporal" ) : null;
+ if ( subElement != null ) {
+ AnnotationDescriptor ad = new AnnotationDescriptor( Temporal.class );
+ String temporal = subElement.getTextTrim();
+ if ( "DATE".equalsIgnoreCase( temporal ) ) {
+ ad.setValue( "value", TemporalType.DATE );
+ }
+ else if ( "TIME".equalsIgnoreCase( temporal ) ) {
+ ad.setValue( "value", TemporalType.TIME );
+ }
+ else if ( "TIMESTAMP".equalsIgnoreCase( temporal ) ) {
+ ad.setValue( "value", TemporalType.TIMESTAMP );
+ }
+ else if ( StringHelper.isNotEmpty( temporal ) ) {
+ throw new AnnotationException( "Unknown TemporalType: " + temporal + ". " + SCHEMA_VALIDATION );
+ }
+ annotationList.add( AnnotationFactory.create( ad ) );
+ }
+ }
+
+ private AssociationOverrides getAssociationOverrides(Element tree, XMLContext.Default defaults) {
+ List<AssociationOverride> attributes = (List<AssociationOverride>) buildAssociationOverrides( tree );
+ if ( defaults.canUseJavaAnnotations() ) {
+ AssociationOverride annotation = getJavaAnnotation( AssociationOverride.class );
+ addAssociationOverrideIfNeeded( annotation, attributes );
+ AssociationOverrides annotations = getJavaAnnotation( AssociationOverrides.class );
+ if ( annotations != null ) {
+ for (AssociationOverride current : annotations.value()) {
+ addAssociationOverrideIfNeeded( current, attributes );
+ }
+ }
+ }
+ if ( attributes.size() > 0 ) {
+ AnnotationDescriptor ad = new AnnotationDescriptor( AssociationOverrides.class );
+ ad.setValue( "value", attributes.toArray( new AssociationOverride[attributes.size()] ) );
+ return AnnotationFactory.create( ad );
+ }
+ else {
+ return null;
+ }
+ }
+
+ private List<AssociationOverride> buildAssociationOverrides(Element element) {
+ List<Element> subelements = element == null ? null : element.elements( "association-override" );
+ List<AssociationOverride> overrides = new ArrayList<AssociationOverride>();
+ if ( subelements != null && subelements.size() > 0 ) {
+ for (Element current : subelements) {
+ AnnotationDescriptor override = new AnnotationDescriptor( AssociationOverride.class );
+ copyStringAttribute( override, current, "name", true );
+ override.setValue( "joinColumns", getJoinColumns( current, false ) );
+ overrides.add( (AssociationOverride) AnnotationFactory.create( override ) );
+ }
+ }
+ return overrides;
+ }
+
+ private JoinColumn[] getJoinColumns(Element element, boolean isInverse) {
+ List<Element> subelements = element != null ?
+ element.elements( isInverse ? "inverse-join-column" : "join-column" ) :
+ null;
+ List<JoinColumn> joinColumns = new ArrayList<JoinColumn>();
+ if ( subelements != null ) {
+ for (Element subelement : subelements) {
+ AnnotationDescriptor column = new AnnotationDescriptor( JoinColumn.class );
+ copyStringAttribute( column, subelement, "name", false );
+ copyStringAttribute( column, subelement, "referenced-column-name", false );
+ copyBooleanAttribute( column, subelement, "unique" );
+ copyBooleanAttribute( column, subelement, "nullable" );
+ copyBooleanAttribute( column, subelement, "insertable" );
+ copyBooleanAttribute( column, subelement, "updatable" );
+ copyStringAttribute( column, subelement, "column-definition", false );
+ copyStringAttribute( column, subelement, "table", false );
+ joinColumns.add( (JoinColumn) AnnotationFactory.create( column ) );
+ }
+ }
+ return joinColumns.toArray( new JoinColumn[joinColumns.size()] );
+ }
+
+ private void addAssociationOverrideIfNeeded(AssociationOverride annotation, List<AssociationOverride> overrides) {
+ if ( annotation != null ) {
+ String overrideName = annotation.name();
+ boolean present = false;
+ for (AssociationOverride current : overrides) {
+ if ( current.name().equals( overrideName ) ) {
+ present = true;
+ break;
+ }
+ }
+ if ( !present ) overrides.add( annotation );
+ }
+ }
+
+ private AttributeOverrides getAttributeOverrides(Element tree, XMLContext.Default defaults) {
+ List<AttributeOverride> attributes = buildAttributeOverrides( tree );
+ return mergeAttributeOverrides( defaults, attributes );
+ }
+
+ private AttributeOverrides getAttributeOverrides(List<Element> elements, XMLContext.Default defaults) {
+ List<AttributeOverride> attributes = new ArrayList<AttributeOverride>();
+ for (Element element : elements) {
+ attributes.addAll( buildAttributeOverrides( element ) );
+ }
+ return mergeAttributeOverrides( defaults, attributes );
+ }
+
+ private AttributeOverrides mergeAttributeOverrides(XMLContext.Default defaults,
+ List<AttributeOverride> attributes) {
+ if ( defaults.canUseJavaAnnotations() ) {
+ AttributeOverride annotation = getJavaAnnotation( AttributeOverride.class );
+ addAttributeOverrideIfNeeded( annotation, attributes );
+ AttributeOverrides annotations = getJavaAnnotation( AttributeOverrides.class );
+ if ( annotations != null ) {
+ for (AttributeOverride current : annotations.value()) {
+ addAttributeOverrideIfNeeded( current, attributes );
+ }
+ }
+ }
+ if ( attributes.size() > 0 ) {
+ AnnotationDescriptor ad = new AnnotationDescriptor( AttributeOverrides.class );
+ ad.setValue( "value", attributes.toArray( new AttributeOverride[attributes.size()] ) );
+ return AnnotationFactory.create( ad );
+ }
+ else {
+ return null;
+ }
+ }
+
+ private List<AttributeOverride> buildAttributeOverrides(Element element) {
+ List<Element> subelements = element == null ? null : element.elements( "attribute-override" );
+ return buildAttributeOverrides( subelements );
+ }
+
+ private List<AttributeOverride> buildAttributeOverrides(List<Element> subelements) {
+ List<AttributeOverride> overrides = new ArrayList<AttributeOverride>();
+ if ( subelements != null && subelements.size() > 0 ) {
+ for (Element current : subelements) {
+ if ( !current.getName().equals( "attribute-override" ) ) continue;
+ AnnotationDescriptor override = new AnnotationDescriptor( AttributeOverride.class );
+ copyStringAttribute( override, current, "name", true );
+ Element column = current != null ? current.element( "column" ) : null;
+ override.setValue( "column", getColumn( column, true, current ) );
+ overrides.add( (AttributeOverride) AnnotationFactory.create( override ) );
+ }
+ }
+ return overrides;
+ }
+
+ private Column getColumn(Element element, boolean isMandatory, Element current) {
+ //Element subelement = element != null ? element.element( "column" ) : null;
+ if ( element != null ) {
+ AnnotationDescriptor column = new AnnotationDescriptor( Column.class );
+ copyStringAttribute( column, element, "name", false );
+ copyBooleanAttribute( column, element, "unique" );
+ copyBooleanAttribute( column, element, "nullable" );
+ copyBooleanAttribute( column, element, "insertable" );
+ copyBooleanAttribute( column, element, "updatable" );
+ copyStringAttribute( column, element, "column-definition", false );
+ copyStringAttribute( column, element, "table", false );
+ copyIntegerAttribute( column, element, "length" );
+ copyIntegerAttribute( column, element, "precision" );
+ copyIntegerAttribute( column, element, "scale" );
+ return (Column) AnnotationFactory.create( column );
+ }
+ else {
+ if ( isMandatory ) {
+ throw new AnnotationException( current.getPath() + ".column is mandatory. " + SCHEMA_VALIDATION );
+ }
+ return null;
+ }
+ }
+
+ private void addAttributeOverrideIfNeeded(AttributeOverride annotation, List<AttributeOverride> overrides) {
+ if ( annotation != null ) {
+ String overrideName = annotation.name();
+ boolean present = false;
+ for (AttributeOverride current : overrides) {
+ if ( current.name().equals( overrideName ) ) {
+ present = true;
+ break;
+ }
+ }
+ if ( !present ) overrides.add( annotation );
+ }
+ }
+
+ private AccessType getAccessType(Element tree, XMLContext.Default defaults) {
+ String access = tree == null ? null : tree.attributeValue( "access" );
+ if ( "FIELD".equals( access ) || "PROPERTY".equals( access ) ) {
+ access = access.toLowerCase();
+ }
+ if ( access != null ) {
+ AnnotationDescriptor ad = new AnnotationDescriptor( AccessType.class );
+ ad.setValue( "value", access );
+ return AnnotationFactory.create( ad );
+ }
+ else if ( defaults.canUseJavaAnnotations() && isJavaAnnotationPresent( AccessType.class ) ) {
+ AccessType annotation = getJavaAnnotation( AccessType.class );
+ return annotation;
+ }
+ else if ( defaults.getAccess() != null ) {
+ AnnotationDescriptor ad = new AnnotationDescriptor( AccessType.class );
+ ad.setValue( "value", defaults.getAccess() );
+ return AnnotationFactory.create( ad );
+ }
+ else {
+ return null;
+ }
+ }
+
+ private ExcludeSuperclassListeners getExcludeSuperclassListeners(Element tree, XMLContext.Default defaults) {
+ return (ExcludeSuperclassListeners) getMarkerAnnotation( ExcludeSuperclassListeners.class, tree, defaults );
+ }
+
+ private ExcludeDefaultListeners getExcludeDefaultListeners(Element tree, XMLContext.Default defaults) {
+ return (ExcludeDefaultListeners) getMarkerAnnotation( ExcludeDefaultListeners.class, tree, defaults );
+ }
+
+ private Annotation getMarkerAnnotation(
+ Class<? extends Annotation> clazz, Element element, XMLContext.Default defaults
+ ) {
+ Element subelement = element == null ? null : element.element( annotationToXml.get( clazz ) );
+ if ( subelement != null ) {
+ return AnnotationFactory.create( new AnnotationDescriptor( clazz ) );
+ }
+ else if ( defaults.canUseJavaAnnotations() ) {
+ //TODO wonder whether it should be excluded so that user can undone it
+ return getJavaAnnotation( clazz );
+ }
+ else {
+ return null;
+ }
+ }
+
+ private SqlResultSetMappings getSqlResultSetMappings(Element tree, XMLContext.Default defaults) {
+ List<SqlResultSetMapping> results = (List<SqlResultSetMapping>) buildSqlResultsetMappings( tree, defaults );
+ if ( defaults.canUseJavaAnnotations() ) {
+ SqlResultSetMapping annotation = getJavaAnnotation( SqlResultSetMapping.class );
+ addSqlResultsetMappingIfNeeded( annotation, results );
+ SqlResultSetMappings annotations = getJavaAnnotation( SqlResultSetMappings.class );
+ if ( annotations != null ) {
+ for (SqlResultSetMapping current : annotations.value()) {
+ addSqlResultsetMappingIfNeeded( current, results );
+ }
+ }
+ }
+ if ( results.size() > 0 ) {
+ AnnotationDescriptor ad = new AnnotationDescriptor( SqlResultSetMappings.class );
+ ad.setValue( "value", results.toArray( new SqlResultSetMapping[results.size()] ) );
+ return AnnotationFactory.create( ad );
+ }
+ else {
+ return null;
+ }
+ }
+
+ public static List<SqlResultSetMapping> buildSqlResultsetMappings(Element element, XMLContext.Default defaults) {
+ if ( element == null ) return new ArrayList<SqlResultSetMapping>();
+ List resultsetElementList = element.elements( "sql-result-set-mapping" );
+ List<SqlResultSetMapping> resultsets = new ArrayList<SqlResultSetMapping>();
+ Iterator it = resultsetElementList.listIterator();
+ while ( it.hasNext() ) {
+ Element subelement = (Element) it.next();
+ AnnotationDescriptor ann = new AnnotationDescriptor( SqlResultSetMapping.class );
+ copyStringAttribute( ann, subelement, "name", true );
+ List<Element> elements = subelement.elements( "entity-result" );
+ List<EntityResult> entityResults = new ArrayList<EntityResult>( elements.size() );
+ for (Element entityResult : elements) {
+ AnnotationDescriptor entityResultDescriptor = new AnnotationDescriptor( EntityResult.class );
+ String clazzName = entityResult.attributeValue( "entity-class" );
+ if ( clazzName == null ) {
+ throw new AnnotationException( "<entity-result> without entity-class. " + SCHEMA_VALIDATION );
+ }
+ Class clazz = null;
+ try {
+ clazz = ReflectHelper.classForName(
+ XMLContext.buildSafeClassName( clazzName, defaults ),
+ EJB3OverridenAnnotationReader.class
+ );
+ }
+ catch (ClassNotFoundException e) {
+ throw new AnnotationException( "Unable to find entity-class: " + clazzName, e );
+ }
+ entityResultDescriptor.setValue( "entityClass", clazz );
+ copyStringAttribute( entityResultDescriptor, entityResult, "discriminator-column", false );
+ List<FieldResult> fieldResults = new ArrayList<FieldResult>();
+ for (Element fieldResult : (List<Element>) entityResult.elements( "field-result" )) {
+ AnnotationDescriptor fieldResultDescriptor = new AnnotationDescriptor( FieldResult.class );
+ copyStringAttribute( fieldResultDescriptor, fieldResult, "name", true );
+ copyStringAttribute( fieldResultDescriptor, fieldResult, "column", true );
+ fieldResults.add( (FieldResult) AnnotationFactory.create( fieldResultDescriptor ) );
+ }
+ entityResultDescriptor.setValue(
+ "fields", fieldResults.toArray( new FieldResult[fieldResults.size()] )
+ );
+ entityResults.add( (EntityResult) AnnotationFactory.create( entityResultDescriptor ) );
+ }
+ ann.setValue( "entities", entityResults.toArray( new EntityResult[entityResults.size()] ) );
+
+ elements = subelement.elements( "column-result" );
+ List<ColumnResult> columnResults = new ArrayList<ColumnResult>( elements.size() );
+ for (Element columnResult : elements) {
+ AnnotationDescriptor columnResultDescriptor = new AnnotationDescriptor( ColumnResult.class );
+ copyStringAttribute( columnResultDescriptor, columnResult, "name", true );
+ columnResults.add( (ColumnResult) AnnotationFactory.create( columnResultDescriptor ) );
+ }
+ ann.setValue( "columns", columnResults.toArray( new ColumnResult[columnResults.size()] ) );
+ //FIXME there is never such a result-class, get rid of it?
+ String clazzName = subelement.attributeValue( "result-class" );
+ if ( StringHelper.isNotEmpty( clazzName ) ) {
+ Class clazz = null;
+ try {
+ clazz = ReflectHelper.classForName(
+ XMLContext.buildSafeClassName( clazzName, defaults ),
+ EJB3OverridenAnnotationReader.class
+ );
+ }
+ catch (ClassNotFoundException e) {
+ throw new AnnotationException( "Unable to find entity-class: " + clazzName, e );
+ }
+ ann.setValue( "resultClass", clazz );
+ }
+ copyStringAttribute( ann, subelement, "result-set-mapping", false );
+ resultsets.add( (SqlResultSetMapping) AnnotationFactory.create( ann ) );
+ }
+ return resultsets;
+ }
+
+ private void addSqlResultsetMappingIfNeeded(SqlResultSetMapping annotation, List<SqlResultSetMapping> resultsets) {
+ if ( annotation != null ) {
+ String resultsetName = annotation.name();
+ boolean present = false;
+ for (SqlResultSetMapping current : resultsets) {
+ if ( current.name().equals( resultsetName ) ) {
+ present = true;
+ break;
+ }
+ }
+ if ( !present ) resultsets.add( annotation );
+ }
+ }
+
+ private NamedQueries getNamedQueries(Element tree, XMLContext.Default defaults) {
+ //TODO avoid the Proxy Creation (@NamedQueries) when possible
+ List<NamedQuery> queries = (List<NamedQuery>) buildNamedQueries( tree, false, defaults );
+ if ( defaults.canUseJavaAnnotations() ) {
+ NamedQuery annotation = getJavaAnnotation( NamedQuery.class );
+ addNamedQueryIfNeeded( annotation, queries );
+ NamedQueries annotations = getJavaAnnotation( NamedQueries.class );
+ if ( annotations != null ) {
+ for (NamedQuery current : annotations.value()) {
+ addNamedQueryIfNeeded( current, queries );
+ }
+ }
+ }
+ if ( queries.size() > 0 ) {
+ AnnotationDescriptor ad = new AnnotationDescriptor( NamedQueries.class );
+ ad.setValue( "value", queries.toArray( new NamedQuery[queries.size()] ) );
+ return AnnotationFactory.create( ad );
+ }
+ else {
+ return null;
+ }
+ }
+
+ private void addNamedQueryIfNeeded(NamedQuery annotation, List<NamedQuery> queries) {
+ if ( annotation != null ) {
+ String queryName = annotation.name();
+ boolean present = false;
+ for (NamedQuery current : queries) {
+ if ( current.name().equals( queryName ) ) {
+ present = true;
+ break;
+ }
+ }
+ if ( !present ) queries.add( annotation );
+ }
+ }
+
+ private NamedNativeQueries getNamedNativeQueries(Element tree, XMLContext.Default defaults) {
+ List<NamedNativeQuery> queries = (List<NamedNativeQuery>) buildNamedQueries( tree, true, defaults );
+ if ( defaults.canUseJavaAnnotations() ) {
+ NamedNativeQuery annotation = getJavaAnnotation( NamedNativeQuery.class );
+ addNamedNativeQueryIfNeeded( annotation, queries );
+ NamedNativeQueries annotations = getJavaAnnotation( NamedNativeQueries.class );
+ if ( annotations != null ) {
+ for (NamedNativeQuery current : annotations.value()) {
+ addNamedNativeQueryIfNeeded( current, queries );
+ }
+ }
+ }
+ if ( queries.size() > 0 ) {
+ AnnotationDescriptor ad = new AnnotationDescriptor( NamedNativeQueries.class );
+ ad.setValue( "value", queries.toArray( new NamedNativeQuery[queries.size()] ) );
+ return AnnotationFactory.create( ad );
+ }
+ else {
+ return null;
+ }
+ }
+
+ private void addNamedNativeQueryIfNeeded(NamedNativeQuery annotation, List<NamedNativeQuery> queries) {
+ if ( annotation != null ) {
+ String queryName = annotation.name();
+ boolean present = false;
+ for (NamedNativeQuery current : queries) {
+ if ( current.name().equals( queryName ) ) {
+ present = true;
+ break;
+ }
+ }
+ if ( !present ) queries.add( annotation );
+ }
+ }
+
+ public static List buildNamedQueries(Element element, boolean isNative, XMLContext.Default defaults) {
+ if ( element == null ) return new ArrayList();
+ List namedQueryElementList = isNative ?
+ element.elements( "named-native-query" ) :
+ element.elements( "named-query" );
+ List namedQueries = new ArrayList();
+ Iterator it = namedQueryElementList.listIterator();
+ while ( it.hasNext() ) {
+ Element subelement = (Element) it.next();
+ AnnotationDescriptor ann = new AnnotationDescriptor(
+ isNative ? NamedNativeQuery.class : NamedQuery.class
+ );
+ copyStringAttribute( ann, subelement, "name", false );
+ Element queryElt = subelement.element( "query" );
+ if ( queryElt == null ) throw new AnnotationException( "No <query> element found." + SCHEMA_VALIDATION );
+ ann.setValue( "query", queryElt.getTextTrim() );
+ List<Element> elements = subelement.elements( "hint" );
+ List<QueryHint> queryHints = new ArrayList<QueryHint>( elements.size() );
+ for (Element hint : elements) {
+ AnnotationDescriptor hintDescriptor = new AnnotationDescriptor( QueryHint.class );
+ String value = hint.attributeValue( "name" );
+ if ( value == null ) throw new AnnotationException( "<hint> without name. " + SCHEMA_VALIDATION );
+ hintDescriptor.setValue( "name", value );
+ value = hint.attributeValue( "value" );
+ if ( value == null ) throw new AnnotationException( "<hint> without value. " + SCHEMA_VALIDATION );
+ hintDescriptor.setValue( "value", value );
+ queryHints.add( (QueryHint) AnnotationFactory.create( hintDescriptor ) );
+ }
+ ann.setValue( "hints", queryHints.toArray( new QueryHint[queryHints.size()] ) );
+ String clazzName = subelement.attributeValue( "result-class" );
+ if ( StringHelper.isNotEmpty( clazzName ) ) {
+ Class clazz = null;
+ try {
+ clazz = ReflectHelper.classForName(
+ XMLContext.buildSafeClassName( clazzName, defaults ),
+ EJB3OverridenAnnotationReader.class
+ );
+ }
+ catch (ClassNotFoundException e) {
+ throw new AnnotationException( "Unable to find entity-class: " + clazzName, e );
+ }
+ ann.setValue( "resultClass", clazz );
+ }
+ copyStringAttribute( ann, subelement, "result-set-mapping", false );
+ namedQueries.add( AnnotationFactory.create( ann ) );
+ }
+ return namedQueries;
+ }
+
+ private TableGenerator getTableGenerator(Element tree, XMLContext.Default defaults) {
+ Element element = tree != null ? tree.element( annotationToXml.get( TableGenerator.class ) ) : null;
+ if ( element != null ) {
+ return buildTableGeneratorAnnotation( element, defaults );
+ }
+ else if ( defaults.canUseJavaAnnotations() && isJavaAnnotationPresent( TableGenerator.class ) ) {
+ TableGenerator tableAnn = getJavaAnnotation( TableGenerator.class );
+ if ( StringHelper.isNotEmpty( defaults.getSchema() )
+ || StringHelper.isNotEmpty( defaults.getCatalog() ) ) {
+ AnnotationDescriptor annotation = new AnnotationDescriptor( TableGenerator.class );
+ annotation.setValue( "name", tableAnn.name() );
+ annotation.setValue( "table", tableAnn.table() );
+ annotation.setValue( "catalog", tableAnn.table() );
+ if ( StringHelper.isEmpty( (String) annotation.valueOf( "catalog" ) )
+ && StringHelper.isNotEmpty( defaults.getCatalog() ) ) {
+ annotation.setValue( "catalog", defaults.getCatalog() );
+ }
+ annotation.setValue( "schema", tableAnn.table() );
+ if ( StringHelper.isEmpty( (String) annotation.valueOf( "schema" ) )
+ && StringHelper.isNotEmpty( defaults.getSchema() ) ) {
+ annotation.setValue( "catalog", defaults.getSchema() );
+ }
+ annotation.setValue( "pkColumnName", tableAnn.pkColumnName() );
+ annotation.setValue( "valueColumnName", tableAnn.valueColumnName() );
+ annotation.setValue( "pkColumnValue", tableAnn.pkColumnValue() );
+ annotation.setValue( "initialValue", tableAnn.initialValue() );
+ annotation.setValue( "allocationSize", tableAnn.allocationSize() );
+ annotation.setValue( "uniqueConstraints", tableAnn.uniqueConstraints() );
+ return AnnotationFactory.create( annotation );
+ }
+ else {
+ return tableAnn;
+ }
+ }
+ else {
+ return null;
+ }
+ }
+
+ public static TableGenerator buildTableGeneratorAnnotation(Element element, XMLContext.Default defaults) {
+ AnnotationDescriptor ad = new AnnotationDescriptor( TableGenerator.class );
+ copyStringAttribute( ad, element, "name", false );
+ copyStringAttribute( ad, element, "table", false );
+ copyStringAttribute( ad, element, "catalog", false );
+ copyStringAttribute( ad, element, "schema", false );
+ copyStringAttribute( ad, element, "pk-column-name", false );
+ copyStringAttribute( ad, element, "value-column-name", false );
+ copyStringAttribute( ad, element, "pk-column-value", false );
+ copyIntegerAttribute( ad, element, "initial-value" );
+ copyIntegerAttribute( ad, element, "allocation-size" );
+ buildUniqueConstraints( ad, element );
+ if ( StringHelper.isEmpty( (String) ad.valueOf( "schema" ) )
+ && StringHelper.isNotEmpty( defaults.getSchema() ) ) {
+ ad.setValue( "schema", defaults.getSchema() );
+ }
+ if ( StringHelper.isEmpty( (String) ad.valueOf( "catalog" ) )
+ && StringHelper.isNotEmpty( defaults.getCatalog() ) ) {
+ ad.setValue( "catalog", defaults.getCatalog() );
+ }
+ return AnnotationFactory.create( ad );
+ }
+
+ private SequenceGenerator getSequenceGenerator(Element tree, XMLContext.Default defaults) {
+ Element element = tree != null ? tree.element( annotationToXml.get( SequenceGenerator.class ) ) : null;
+ if ( element != null ) {
+ return buildSequenceGeneratorAnnotation( element );
+ }
+ else if ( defaults.canUseJavaAnnotations() ) {
+ return getJavaAnnotation( SequenceGenerator.class );
+ }
+ else {
+ return null;
+ }
+ }
+
+ public static SequenceGenerator buildSequenceGeneratorAnnotation(Element element) {
+ if ( element != null ) {
+ AnnotationDescriptor ad = new AnnotationDescriptor( SequenceGenerator.class );
+ copyStringAttribute( ad, element, "name", false );
+ copyStringAttribute( ad, element, "sequence-name", false );
+ copyIntegerAttribute( ad, element, "initial-value" );
+ copyIntegerAttribute( ad, element, "allocation-size" );
+ return AnnotationFactory.create( ad );
+ }
+ else {
+ return null;
+ }
+ }
+
+ private DiscriminatorColumn getDiscriminatorColumn(Element tree, XMLContext.Default defaults) {
+ Element element = tree != null ? tree.element( "discriminator-column" ) : null;
+ if ( element != null ) {
+ AnnotationDescriptor ad = new AnnotationDescriptor( DiscriminatorColumn.class );
+ copyStringAttribute( ad, element, "name", false );
+ copyStringAttribute( ad, element, "column-definition", false );
+ String value = element.attributeValue( "discriminator-type" );
+ DiscriminatorType type = DiscriminatorType.STRING;
+ if ( value != null ) {
+ if ( "STRING".equals( value ) ) {
+ type = DiscriminatorType.STRING;
+ }
+ else if ( "CHAR".equals( value ) ) {
+ type = DiscriminatorType.CHAR;
+ }
+ else if ( "INTEGER".equals( value ) ) {
+ type = DiscriminatorType.INTEGER;
+ }
+ else {
+ throw new AnnotationException(
+ "Unknown DiscrimiatorType in XML: " + value + " (" + SCHEMA_VALIDATION + ")"
+ );
+ }
+ }
+ ad.setValue( "discriminatorType", type );
+ copyIntegerAttribute( ad, element, "length" );
+ return AnnotationFactory.create( ad );
+ }
+ else if ( defaults.canUseJavaAnnotations() ) {
+ return getJavaAnnotation( DiscriminatorColumn.class );
+ }
+ else {
+ return null;
+ }
+ }
+
+ private DiscriminatorValue getDiscriminatorValue(Element tree, XMLContext.Default defaults) {
+ Element element = tree != null ? tree.element( "discriminator-value" ) : null;
+ if ( element != null ) {
+ AnnotationDescriptor ad = new AnnotationDescriptor( DiscriminatorValue.class );
+ copyStringElement( element, ad, "value" );
+ return AnnotationFactory.create( ad );
+ }
+ else if ( defaults.canUseJavaAnnotations() ) {
+ return getJavaAnnotation( DiscriminatorValue.class );
+ }
+ else {
+ return null;
+ }
+ }
+
+ private Inheritance getInheritance(Element tree, XMLContext.Default defaults) {
+ Element element = tree != null ? tree.element( "inheritance" ) : null;
+ if ( element != null ) {
+ AnnotationDescriptor ad = new AnnotationDescriptor( Inheritance.class );
+ Attribute attr = element.attribute( "strategy" );
+ InheritanceType strategy = InheritanceType.SINGLE_TABLE;
+ if ( attr != null ) {
+ String value = attr.getValue();
+ if ( "SINGLE_TABLE".equals( value ) ) {
+ strategy = InheritanceType.SINGLE_TABLE;
+ }
+ else if ( "JOINED".equals( value ) ) {
+ strategy = InheritanceType.JOINED;
+ }
+ else if ( "TABLE_PER_CLASS".equals( value ) ) {
+ strategy = InheritanceType.TABLE_PER_CLASS;
+ }
+ else {
+ throw new AnnotationException(
+ "Unknown InheritanceType in XML: " + value + " (" + SCHEMA_VALIDATION + ")"
+ );
+ }
+ }
+ ad.setValue( "strategy", strategy );
+ return AnnotationFactory.create( ad );
+ }
+ else if ( defaults.canUseJavaAnnotations() ) {
+ return getJavaAnnotation( Inheritance.class );
+ }
+ else {
+ return null;
+ }
+ }
+
+ private IdClass getIdClass(Element tree, XMLContext.Default defaults) {
+ Element element = tree == null ? null : tree.element( "id-class" );
+ if ( element != null ) {
+ Attribute attr = element.attribute( "class" );
+ if ( attr != null ) {
+ AnnotationDescriptor ad = new AnnotationDescriptor( IdClass.class );
+ Class clazz = null;
+ try {
+ clazz = ReflectHelper.classForName(
+ XMLContext.buildSafeClassName( attr.getValue(), defaults ),
+ this.getClass()
+ );
+ }
+ catch (ClassNotFoundException e) {
+ throw new AnnotationException( "Unable to find id-class: " + attr.getValue(), e );
+ }
+ ad.setValue( "value", clazz );
+ return AnnotationFactory.create( ad );
+ }
+ else {
+ throw new AnnotationException( "id-class without class. " + SCHEMA_VALIDATION );
+ }
+ }
+ else if ( defaults.canUseJavaAnnotations() ) {
+ return getJavaAnnotation( IdClass.class );
+ }
+ else {
+ return null;
+ }
+ }
+
+ private PrimaryKeyJoinColumns getPrimaryKeyJoinColumns(Element element, XMLContext.Default defaults) {
+ PrimaryKeyJoinColumn[] columns = buildPrimaryKeyJoinColumns( element );
+ if ( columns.length == 0 && defaults.canUseJavaAnnotations() ) {
+ PrimaryKeyJoinColumn annotation = getJavaAnnotation( PrimaryKeyJoinColumn.class );
+ if ( annotation != null ) {
+ columns = new PrimaryKeyJoinColumn[] { annotation };
+ }
+ else {
+ PrimaryKeyJoinColumns annotations = getJavaAnnotation( PrimaryKeyJoinColumns.class );
+ columns = annotations != null ? annotations.value() : columns;
+ }
+ }
+ if ( columns.length > 0 ) {
+ AnnotationDescriptor ad = new AnnotationDescriptor( PrimaryKeyJoinColumns.class );
+ ad.setValue( "value", columns );
+ return AnnotationFactory.create( ad );
+ }
+ else {
+ return null;
+ }
+ }
+
+ private Entity getEntity(Element tree, XMLContext.Default defaults) {
+ if ( tree == null ) {
+ return defaults.canUseJavaAnnotations() ? getJavaAnnotation( Entity.class ) : null;
+ }
+ else {
+ if ( "entity".equals( tree.getName() ) ) {
+ AnnotationDescriptor entity = new AnnotationDescriptor( Entity.class );
+ copyStringAttribute( entity, tree, "name", false );
+ if ( defaults.canUseJavaAnnotations()
+ && StringHelper.isEmpty( (String) entity.valueOf( "name" ) ) ) {
+ Entity javaAnn = getJavaAnnotation( Entity.class );
+ if ( javaAnn != null ) entity.setValue( "name", javaAnn.name() );
+ }
+ return AnnotationFactory.create( entity );
+ }
+ else {
+ return null; //this is not an entity
+ }
+ }
+ }
+
+ private MappedSuperclass getMappedSuperclass(Element tree, XMLContext.Default defaults) {
+ if ( tree == null ) {
+ return defaults.canUseJavaAnnotations() ? getJavaAnnotation( MappedSuperclass.class ) : null;
+ }
+ else {
+ if ( "mapped-superclass".equals( tree.getName() ) ) {
+ AnnotationDescriptor entity = new AnnotationDescriptor( MappedSuperclass.class );
+ return AnnotationFactory.create( entity );
+ }
+ else {
+ return null; //this is not an entity
+ }
+ }
+ }
+
+ private Embeddable getEmbeddable(Element tree, XMLContext.Default defaults) {
+ if ( tree == null ) {
+ return defaults.canUseJavaAnnotations() ? getJavaAnnotation( Embeddable.class ) : null;
+ }
+ else {
+ if ( "embeddable".equals( tree.getName() ) ) {
+ AnnotationDescriptor entity = new AnnotationDescriptor( Embeddable.class );
+ return AnnotationFactory.create( entity );
+ }
+ else {
+ return null; //this is not an entity
+ }
+ }
+ }
+
+ private Table getTable(Element tree, XMLContext.Default defaults) {
+ Element subelement = tree == null ? null : tree.element( "table" );
+ if ( subelement == null ) {
+ //no element but might have some default or some annotation
+ if ( StringHelper.isNotEmpty( defaults.getCatalog() )
+ || StringHelper.isNotEmpty( defaults.getSchema() ) ) {
+ AnnotationDescriptor annotation = new AnnotationDescriptor( Table.class );
+ if ( defaults.canUseJavaAnnotations() ) {
+ Table table = getJavaAnnotation( Table.class );
+ if ( table != null ) {
+ annotation.setValue( "name", table.name() );
+ annotation.setValue( "schema", table.schema() );
+ annotation.setValue( "catalog", table.catalog() );
+ annotation.setValue( "uniqueConstraints", table.uniqueConstraints() );
+ }
+ }
+ if ( StringHelper.isEmpty( (String) annotation.valueOf( "schema" ) )
+ && StringHelper.isNotEmpty( defaults.getSchema() ) ) {
+ annotation.setValue( "schema", defaults.getSchema() );
+ }
+ if ( StringHelper.isEmpty( (String) annotation.valueOf( "catalog" ) )
+ && StringHelper.isNotEmpty( defaults.getCatalog() ) ) {
+ annotation.setValue( "catalog", defaults.getCatalog() );
+ }
+ return AnnotationFactory.create( annotation );
+ }
+ else if ( defaults.canUseJavaAnnotations() ) {
+ return getJavaAnnotation( Table.class );
+ }
+ else {
+ return null;
+ }
+ }
+ else {
+ //ignore java annotation, an element is defined
+ AnnotationDescriptor annotation = new AnnotationDescriptor( Table.class );
+ copyStringAttribute( annotation, subelement, "name", false );
+ copyStringAttribute( annotation, subelement, "catalog", false );
+ if ( StringHelper.isNotEmpty( defaults.getCatalog() )
+ && StringHelper.isEmpty( (String) annotation.valueOf( "catalog" ) ) ) {
+ annotation.setValue( "catalog", defaults.getCatalog() );
+ }
+ copyStringAttribute( annotation, subelement, "schema", false );
+ if ( StringHelper.isNotEmpty( defaults.getSchema() )
+ && StringHelper.isEmpty( (String) annotation.valueOf( "schema" ) ) ) {
+ annotation.setValue( "schema", defaults.getSchema() );
+ }
+ buildUniqueConstraints( annotation, subelement );
+ return AnnotationFactory.create( annotation );
+ }
+ }
+
+ private SecondaryTables getSecondaryTables(Element tree, XMLContext.Default defaults) {
+ List<Element> elements = tree == null ?
+ new ArrayList<Element>() :
+ (List<Element>) tree.elements( "secondary-table" );
+ List<SecondaryTable> secondaryTables = new ArrayList<SecondaryTable>( 3 );
+ for (Element element : elements) {
+ AnnotationDescriptor annotation = new AnnotationDescriptor( SecondaryTable.class );
+ copyStringAttribute( annotation, element, "name", false );
+ copyStringAttribute( annotation, element, "catalog", false );
+ if ( StringHelper.isNotEmpty( defaults.getCatalog() )
+ && StringHelper.isEmpty( (String) annotation.valueOf( "catalog" ) ) ) {
+ annotation.setValue( "catalog", defaults.getCatalog() );
+ }
+ copyStringAttribute( annotation, element, "schema", false );
+ if ( StringHelper.isNotEmpty( defaults.getSchema() )
+ && StringHelper.isEmpty( (String) annotation.valueOf( "schema" ) ) ) {
+ annotation.setValue( "schema", defaults.getSchema() );
+ }
+ buildUniqueConstraints( annotation, element );
+ annotation.setValue( "pkJoinColumns", buildPrimaryKeyJoinColumns( element ) );
+ secondaryTables.add( (SecondaryTable) AnnotationFactory.create( annotation ) );
+ }
+ /*
+ * You can't have both secondary table in XML and Java,
+ * since there would be no way to "remove" a secondary table
+ */
+ if ( secondaryTables.size() == 0 && defaults.canUseJavaAnnotations() ) {
+ SecondaryTable secTableAnn = getJavaAnnotation( SecondaryTable.class );
+ overridesDefaultInSecondaryTable( secTableAnn, defaults, secondaryTables );
+ SecondaryTables secTablesAnn = getJavaAnnotation( SecondaryTables.class );
+ if ( secTablesAnn != null ) {
+ for (SecondaryTable table : secTablesAnn.value()) {
+ overridesDefaultInSecondaryTable( table, defaults, secondaryTables );
+ }
+ }
+ }
+ if ( secondaryTables.size() > 0 ) {
+ AnnotationDescriptor descriptor = new AnnotationDescriptor( SecondaryTables.class );
+ descriptor.setValue( "value", secondaryTables.toArray( new SecondaryTable[secondaryTables.size()] ) );
+ return AnnotationFactory.create( descriptor );
+ }
+ else {
+ return null;
+ }
+ }
+
+ private void overridesDefaultInSecondaryTable(
+ SecondaryTable secTableAnn, XMLContext.Default defaults, List<SecondaryTable> secondaryTables
+ ) {
+ if ( secTableAnn != null ) {
+ //handle default values
+ if ( StringHelper.isNotEmpty( defaults.getCatalog() )
+ || StringHelper.isNotEmpty( defaults.getSchema() ) ) {
+ AnnotationDescriptor annotation = new AnnotationDescriptor( SecondaryTable.class );
+ annotation.setValue( "name", secTableAnn.name() );
+ annotation.setValue( "schema", secTableAnn.schema() );
+ annotation.setValue( "catalog", secTableAnn.catalog() );
+ annotation.setValue( "uniqueConstraints", secTableAnn.uniqueConstraints() );
+ annotation.setValue( "pkJoinColumns", secTableAnn.pkJoinColumns() );
+ if ( StringHelper.isEmpty( (String) annotation.valueOf( "schema" ) )
+ && StringHelper.isNotEmpty( defaults.getSchema() ) ) {
+ annotation.setValue( "schema", defaults.getSchema() );
+ }
+ if ( StringHelper.isEmpty( (String) annotation.valueOf( "catalog" ) )
+ && StringHelper.isNotEmpty( defaults.getCatalog() ) ) {
+ annotation.setValue( "catalog", defaults.getCatalog() );
+ }
+ secondaryTables.add( (SecondaryTable) AnnotationFactory.create( annotation ) );
+ }
+ else {
+ secondaryTables.add( secTableAnn );
+ }
+ }
+ }
+
+ private static void buildUniqueConstraints(AnnotationDescriptor annotation, Element element) {
+ List uniqueConstraintElementList = element.elements( "unique-constraint" );
+ UniqueConstraint[] uniqueConstraints = new UniqueConstraint[uniqueConstraintElementList.size()];
+ int ucIndex = 0;
+ Iterator ucIt = uniqueConstraintElementList.listIterator();
+ while ( ucIt.hasNext() ) {
+ Element subelement = (Element) ucIt.next();
+ List<Element> columnNamesElements = subelement.elements( "column-name" );
+ String[] columnNames = new String[columnNamesElements.size()];
+ int columnNameIndex = 0;
+ Iterator it = columnNamesElements.listIterator();
+ while ( it.hasNext() ) {
+ Element columnNameElt = (Element) it.next();
+ columnNames[columnNameIndex++] = columnNameElt.getTextTrim();
+ }
+ AnnotationDescriptor ucAnn = new AnnotationDescriptor( UniqueConstraint.class );
+ ucAnn.setValue( "columnNames", columnNames );
+ uniqueConstraints[ucIndex++] = AnnotationFactory.create( ucAnn );
+ }
+ annotation.setValue( "uniqueConstraints", uniqueConstraints );
+ }
+
+ private PrimaryKeyJoinColumn[] buildPrimaryKeyJoinColumns(Element element) {
+ if ( element == null ) return new PrimaryKeyJoinColumn[] { };
+ List pkJoinColumnElementList = element.elements( "primary-key-join-column" );
+ PrimaryKeyJoinColumn[] pkJoinColumns = new PrimaryKeyJoinColumn[pkJoinColumnElementList.size()];
+ int index = 0;
+ Iterator pkIt = pkJoinColumnElementList.listIterator();
+ while ( pkIt.hasNext() ) {
+ Element subelement = (Element) pkIt.next();
+ AnnotationDescriptor pkAnn = new AnnotationDescriptor( PrimaryKeyJoinColumn.class );
+ copyStringAttribute( pkAnn, subelement, "name", false );
+ copyStringAttribute( pkAnn, subelement, "referenced-column-name", false );
+ copyStringAttribute( pkAnn, subelement, "column-definition", false );
+ pkJoinColumns[index++] = AnnotationFactory.create( pkAnn );
+ }
+ return pkJoinColumns;
+ }
+
+ private static void copyStringAttribute(
+ AnnotationDescriptor annotation, Element element, String attributeName, boolean mandatory
+ ) {
+ String attribute = element.attributeValue( attributeName );
+ if ( attribute != null ) {
+ String annotationAttributeName = getJavaAttributeNameFromXMLOne( attributeName );
+ annotation.setValue( annotationAttributeName, attribute );
+ }
+ else {
+ if ( mandatory ) {
+ throw new AnnotationException(
+ element.getName() + "." + attributeName + " is mandatory in XML overring. " + SCHEMA_VALIDATION
+ );
+ }
+ }
+ }
+
+ private static void copyIntegerAttribute(AnnotationDescriptor annotation, Element element, String attributeName) {
+ String attribute = element.attributeValue( attributeName );
+ if ( attribute != null ) {
+ String annotationAttributeName = getJavaAttributeNameFromXMLOne( attributeName );
+ annotation.setValue( annotationAttributeName, attribute );
+ try {
+ int length = Integer.parseInt( attribute );
+ annotation.setValue( annotationAttributeName, length );
+ }
+ catch (NumberFormatException e) {
+ throw new AnnotationException(
+ element.getPath() + attributeName + " not parseable: " + attribute + " (" + SCHEMA_VALIDATION + ")"
+ );
+ }
+ }
+ }
+
+ private static String getJavaAttributeNameFromXMLOne(String attributeName) {
+ StringBuilder annotationAttributeName = new StringBuilder( attributeName );
+ int index = annotationAttributeName.indexOf( WORD_SEPARATOR );
+ while ( index != -1 ) {
+ annotationAttributeName.deleteCharAt( index );
+ annotationAttributeName.setCharAt(
+ index, Character.toUpperCase( annotationAttributeName.charAt( index ) )
+ );
+ index = annotationAttributeName.indexOf( WORD_SEPARATOR );
+ }
+ return annotationAttributeName.toString();
+ }
+
+ private static void copyStringElement(Element element, AnnotationDescriptor ad, String annotationAttribute) {
+ String discr = element.getTextTrim();
+ ad.setValue( annotationAttribute, discr );
+ }
+
+ private static void copyBooleanAttribute(AnnotationDescriptor descriptor, Element element, String attribute) {
+ String attributeValue = element.attributeValue( attribute );
+ if ( StringHelper.isNotEmpty( attributeValue ) ) {
+ String javaAttribute = getJavaAttributeNameFromXMLOne( attribute );
+ descriptor.setValue( javaAttribute, Boolean.parseBoolean( attributeValue ) );
+ }
+ }
+
+ private <T extends Annotation> T getJavaAnnotation(Class<T> annotationType) {
+ return element.getAnnotation( annotationType );
+ }
+
+ private <T extends Annotation> boolean isJavaAnnotationPresent(Class<T> annotationType) {
+ return element.isAnnotationPresent( annotationType );
+ }
+
+ private Annotation[] getJavaAnnotations() {
+ return element.getAnnotations();
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/reflection/EJB3ReflectionManager.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/reflection/EJB3ReflectionManager.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/reflection/EJB3ReflectionManager.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,101 @@
+package org.hibernate.cfg.annotations.reflection;
+
+import java.lang.reflect.AnnotatedElement;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import javax.persistence.EntityListeners;
+import javax.persistence.NamedNativeQuery;
+import javax.persistence.NamedQuery;
+import javax.persistence.SequenceGenerator;
+import javax.persistence.SqlResultSetMapping;
+import javax.persistence.TableGenerator;
+
+import org.dom4j.Element;
+import org.hibernate.annotations.common.reflection.AnnotationReader;
+import org.hibernate.annotations.common.reflection.java.JavaReflectionManager;
+import org.hibernate.util.ReflectHelper;
+
+public class EJB3ReflectionManager extends JavaReflectionManager {
+
+ private XMLContext xmlContext = new XMLContext();
+ private HashMap defaults = null;
+
+ public AnnotationReader buildAnnotationReader(AnnotatedElement annotatedElement) {
+ if ( xmlContext.hasContext() ) {
+ return new EJB3OverridenAnnotationReader( annotatedElement, xmlContext );
+ }
+ else {
+ return super.buildAnnotationReader( annotatedElement );
+ }
+ }
+
+ public Map getDefaults() {
+ if ( defaults == null ) {
+ defaults = new HashMap();
+ XMLContext.Default xmlDefaults = xmlContext.getDefault( null );
+ List<Class> entityListeners = new ArrayList<Class>();
+ for (String className : xmlContext.getDefaultEntityListeners()) {
+ try {
+ entityListeners.add( ReflectHelper.classForName( className, this.getClass() ) );
+ }
+ catch (ClassNotFoundException e) {
+ throw new IllegalStateException( "Default entity listener class not found: " + className );
+ }
+ }
+ defaults.put( EntityListeners.class, entityListeners );
+ for (Element element : xmlContext.getAllDocuments()) {
+
+ List<Element> elements = element.elements( "sequence-generator" );
+ List<SequenceGenerator> sequenceGenerators = (List<SequenceGenerator>) defaults.get( SequenceGenerator.class );
+ if ( sequenceGenerators == null ) {
+ sequenceGenerators = new ArrayList<SequenceGenerator>();
+ defaults.put( SequenceGenerator.class, sequenceGenerators );
+ }
+ for (Element subelement : elements) {
+ sequenceGenerators.add( EJB3OverridenAnnotationReader.buildSequenceGeneratorAnnotation( subelement ) );
+ }
+
+ elements = element.elements( "table-generator" );
+ List<TableGenerator> tableGenerators = (List<TableGenerator>) defaults.get( TableGenerator.class );
+ if ( tableGenerators == null ) {
+ tableGenerators = new ArrayList<TableGenerator>();
+ defaults.put( TableGenerator.class, tableGenerators );
+ }
+ for (Element subelement : elements) {
+ tableGenerators.add( EJB3OverridenAnnotationReader.buildTableGeneratorAnnotation( subelement, xmlDefaults ) );
+ }
+
+ List<NamedQuery> namedQueries = (List<NamedQuery>) defaults.get( NamedQuery.class );
+ if ( namedQueries == null ) {
+ namedQueries = new ArrayList<NamedQuery>();
+ defaults.put( NamedQuery.class, namedQueries );
+ }
+ List<NamedQuery> currentNamedQueries = EJB3OverridenAnnotationReader.buildNamedQueries( element, false, xmlDefaults );
+ namedQueries.addAll( currentNamedQueries );
+
+ List<NamedNativeQuery> namedNativeQueries = (List<NamedNativeQuery>) defaults.get( NamedNativeQuery.class );
+ if ( namedNativeQueries == null ) {
+ namedNativeQueries = new ArrayList<NamedNativeQuery>();
+ defaults.put( NamedNativeQuery.class, namedNativeQueries );
+ }
+ List<NamedNativeQuery> currentNamedNativeQueries = EJB3OverridenAnnotationReader.buildNamedQueries( element, true, xmlDefaults );
+ namedNativeQueries.addAll( currentNamedNativeQueries );
+
+ List<SqlResultSetMapping> sqlResultSetMappings = (List<SqlResultSetMapping>) defaults.get( SqlResultSetMapping.class );
+ if ( sqlResultSetMappings == null ) {
+ sqlResultSetMappings = new ArrayList<SqlResultSetMapping>();
+ defaults.put( SqlResultSetMapping.class, sqlResultSetMappings );
+ }
+ List<SqlResultSetMapping> currentSqlResultSetMappings = EJB3OverridenAnnotationReader.buildSqlResultsetMappings( element, xmlDefaults );
+ sqlResultSetMappings.addAll( currentSqlResultSetMappings );
+ }
+ }
+ return defaults;
+ }
+
+ public XMLContext getXMLContext() {
+ return xmlContext;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/reflection/XMLContext.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/reflection/XMLContext.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/annotations/reflection/XMLContext.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,255 @@
+//$Id: XMLContext.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.cfg.annotations.reflection;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.dom4j.Document;
+import org.dom4j.Element;
+import org.hibernate.util.StringHelper;
+import org.slf4j.LoggerFactory;
+import org.slf4j.Logger;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class XMLContext {
+ private Logger log = LoggerFactory.getLogger( XMLContext.class );
+ private Default globalDefaults;
+ private Map<String, Element> classOverriding = new HashMap<String, Element>();
+ private Map<String, Default> defaultsOverriding = new HashMap<String, Default>();
+ private List<Element> defaultElements = new ArrayList<Element>();
+ private List<String> defaultEntityListeners = new ArrayList<String>();
+ private boolean hasContext = false;
+
+ /**
+ * Add a document and return the list of added classes names
+ */
+ public List<String> addDocument(Document doc) {
+ hasContext = true;
+ List<String> addedClasses = new ArrayList<String>();
+ Element root = doc.getRootElement();
+ //global defaults
+ Element metadata = root.element( "persistence-unit-metadata" );
+ if ( metadata != null ) {
+ if ( globalDefaults == null ) {
+ globalDefaults = new Default();
+ globalDefaults.setMetadataComplete(
+ metadata.element( "xml-mapping-metadata-complete" ) != null ?
+ Boolean.TRUE :
+ null
+ );
+ Element defaultElement = metadata.element( "persistence-unit-defaults" );
+ if ( defaultElement != null ) {
+ Element unitElement = defaultElement.element( "schema" );
+ globalDefaults.setSchema( unitElement != null ? unitElement.getTextTrim() : null );
+ unitElement = defaultElement.element( "catalog" );
+ globalDefaults.setCatalog( unitElement != null ? unitElement.getTextTrim() : null );
+ unitElement = defaultElement.element( "access" );
+ globalDefaults.setAccess( unitElement != null ? unitElement.getTextTrim() : null );
+ unitElement = defaultElement.element( "cascade-persist" );
+ globalDefaults.setCascadePersist( unitElement != null ? Boolean.TRUE : null );
+ defaultEntityListeners.addAll( addEntityListenerClasses( defaultElement, null, addedClasses ) );
+ }
+ }
+ else {
+ log.warn( "Found more than one <persistence-unit-metadata>, subsequent ignored" );
+ }
+ }
+
+ //entity mapping default
+ Default entityMappingDefault = new Default();
+ Element unitElement = root.element( "package" );
+ String packageName = unitElement != null ? unitElement.getTextTrim() : null;
+ entityMappingDefault.setPackageName( packageName );
+ unitElement = root.element( "schema" );
+ entityMappingDefault.setSchema( unitElement != null ? unitElement.getTextTrim() : null );
+ unitElement = root.element( "catalog" );
+ entityMappingDefault.setCatalog( unitElement != null ? unitElement.getTextTrim() : null );
+ unitElement = root.element( "access" );
+ entityMappingDefault.setAccess( unitElement != null ? unitElement.getTextTrim() : null );
+ defaultElements.add( root );
+
+ List<Element> entities = (List<Element>) root.elements( "entity" );
+ addClass( entities, packageName, entityMappingDefault, addedClasses );
+
+ entities = (List<Element>) root.elements( "mapped-superclass" );
+ addClass( entities, packageName, entityMappingDefault, addedClasses );
+
+ entities = (List<Element>) root.elements( "embeddable" );
+ addClass( entities, packageName, entityMappingDefault, addedClasses );
+ return addedClasses;
+ }
+
+ private void addClass(List<Element> entities, String packageName, Default defaults, List<String> addedClasses) {
+ for (Element element : entities) {
+ String className = buildSafeClassName( element.attributeValue( "class" ), packageName );
+ if ( classOverriding.containsKey( className ) ) {
+ //maybe switch it to warn?
+ throw new IllegalStateException( "Duplicate XML entry for " + className );
+ }
+ addedClasses.add( className );
+ classOverriding.put( className, element );
+ Default localDefault = new Default();
+ localDefault.override( defaults );
+ String metadataCompleteString = element.attributeValue( "metadata-complete" );
+ if ( metadataCompleteString != null ) {
+ localDefault.setMetadataComplete( Boolean.parseBoolean( metadataCompleteString ) );
+ }
+ String access = element.attributeValue( "access" );
+ if ( access != null ) localDefault.setAccess( access );
+ defaultsOverriding.put( className, localDefault );
+
+ log.debug( "Adding XML overriding information for {}", className );
+ addEntityListenerClasses( element, packageName, addedClasses );
+ }
+ }
+
+ private List<String> addEntityListenerClasses(Element element, String packageName, List<String> addedClasses) {
+ List<String> localAddedClasses = new ArrayList<String>();
+ Element listeners = element.element( "entity-listeners" );
+ if ( listeners != null ) {
+ List<Element> elements = (List<Element>) listeners.elements( "entity-listener" );
+ for (Element listener : elements) {
+ String listenerClassName = buildSafeClassName( listener.attributeValue( "class" ), packageName );
+ if ( classOverriding.containsKey( listenerClassName ) ) {
+ //maybe switch it to warn?
+ if ( "entity-listener".equals( classOverriding.get( listenerClassName ).getName() ) ) {
+ log.info(
+ "entity-listener duplication, first event definition will be used: {}",
+ listenerClassName
+ );
+ continue;
+ }
+ else {
+ throw new IllegalStateException( "Duplicate XML entry for " + listenerClassName );
+ }
+ }
+ localAddedClasses.add( listenerClassName );
+ classOverriding.put( listenerClassName, listener );
+ }
+ }
+ log.debug( "Adding XML overriding information for listener: {}", listeners );
+ addedClasses.addAll( localAddedClasses );
+ return localAddedClasses;
+ }
+
+ public static String buildSafeClassName(String className, String defaultPackageName) {
+ if ( className.indexOf( '.' ) < 0 && StringHelper.isNotEmpty( defaultPackageName ) ) {
+ className = StringHelper.qualify( defaultPackageName, className );
+ }
+ return className;
+ }
+
+ public static String buildSafeClassName(String className, XMLContext.Default defaults) {
+ return buildSafeClassName( className, defaults.getPackageName() );
+ }
+
+ public Default getDefault(String className) {
+ Default xmlDefault = new Default();
+ xmlDefault.override( globalDefaults );
+ if ( className != null ) {
+ Default entityMappingOverriding = defaultsOverriding.get( className );
+ xmlDefault.override( entityMappingOverriding );
+ }
+ return xmlDefault;
+ }
+
+ public Element getXMLTree(String className, String methodName) {
+ return classOverriding.get( className );
+ }
+
+ public List<Element> getAllDocuments() {
+ return defaultElements;
+ }
+
+ public boolean hasContext() {
+ return hasContext;
+ }
+
+ public static class Default {
+ private String access;
+ private String packageName;
+ private String schema;
+ private String catalog;
+ private Boolean metadataComplete;
+ private Boolean cascadePersist;
+
+ public String getAccess() {
+ return access;
+ }
+
+ protected void setAccess(String access) {
+ if ( "FIELD".equals( access ) || "PROPERTY".equals( access ) ) {
+ this.access = access.toLowerCase();
+ }
+ else {
+ this.access = access;
+ }
+ }
+
+ public String getCatalog() {
+ return catalog;
+ }
+
+ protected void setCatalog(String catalog) {
+ this.catalog = catalog;
+ }
+
+ public String getPackageName() {
+ return packageName;
+ }
+
+ protected void setPackageName(String packageName) {
+ this.packageName = packageName;
+ }
+
+ public String getSchema() {
+ return schema;
+ }
+
+ protected void setSchema(String schema) {
+ this.schema = schema;
+ }
+
+ public Boolean getMetadataComplete() {
+ return metadataComplete;
+ }
+
+ public boolean canUseJavaAnnotations() {
+ return metadataComplete == null || !metadataComplete.booleanValue();
+ }
+
+ protected void setMetadataComplete(Boolean metadataComplete) {
+ this.metadataComplete = metadataComplete;
+ }
+
+ public Boolean getCascadePersist() {
+ return cascadePersist;
+ }
+
+ void setCascadePersist(Boolean cascadePersist) {
+ this.cascadePersist = cascadePersist;
+ }
+
+ public void override(Default globalDefault) {
+ if ( globalDefault != null ) {
+ if ( globalDefault.getAccess() != null ) access = globalDefault.getAccess();
+ if ( globalDefault.getPackageName() != null ) packageName = globalDefault.getPackageName();
+ if ( globalDefault.getSchema() != null ) schema = globalDefault.getSchema();
+ if ( globalDefault.getCatalog() != null ) catalog = globalDefault.getCatalog();
+ if ( globalDefault.getMetadataComplete() != null ) {
+ metadataComplete = globalDefault.getMetadataComplete();
+ }
+ //TODO fix that in stone if cascade-persist is set already?
+ if ( globalDefault.getCascadePersist() != null ) cascadePersist = globalDefault.getCascadePersist();
+ }
+ }
+ }
+
+ public List<String> getDefaultEntityListeners() {
+ return defaultEntityListeners;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/search/HibernateSearchEventListenerRegister.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/search/HibernateSearchEventListenerRegister.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/cfg/search/HibernateSearchEventListenerRegister.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,224 @@
+// $Id: HibernateSearchEventListenerRegister.java 14991 2008-07-29 18:20:47Z epbernard $
+package org.hibernate.cfg.search;
+
+import java.util.Properties;
+
+import org.hibernate.AnnotationException;
+import org.hibernate.event.EventListeners;
+import org.hibernate.event.PostCollectionRecreateEventListener;
+import org.hibernate.event.PostCollectionRemoveEventListener;
+import org.hibernate.event.PostCollectionUpdateEventListener;
+import org.hibernate.event.PostDeleteEventListener;
+import org.hibernate.event.PostInsertEventListener;
+import org.hibernate.event.PostUpdateEventListener;
+import org.hibernate.util.ReflectHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Helper methods initializing Hibernate Search event listeners.
+ *
+ * @deprecated as of release 3.4.0.CR2, replaced by Hibernate Search's {@link org.hibernate.search.cfg.EventListenerRegister}
+ * @author Emmanuel Bernard
+ * @author Hardy Ferentschik
+ */
+@Deprecated
+public class HibernateSearchEventListenerRegister {
+
+ private static final Logger log = LoggerFactory.getLogger(HibernateSearchEventListenerRegister.class);
+
+ /**
+ * Class name of the class needed to enable Search.
+ */
+ private static final String FULL_TEXT_INDEX_EVENT_LISTENER_CLASS = "org.hibernate.search.event.FullTextIndexEventListener";
+
+ /**
+ * @deprecated as of release 3.4.0.CR2, replaced by Hibernate Search's {@link org.hibernate.search.cfg.EventListenerRegister#enableHibernateSearch(EventListeners, Properties)}
+ */
+ @SuppressWarnings("unchecked")
+ @Deprecated
+ public static void enableHibernateSearch(EventListeners eventListeners, Properties properties) {
+ // check whether search is explicitly enabled - if so there is nothing
+ // to do
+ String enableSearchListeners = properties.getProperty( "hibernate.search.autoregister_listeners" );
+ if("false".equalsIgnoreCase(enableSearchListeners )) {
+ log.info("Property hibernate.search.autoregister_listeners is set to false." +
+ " No attempt will be made to register Hibernate Search event listeners.");
+ return;
+ }
+
+ // add search events if the jar is available and class can be loaded
+ Class searchEventListenerClass = attemptToLoadSearchEventListener();
+ if ( searchEventListenerClass == null ) {
+ log.info("Unable to find {} on the classpath. Hibernate Search is not enabled.", FULL_TEXT_INDEX_EVENT_LISTENER_CLASS);
+ return;
+ }
+
+ Object searchEventListener = instantiateEventListener(searchEventListenerClass);
+
+ //TODO Generalize this. Pretty much the same code all the time. Reflecetion?
+ {
+ boolean present = false;
+ PostInsertEventListener[] listeners = eventListeners
+ .getPostInsertEventListeners();
+ if (listeners != null) {
+ for (Object eventListener : listeners) {
+ // not isAssignableFrom since the user could subclass
+ present = present
+ || searchEventListenerClass == eventListener
+ .getClass();
+ }
+ if (!present) {
+ int length = listeners.length + 1;
+ PostInsertEventListener[] newListeners = new PostInsertEventListener[length];
+ System.arraycopy(listeners, 0, newListeners, 0, length - 1);
+ newListeners[length - 1] = (PostInsertEventListener) searchEventListener;
+ eventListeners.setPostInsertEventListeners(newListeners);
+ }
+ } else {
+ eventListeners
+ .setPostInsertEventListeners(new PostInsertEventListener[] { (PostInsertEventListener) searchEventListener });
+ }
+ }
+ {
+ boolean present = false;
+ PostUpdateEventListener[] listeners = eventListeners
+ .getPostUpdateEventListeners();
+ if (listeners != null) {
+ for (Object eventListener : listeners) {
+ // not isAssignableFrom since the user could subclass
+ present = present
+ || searchEventListenerClass == eventListener
+ .getClass();
+ }
+ if (!present) {
+ int length = listeners.length + 1;
+ PostUpdateEventListener[] newListeners = new PostUpdateEventListener[length];
+ System.arraycopy(listeners, 0, newListeners, 0, length - 1);
+ newListeners[length - 1] = (PostUpdateEventListener) searchEventListener;
+ eventListeners.setPostUpdateEventListeners(newListeners);
+ }
+ } else {
+ eventListeners
+ .setPostUpdateEventListeners(new PostUpdateEventListener[] { (PostUpdateEventListener) searchEventListener });
+ }
+ }
+ {
+ boolean present = false;
+ PostDeleteEventListener[] listeners = eventListeners
+ .getPostDeleteEventListeners();
+ if (listeners != null) {
+ for (Object eventListener : listeners) {
+ // not isAssignableFrom since the user could subclass
+ present = present
+ || searchEventListenerClass == eventListener
+ .getClass();
+ }
+ if (!present) {
+ int length = listeners.length + 1;
+ PostDeleteEventListener[] newListeners = new PostDeleteEventListener[length];
+ System.arraycopy(listeners, 0, newListeners, 0, length - 1);
+ newListeners[length - 1] = (PostDeleteEventListener) searchEventListener;
+ eventListeners.setPostDeleteEventListeners(newListeners);
+ }
+ } else {
+ eventListeners
+ .setPostDeleteEventListeners(new PostDeleteEventListener[] { (PostDeleteEventListener) searchEventListener });
+ }
+ }
+ {
+ boolean present = false;
+ PostCollectionRecreateEventListener[] listeners = eventListeners.getPostCollectionRecreateEventListeners();
+ if ( listeners != null ) {
+ for (Object eventListener : listeners) {
+ //not isAssignableFrom since the user could subclass
+ present = present || searchEventListenerClass == eventListener.getClass();
+ }
+ if ( !present ) {
+ int length = listeners.length + 1;
+ PostCollectionRecreateEventListener[] newListeners = new PostCollectionRecreateEventListener[length];
+ System.arraycopy( listeners, 0, newListeners, 0, length - 1 );
+ newListeners[length - 1] = (PostCollectionRecreateEventListener) searchEventListener;
+ eventListeners.setPostCollectionRecreateEventListeners( newListeners );
+ }
+ }
+ else {
+ eventListeners.setPostCollectionRecreateEventListeners(
+ new PostCollectionRecreateEventListener[] { (PostCollectionRecreateEventListener) searchEventListener }
+ );
+ }
+ }
+ {
+ boolean present = false;
+ PostCollectionRemoveEventListener[] listeners = eventListeners.getPostCollectionRemoveEventListeners();
+ if ( listeners != null ) {
+ for (Object eventListener : listeners) {
+ //not isAssignableFrom since the user could subclass
+ present = present || searchEventListenerClass == eventListener.getClass();
+ }
+ if ( !present ) {
+ int length = listeners.length + 1;
+ PostCollectionRemoveEventListener[] newListeners = new PostCollectionRemoveEventListener[length];
+ System.arraycopy( listeners, 0, newListeners, 0, length - 1 );
+ newListeners[length - 1] = (PostCollectionRemoveEventListener) searchEventListener;
+ eventListeners.setPostCollectionRemoveEventListeners( newListeners );
+ }
+ }
+ else {
+ eventListeners.setPostCollectionRemoveEventListeners(
+ new PostCollectionRemoveEventListener[] { (PostCollectionRemoveEventListener) searchEventListener }
+ );
+ }
+ }
+ {
+ boolean present = false;
+ PostCollectionUpdateEventListener[] listeners = eventListeners.getPostCollectionUpdateEventListeners();
+ if ( listeners != null ) {
+ for (Object eventListener : listeners) {
+ //not isAssignableFrom since the user could subclass
+ present = present || searchEventListenerClass == eventListener.getClass();
+ }
+ if ( !present ) {
+ int length = listeners.length + 1;
+ PostCollectionUpdateEventListener[] newListeners = new PostCollectionUpdateEventListener[length];
+ System.arraycopy( listeners, 0, newListeners, 0, length - 1 );
+ newListeners[length - 1] = (PostCollectionUpdateEventListener) searchEventListener;
+ eventListeners.setPostCollectionUpdateEventListeners( newListeners );
+ }
+ }
+ else {
+ eventListeners.setPostCollectionUpdateEventListeners(
+ new PostCollectionUpdateEventListener[] { (PostCollectionUpdateEventListener) searchEventListener }
+ );
+ }
+ }
+ }
+
+ /**
+ * Tries to load Hibernate Search event listener.
+ *
+ * @return An event listener instance in case the jar was available.
+ */
+ private static Class<?> attemptToLoadSearchEventListener() {
+ Class searchEventListenerClass = null;
+ try {
+ searchEventListenerClass = ReflectHelper.classForName(
+ FULL_TEXT_INDEX_EVENT_LISTENER_CLASS,
+ HibernateSearchEventListenerRegister.class);
+ } catch (ClassNotFoundException e) {
+ log.debug("Search not present in classpath, ignoring event listener registration.");
+ }
+ return searchEventListenerClass;
+ }
+
+ private static Object instantiateEventListener(Class<?> clazz) {
+ Object searchEventListener;
+ try {
+ searchEventListener = clazz.newInstance();
+ } catch (Exception e) {
+ throw new AnnotationException(
+ "Unable to load Search event listener", e);
+ }
+ return searchEventListener;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/mapping/IdGenerator.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/mapping/IdGenerator.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/mapping/IdGenerator.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,52 @@
+//$Id: IdGenerator.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.mapping;
+
+import java.io.Serializable;
+import java.util.Properties;
+
+/**
+ * Identifier generator container,
+ * Useful to keep named generator in annotations
+ *
+ * @author Emmanuel Bernard
+ */
+public class IdGenerator implements Serializable {
+ private String name;
+ private String identifierGeneratorStrategy;
+ private Properties params = new Properties();
+
+
+ /**
+ * @return identifier generator strategy
+ */
+ public String getIdentifierGeneratorStrategy() {
+ return identifierGeneratorStrategy;
+ }
+
+ /**
+ * @return generator name
+ */
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * @return generator configuration parameters
+ */
+ public Properties getParams() {
+ return params;
+ }
+
+ public void setIdentifierGeneratorStrategy(String string) {
+ identifierGeneratorStrategy = string;
+ }
+
+ public void setName(String string) {
+ name = string;
+ }
+
+ public void addParam(String key, String value) {
+ params.setProperty( key, value );
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/type/AbstractLobType.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/type/AbstractLobType.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/type/AbstractLobType.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,67 @@
+//$Id: AbstractLobType.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.type;
+
+import java.io.Serializable;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+
+import org.hibernate.EntityMode;
+import org.hibernate.HibernateException;
+import org.hibernate.MappingException;
+import org.hibernate.engine.Mapping;
+import org.hibernate.engine.SessionImplementor;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public abstract class AbstractLobType extends AbstractType implements Serializable {
+ public boolean isDirty(Object old, Object current, boolean[] checkable, SessionImplementor session)
+ throws HibernateException {
+ return checkable[0] ? ! isEqual( old, current, session.getEntityMode() ) : false;
+ }
+
+ @Override
+ public boolean isEqual(Object x, Object y, EntityMode entityMode) {
+ return isEqual( x, y, entityMode, null );
+ }
+
+ @Override
+ public int getHashCode(Object x, EntityMode entityMode) {
+ return getHashCode( x, entityMode, null );
+ }
+
+ public String getName() {
+ return this.getClass().getName();
+ }
+
+ public int getColumnSpan(Mapping mapping) throws MappingException {
+ return 1;
+ }
+
+ protected abstract Object get(ResultSet rs, String name) throws SQLException;
+
+ public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner)
+ throws HibernateException, SQLException {
+ return get( rs, names[0] );
+ }
+
+ public Object nullSafeGet(ResultSet rs, String name, SessionImplementor session, Object owner)
+ throws HibernateException, SQLException {
+ return get( rs, name );
+ }
+
+ public void nullSafeSet(
+ PreparedStatement st, Object value, int index, boolean[] settable, SessionImplementor session
+ ) throws HibernateException, SQLException {
+ if ( settable[0] ) set( st, value, index, session );
+ }
+
+ protected abstract void set(PreparedStatement st, Object value, int index, SessionImplementor session)
+ throws SQLException;
+
+ public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session)
+ throws HibernateException, SQLException {
+ set( st, value, index, session );
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/type/ByteArrayBlobType.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/type/ByteArrayBlobType.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/type/ByteArrayBlobType.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,195 @@
+//$Id: ByteArrayBlobType.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.type;
+
+import java.io.ByteArrayInputStream;
+import java.sql.Blob;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Types;
+import java.util.Map;
+
+import org.dom4j.Node;
+import org.hibernate.EntityMode;
+import org.hibernate.HibernateException;
+import org.hibernate.MappingException;
+import org.hibernate.engine.Mapping;
+import org.hibernate.engine.SessionFactoryImplementor;
+import org.hibernate.engine.SessionImplementor;
+import org.hibernate.lob.BlobImpl;
+import org.hibernate.util.ArrayHelper;
+
+/**
+ * Map a Byte[] into a Blob
+ * Experimental
+ *
+ * @author Emmanuel Bernard
+ */
+public class ByteArrayBlobType extends AbstractLobType {
+
+ public int[] sqlTypes(Mapping mapping) throws MappingException {
+ return new int[]{Types.BLOB};
+ }
+
+ @Override
+ public boolean isEqual(Object x, Object y, EntityMode entityMode, SessionFactoryImplementor factory) {
+ if ( x == y ) return true;
+ if ( x == null || y == null ) return false;
+ if ( x instanceof Byte[] ) {
+ Object[] o1 = (Object[]) x;
+ Object[] o2 = (Object[]) y;
+ return ArrayHelper.isEquals( o1, o2 );
+ }
+ else {
+ byte[] c1 = (byte[]) x;
+ byte[] c2 = (byte[]) y;
+ return ArrayHelper.isEquals( c1, c2 );
+ }
+ }
+
+ public int getHashCode(Object x, EntityMode entityMode, SessionFactoryImplementor factory) {
+ if ( x instanceof Character[] ) {
+ Object[] o = (Object[]) x;
+ return ArrayHelper.hash( o );
+ }
+ else {
+ byte[] c = (byte[]) x;
+ return ArrayHelper.hash( c );
+ }
+ }
+
+ public Object deepCopy(Object value, EntityMode entityMode, SessionFactoryImplementor factory)
+ throws HibernateException {
+ if ( value == null ) return null;
+ if ( value instanceof Byte[] ) {
+ Byte[] array = (Byte[]) value;
+ int length = array.length;
+ Byte[] copy = new Byte[length];
+ for ( int index = 0; index < length ; index++ ) {
+ copy[index] = Byte.valueOf( array[index].byteValue() );
+ }
+ return copy;
+ }
+ else {
+ byte[] array = (byte[]) value;
+ int length = array.length;
+ byte[] copy = new byte[length];
+ System.arraycopy( array, 0, copy, 0, length );
+ return copy;
+ }
+ }
+
+ public Class getReturnedClass() {
+ return Byte[].class;
+ }
+
+ protected Object get(ResultSet rs, String name) throws SQLException {
+ Blob blob = rs.getBlob( name );
+ if ( rs.wasNull() ) return null;
+ int length = (int) blob.length();
+ byte[] primaryResult = blob.getBytes( 1, length );
+ return wrap( primaryResult );
+ }
+
+ protected void set(PreparedStatement st, Object value, int index, SessionImplementor session) throws SQLException {
+ if ( value == null ) {
+ st.setNull( index, sqlTypes( null )[0] );
+ }
+ else {
+ byte[] toSet = unWrap( value );
+ final boolean useInputStream = session.getFactory().getDialect().useInputStreamToInsertBlob();
+
+ if ( useInputStream ) {
+ st.setBinaryStream( index, new ByteArrayInputStream( toSet ), toSet.length );
+ }
+ else {
+ st.setBlob( index, new BlobImpl( toSet ) );
+ }
+ }
+ }
+
+ public void setToXMLNode(Node node, Object value, SessionFactoryImplementor factory) throws HibernateException {
+ node.setText( toString( value ) );
+ }
+
+ public String toString(Object val) {
+ byte[] bytes = unWrap( val );
+ StringBuilder buf = new StringBuilder( 2 * bytes.length );
+ for ( int i = 0; i < bytes.length ; i++ ) {
+ String hexStr = Integer.toHexString( bytes[i] - Byte.MIN_VALUE );
+ if ( hexStr.length() == 1 ) buf.append( '0' );
+ buf.append( hexStr );
+ }
+ return buf.toString();
+ }
+
+ public String toLoggableString(Object value, SessionFactoryImplementor factory) {
+ return value == null ? "null" : toString( value );
+ }
+
+ public Object fromXMLNode(Node xml, Mapping factory) throws HibernateException {
+ String xmlText = xml.getText();
+ return xmlText == null || xmlText.length() == 0 ? null : fromString( xmlText );
+ }
+
+ private Object fromString(String xmlText) {
+ if ( xmlText == null ) {
+ return null;
+ }
+ if ( xmlText.length() % 2 != 0 ) {
+ throw new IllegalArgumentException( "The string is not a valid xml representation of a binary content." );
+ }
+ byte[] bytes = new byte[xmlText.length() / 2];
+ for ( int i = 0; i < bytes.length ; i++ ) {
+ String hexStr = xmlText.substring( i * 2, ( i + 1 ) * 2 );
+ bytes[i] = (byte) ( Integer.parseInt( hexStr, 16 ) + Byte.MIN_VALUE );
+ }
+ return wrap( bytes );
+ }
+
+ protected Object wrap(byte[] bytes) {
+ return wrapPrimitive( bytes );
+ }
+
+ protected byte[] unWrap(Object bytes) {
+ return unwrapNonPrimitive( (Byte[]) bytes );
+ }
+
+ private byte[] unwrapNonPrimitive(Byte[] bytes) {
+ int length = bytes.length;
+ byte[] result = new byte[length];
+ for ( int i = 0; i < length ; i++ ) {
+ result[i] = bytes[i].byteValue();
+ }
+ return result;
+ }
+
+ private Byte[] wrapPrimitive(byte[] bytes) {
+ int length = bytes.length;
+ Byte[] result = new Byte[length];
+ for ( int index = 0; index < length ; index++ ) {
+ result[index] = Byte.valueOf( bytes[index] );
+ }
+ return result;
+ }
+
+ public boolean isMutable() {
+ return true;
+ }
+
+ public Object replace(
+ Object original,
+ Object target,
+ SessionImplementor session,
+ Object owner,
+ Map copyCache
+ )
+ throws HibernateException {
+ if ( isEqual( original, target, session.getEntityMode() ) ) return original;
+ return deepCopy( original, session.getEntityMode(), session.getFactory() );
+ }
+
+ public boolean[] toColumnNullness(Object value, Mapping mapping) {
+ return value == null ? ArrayHelper.FALSE : ArrayHelper.TRUE;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/type/CharacterArrayClobType.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/type/CharacterArrayClobType.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/type/CharacterArrayClobType.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,148 @@
+//$Id: CharacterArrayClobType.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.type;
+
+import java.io.CharArrayReader;
+import java.io.IOException;
+import java.io.Reader;
+import java.io.Serializable;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Types;
+import java.util.ArrayList;
+
+import org.hibernate.HibernateException;
+import org.hibernate.usertype.UserType;
+import org.hibernate.util.ArrayHelper;
+
+/**
+ * Map a Character[] to a Clob
+ * Experimental
+ *
+ * @author Emmanuel Bernard
+ */
+public class CharacterArrayClobType implements UserType, Serializable {
+ public static final int BUFFER_SIZE = 4096;
+
+ public int[] sqlTypes() {
+ return new int[]{Types.CLOB};
+ }
+
+ public Class returnedClass() {
+ return Character[].class;
+ }
+
+ public boolean equals(Object x, Object y) throws HibernateException {
+ if ( x == y ) return true;
+ if ( x == null || y == null ) return false;
+ if ( x instanceof Character[] ) {
+ Object[] o1 = (Object[]) x;
+ Object[] o2 = (Object[]) y;
+ return ArrayHelper.isEquals( o1, o2 );
+ }
+ else {
+ char[] c1 = (char[]) x;
+ char[] c2 = (char[]) y;
+ return ArrayHelper.isEquals( c1, c2 );
+ }
+ }
+
+ public int hashCode(Object x) throws HibernateException {
+ if ( x instanceof Character[] ) {
+ Object[] o = (Object[]) x;
+ return ArrayHelper.hash( o );
+ }
+ else {
+ char[] c = (char[]) x;
+ return ArrayHelper.hash( c );
+ }
+ }
+
+ public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
+ Reader reader = rs.getCharacterStream( names[0] );
+ if ( reader == null ) return null;
+ ArrayList result = new ArrayList();
+ try {
+ char[] charbuf = new char[BUFFER_SIZE];
+ for ( int i = reader.read( charbuf ); i > 0 ; i = reader.read( charbuf ) ) {
+ result.ensureCapacity( result.size() + BUFFER_SIZE );
+ for ( int charIndex = 0; charIndex < i ; charIndex++ ) {
+ result.add( Character.valueOf( charbuf[charIndex] ) );
+ }
+ }
+ }
+ catch (IOException e) {
+ throw new SQLException( e.getMessage() );
+ }
+ if ( returnedClass().equals( Character[].class ) ) {
+ return result.toArray( new Character[ result.size() ] );
+ }
+ else {
+ //very suboptimal
+ int length = result.size();
+ char[] chars = new char[length];
+ for ( int index = 0; index < length ; index++ ) {
+ chars[index] = ( (Character) result.get( index ) ).charValue();
+ }
+ return chars;
+ }
+ }
+
+ public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
+ if ( value != null ) {
+ char[] chars;
+ if ( value instanceof Character[] ) {
+ Character[] character = (Character[]) value;
+ int length = character.length;
+ chars = new char[length];
+ for ( int i = 0; i < length ; i++ ) {
+ chars[i] = character[i].charValue();
+ }
+ }
+ else {
+ chars = (char[]) value;
+ }
+ CharArrayReader reader = new CharArrayReader( chars );
+ st.setCharacterStream( index, reader, chars.length );
+ }
+ else {
+ st.setNull( index, sqlTypes()[0] );
+ }
+ }
+
+ public Object deepCopy(Object value) throws HibernateException {
+ if ( value == null ) return null;
+ if ( value instanceof Character[] ) {
+ Character[] array = (Character[]) value;
+ int length = array.length;
+ Character[] copy = new Character[length];
+ for ( int index = 0; index < length ; index++ ) {
+ copy[index] = Character.valueOf( array[index].charValue() );
+ }
+ return copy;
+ }
+ else {
+ char[] array = (char[]) value;
+ int length = array.length;
+ char[] copy = new char[length];
+ System.arraycopy( array, 0, copy, 0, length );
+ return copy;
+ }
+ }
+
+ public boolean isMutable() {
+ return true;
+ }
+
+ public Serializable disassemble(Object value) throws HibernateException {
+ return (Serializable) deepCopy( value );
+ }
+
+ public Object assemble(Serializable cached, Object owner) throws HibernateException {
+ return deepCopy( cached );
+ }
+
+ public Object replace(Object original, Object target, Object owner) throws HibernateException {
+ return deepCopy( original );
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/type/EnumType.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/type/EnumType.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/type/EnumType.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,269 @@
+//$Id: EnumType.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.type;
+
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.Serializable;
+import java.lang.reflect.Method;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Types;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+
+import org.hibernate.AssertionFailure;
+import org.hibernate.HibernateException;
+import org.hibernate.annotations.common.util.StringHelper;
+import org.hibernate.usertype.EnhancedUserType;
+import org.hibernate.usertype.ParameterizedType;
+import org.hibernate.util.ReflectHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Enum type mapper
+ * Try and find the appropriate SQL type depending on column metadata
+ *
+ * @author Emmanuel Bernard
+ */
+//TODO implements readobject/writeobject to recalculate the enumclasses
+public class EnumType implements EnhancedUserType, ParameterizedType, Serializable {
+ /**
+ * This is the old scheme where logging of parameter bindings and value extractions
+ * was controlled by the trace level enablement on the 'org.hibernate.type' package...
+ * <p/>
+ * Originally was cached such because of performance of looking up the logger each time
+ * in order to check the trace-enablement. Driving this via a central Log-specific class
+ * would alleviate that performance hit, and yet still allow more "normal" logging usage/config.
+ */
+ private static final boolean IS_VALUE_TRACING_ENABLED = LoggerFactory.getLogger( StringHelper.qualifier( Type.class.getName() ) ).isTraceEnabled();
+ private transient Logger log;
+
+ private Logger log() {
+ if ( log == null ) {
+ log = LoggerFactory.getLogger( getClass() );
+ }
+ return log;
+ }
+
+ public static final String ENUM = "enumClass";
+ public static final String SCHEMA = "schema";
+ public static final String CATALOG = "catalog";
+ public static final String TABLE = "table";
+ public static final String COLUMN = "column";
+ public static final String TYPE = "type";
+
+ private static Map<Class, Object[]> enumValues = new HashMap<Class, Object[]>();
+
+ private Class<? extends Enum> enumClass;
+ private String column;
+ private String table;
+ private String catalog;
+ private String schema;
+ private boolean guessed = false;
+ private int sqlType = Types.INTEGER; //before any guessing
+
+ public int[] sqlTypes() {
+ return new int[]{sqlType};
+ }
+
+ public Class returnedClass() {
+ return enumClass;
+ }
+
+ public boolean equals(Object x, Object y) throws HibernateException {
+ return x == y;
+ }
+
+ public int hashCode(Object x) throws HibernateException {
+ return x == null ? 0 : x.hashCode();
+ }
+
+ public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
+ Object object = rs.getObject( names[0] );
+ if ( rs.wasNull() ) {
+ if ( IS_VALUE_TRACING_ENABLED ) {
+ log().debug( "Returning null as column {}", names[0] );
+ }
+ return null;
+ }
+ if ( object instanceof Number ) {
+ Object[] values = enumValues.get( enumClass );
+ if ( values == null ) throw new AssertionFailure( "enumValues not preprocessed: " + enumClass );
+ int ordinal = ( (Number) object ).intValue();
+ if ( ordinal < 0 || ordinal >= values.length ) {
+ throw new IllegalArgumentException( "Unknown ordinal value for enum " + enumClass + ": " + ordinal );
+ }
+ if ( IS_VALUE_TRACING_ENABLED ) {
+ log().debug( "Returning '{}' as column {}", ordinal, names[0] );
+ }
+ return values[ordinal];
+ }
+ else {
+ String name = (String) object;
+ if ( IS_VALUE_TRACING_ENABLED ) {
+ log().debug( "Returning '{}' as column {}", name, names[0] );
+ }
+ try {
+ return Enum.valueOf( enumClass, name );
+ }
+ catch (IllegalArgumentException iae) {
+ throw new IllegalArgumentException( "Unknown name value for enum " + enumClass + ": " + name, iae );
+ }
+ }
+ }
+
+ public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
+ //if (!guessed) guessType( st, index );
+ if ( value == null ) {
+ if ( IS_VALUE_TRACING_ENABLED ) log().debug( "Binding null to parameter: {}", index );
+ st.setNull( index, sqlType );
+ }
+ else {
+ boolean isOrdinal = isOrdinal( sqlType );
+ if ( isOrdinal ) {
+ int ordinal = ( (Enum) value ).ordinal();
+ if ( IS_VALUE_TRACING_ENABLED ) {
+ log().debug( "Binding '{}' to parameter: {}", ordinal, index );
+ }
+ st.setObject( index, Integer.valueOf( ordinal ), sqlType );
+ }
+ else {
+ String enumString = ( (Enum) value ).name();
+ if ( IS_VALUE_TRACING_ENABLED ) {
+ log().debug( "Binding '{}' to parameter: {}", enumString, index );
+ }
+ st.setObject( index, enumString, sqlType );
+ }
+ }
+ }
+
+ private boolean isOrdinal(int paramType) {
+ switch ( paramType ) {
+ case Types.INTEGER:
+ case Types.NUMERIC:
+ case Types.SMALLINT:
+ case Types.TINYINT:
+ case Types.BIGINT:
+ case Types.DECIMAL: //for Oracle Driver
+ case Types.DOUBLE: //for Oracle Driver
+ case Types.FLOAT: //for Oracle Driver
+ return true;
+ case Types.CHAR:
+ case Types.LONGVARCHAR:
+ case Types.VARCHAR:
+ return false;
+ default:
+ throw new HibernateException( "Unable to persist an Enum in a column of SQL Type: " + paramType );
+ }
+ }
+
+ public Object deepCopy(Object value) throws HibernateException {
+ return value;
+ }
+
+ public boolean isMutable() {
+ return false;
+ }
+
+ public Serializable disassemble(Object value) throws HibernateException {
+ return (Serializable) value;
+ }
+
+ public Object assemble(Serializable cached, Object owner) throws HibernateException {
+ return cached;
+ }
+
+ public Object replace(Object original, Object target, Object owner) throws HibernateException {
+ return original;
+ }
+
+ public void setParameterValues(Properties parameters) {
+ String enumClassName = parameters.getProperty( ENUM );
+ try {
+ enumClass = ReflectHelper.classForName( enumClassName, this.getClass() ).asSubclass( Enum.class );
+ }
+ catch (ClassNotFoundException exception) {
+ throw new HibernateException( "Enum class not found", exception );
+ }
+ //this is threadsafe to do it here, setParameterValues() is called sequencially
+ initEnumValue();
+ //nullify unnullified properties yuck!
+ schema = parameters.getProperty( SCHEMA );
+ if ( "".equals( schema ) ) schema = null;
+ catalog = parameters.getProperty( CATALOG );
+ if ( "".equals( catalog ) ) catalog = null;
+ table = parameters.getProperty( TABLE );
+ column = parameters.getProperty( COLUMN );
+ String type = parameters.getProperty( TYPE );
+ if ( type != null ) {
+ sqlType = Integer.decode( type ).intValue();
+ guessed = true;
+ }
+ }
+
+ private void initEnumValue() {
+ Object[] values = enumValues.get( enumClass );
+ if ( values == null ) {
+ try {
+ Method method = null;
+ method = enumClass.getDeclaredMethod( "values", new Class[0] );
+ values = (Object[]) method.invoke( null, new Object[0] );
+ enumValues.put( enumClass, values );
+ }
+ catch (Exception e) {
+ throw new HibernateException( "Error while accessing enum.values(): " + enumClass, e );
+ }
+ }
+ }
+
+ private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
+ //FIXME Hum, I think I break the thread safety here
+ ois.defaultReadObject();
+ initEnumValue();
+ }
+
+ public String objectToSQLString(Object value) {
+ boolean isOrdinal = isOrdinal( sqlType );
+ if ( isOrdinal ) {
+ int ordinal = ( (Enum) value ).ordinal();
+ return Integer.toString( ordinal );
+ }
+ else {
+ return '\'' + ( (Enum) value ).name() + '\'';
+ }
+ }
+
+ public String toXMLString(Object value) {
+ boolean isOrdinal = isOrdinal( sqlType );
+ if ( isOrdinal ) {
+ int ordinal = ( (Enum) value ).ordinal();
+ return Integer.toString( ordinal );
+ }
+ else {
+ return ( (Enum) value ).name();
+ }
+ }
+
+ public Object fromXMLString(String xmlValue) {
+ try {
+ int ordinal = Integer.parseInt( xmlValue );
+ Object[] values = enumValues.get( enumClass );
+ if ( values == null ) throw new AssertionFailure( "enumValues not preprocessed: " + enumClass );
+ if ( ordinal < 0 || ordinal >= values.length ) {
+ throw new IllegalArgumentException( "Unknown ordinal value for enum " + enumClass + ": " + ordinal );
+ }
+ return values[ordinal];
+ }
+ catch(NumberFormatException e) {
+ try {
+ return Enum.valueOf( enumClass, xmlValue );
+ }
+ catch (IllegalArgumentException iae) {
+ throw new IllegalArgumentException( "Unknown name value for enum " + enumClass + ": " + xmlValue, iae );
+ }
+ }
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/type/PrimitiveByteArrayBlobType.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/type/PrimitiveByteArrayBlobType.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/type/PrimitiveByteArrayBlobType.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,21 @@
+//$Id: PrimitiveByteArrayBlobType.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.type;
+
+/**
+ * Map a byte[] to a Blob
+ *
+ * @author Emmanuel Bernard
+ */
+public class PrimitiveByteArrayBlobType extends ByteArrayBlobType {
+ public Class getReturnedClass() {
+ return byte[].class;
+ }
+
+ protected Object wrap(byte[] bytes) {
+ return bytes;
+ }
+
+ protected byte[] unWrap(Object bytes) {
+ return (byte[]) bytes;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/type/PrimitiveCharacterArrayClobType.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/type/PrimitiveCharacterArrayClobType.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/type/PrimitiveCharacterArrayClobType.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,14 @@
+//$Id: PrimitiveCharacterArrayClobType.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.type;
+
+
+/**
+ * Map a char[] to a Clob
+ *
+ * @author Emmanuel Bernard
+ */
+public class PrimitiveCharacterArrayClobType extends CharacterArrayClobType {
+ public Class returnedClass() {
+ return char[].class;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/type/SerializableToBlobType.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/type/SerializableToBlobType.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/type/SerializableToBlobType.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,135 @@
+//$Id: SerializableToBlobType.java 17982 2009-11-14 13:18:39Z stliu $
+package org.hibernate.type;
+
+import java.io.ByteArrayInputStream;
+import java.io.Serializable;
+import java.sql.Blob;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Types;
+import java.util.Map;
+import java.util.Properties;
+
+import org.dom4j.Node;
+import org.hibernate.EntityMode;
+import org.hibernate.HibernateException;
+import org.hibernate.MappingException;
+import org.hibernate.engine.Mapping;
+import org.hibernate.engine.SessionFactoryImplementor;
+import org.hibernate.engine.SessionImplementor;
+import org.hibernate.lob.BlobImpl;
+import org.hibernate.usertype.ParameterizedType;
+import org.hibernate.util.ReflectHelper;
+import org.hibernate.util.SerializationHelper;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class SerializableToBlobType extends AbstractLobType implements ParameterizedType {
+ /**
+ * class name of the serialisable class
+ */
+ public static final String CLASS_NAME = "classname";
+ private Class serializableClass;
+ private SerializableType type;
+
+ public int[] sqlTypes(Mapping mapping) throws MappingException {
+ return new int[]{Types.BLOB};
+ }
+
+ public Class getReturnedClass() {
+ return serializableClass;
+ }
+
+ @Override
+ public boolean isEqual(Object x, Object y, EntityMode entityMode, SessionFactoryImplementor factory) {
+ return type.isEqual( x, y );
+ }
+
+
+ @Override
+ public int getHashCode(Object x, EntityMode entityMode, SessionFactoryImplementor session) {
+ return type.getHashCode( x, null );
+ }
+
+ public Object get(ResultSet rs, String name) throws SQLException {
+ Blob blob = rs.getBlob( name );
+ if ( rs.wasNull() ) return null;
+ int length = (int) blob.length();
+ byte[] primaryResult = blob.getBytes( 1, length );
+ return fromBytes( primaryResult );
+ }
+
+ private static byte[] toBytes(Object object) throws SerializationException {
+ return SerializationHelper.serialize( (Serializable) object );
+ }
+
+ private Object fromBytes(byte[] bytes) throws SerializationException {
+ return SerializationHelper.deserialize( bytes, getReturnedClass().getClassLoader() );
+ }
+
+ public void set(PreparedStatement st, Object value, int index, SessionImplementor session) throws SQLException {
+ if ( value != null ) {
+ byte[] toSet;
+ toSet = toBytes( value );
+ if ( session.getFactory().getDialect().useInputStreamToInsertBlob() ) {
+ st.setBinaryStream( index, new ByteArrayInputStream( toSet ), toSet.length );
+ }
+ else {
+ st.setBlob( index, new BlobImpl( toSet ) );
+ }
+ }
+ else {
+ st.setNull( index, sqlTypes( null )[0] );
+ }
+ }
+
+ public void setToXMLNode(Node node, Object value, SessionFactoryImplementor factory) throws HibernateException {
+ type.setToXMLNode( node, value, factory );
+ }
+
+ public String toLoggableString(Object value, SessionFactoryImplementor factory) throws HibernateException {
+ return type.toLoggableString( value, factory );
+ }
+
+ public Object fromXMLNode(Node xml, Mapping factory) throws HibernateException {
+ return type.fromXMLNode( xml, factory );
+ }
+
+ public Object deepCopy(Object value, EntityMode entityMode, SessionFactoryImplementor factory)
+ throws HibernateException {
+ return type.deepCopy( value, null, null );
+ }
+
+ public boolean isMutable() {
+ return type.isMutable();
+ }
+
+ public Object replace(Object original, Object target, SessionImplementor session, Object owner, Map copyCache)
+ throws HibernateException {
+ return type.replace( original, target, session, owner, copyCache );
+ }
+
+ public boolean[] toColumnNullness(Object value, Mapping mapping) {
+ return type.toColumnNullness( value, mapping );
+ }
+
+ public void setParameterValues(Properties parameters) {
+ if ( parameters != null ) {
+ String className = parameters.getProperty( CLASS_NAME );
+ if ( className == null ) {
+ throw new MappingException(
+ "No class name defined for type: " + SerializableToBlobType.class.getName()
+ );
+ }
+ try {
+ serializableClass = ReflectHelper.classForName( className );
+ }
+ catch (ClassNotFoundException e) {
+ throw new MappingException( "Unable to load class from " + CLASS_NAME + " parameter", e );
+ }
+ }
+ type = new SerializableType( serializableClass );
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/type/StringClobType.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/type/StringClobType.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/main/java/org/hibernate/type/StringClobType.java 2009-11-24 21:08:28 UTC (rev 18050)
@@ -0,0 +1,85 @@
+//$Id: StringClobType.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.type;
+
+import java.io.IOException;
+import java.io.Reader;
+import java.io.Serializable;
+import java.io.StringReader;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Types;
+
+import org.hibernate.HibernateException;
+import org.hibernate.usertype.UserType;
+
+/**
+ * Map a String to a Clob
+ *
+ * @author Emmanuel Bernard
+ */
+public class StringClobType implements UserType, Serializable {
+ public int[] sqlTypes() {
+ return new int[]{Types.CLOB};
+ }
+
+ public Class returnedClass() {
+ return String.class;
+ }
+
+ public boolean equals(Object x, Object y) throws HibernateException {
+ return ( x == y ) || ( x != null && x.equals( y ) );
+ }
+
+ public int hashCode(Object x) throws HibernateException {
+ return x.hashCode();
+ }
+
+ public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
+ Reader reader = rs.getCharacterStream( names[0] );
+ if ( reader == null ) return null;
+ StringBuilder result = new StringBuilder( 4096 );
+ try {
+ char[] charbuf = new char[4096];
+ for ( int i = reader.read( charbuf ); i > 0 ; i = reader.read( charbuf ) ) {
+ result.append( charbuf, 0, i );
+ }
+ }
+ catch (IOException e) {
+ throw new SQLException( e.getMessage() );
+ }
+ return result.toString();
+ }
+
+ public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
+ if ( value != null ) {
+ String string = (String) value;
+ StringReader reader = new StringReader( string );
+ st.setCharacterStream( index, reader, string.length() );
+ }
+ else {
+ st.setNull( index, sqlTypes()[0] );
+ }
+ }
+
+ public Object deepCopy(Object value) throws HibernateException {
+ //returning value should be OK since String are immutable
+ return value;
+ }
+
+ public boolean isMutable() {
+ return false;
+ }
+
+ public Serializable disassemble(Object value) throws HibernateException {
+ return (Serializable) value;
+ }
+
+ public Object assemble(Serializable cached, Object owner) throws HibernateException {
+ return cached;
+ }
+
+ public Object replace(Object original, Object target, Object owner) throws HibernateException {
+ return original;
+ }
+}
15 years
Hibernate SVN: r18049 - in annotations/branches/v3_4_0_GA_CP/src/test: java and 66 other directories.
by hibernate-commits@lists.jboss.org
Author: stliu
Date: 2009-11-24 16:03:15 -0500 (Tue, 24 Nov 2009)
New Revision: 18049
Added:
annotations/branches/v3_4_0_GA_CP/src/test/java/org/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/A320.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/A320b.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/AlternativeNamingStrategy.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/AmericaCupClass.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Boat.hbm.xml
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Boat.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Company.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/ConfigurationTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Country.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Customer.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Discount.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/EntityTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Ferry.hbm.xml
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Ferry.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Flight.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/FlyingObject.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/IncorrectEntity.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/JoinedSubclassTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Passport.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Plane.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Port.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/RequiresDialect.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/SafeMappingTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/SecuredBindingTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Sky.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/TestCase.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Thing.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Ticket.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/TicketComparator.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/access/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/access/AccessTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/access/Bed.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/access/BigBed.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/access/Chair.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/access/Furniture.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/access/Gardenshed.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/access/Thingy.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/access/Woody.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/AnyTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/CharProperty.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/IntegerProperty.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/LongProperty.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/Property.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/PropertyList.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/PropertyMap.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/PropertySet.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/StringProperty.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/package-info.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/array/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/array/ArrayTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/array/Competitor.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/array/Contest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/backquotes/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/backquotes/BackquoteTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/backquotes/Bug.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/backquotes/Category.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/bytecode/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/bytecode/Hammer.hbm.xml
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/bytecode/Hammer.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/bytecode/ProxyBreakingTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/bytecode/Tool.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cascade/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cascade/CascadeTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cascade/Mouth.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cascade/Tooth.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/A.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/AId.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/B.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/C.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/Channel.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/Child.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/ChildPk.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/CompositeIdTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/LittleGenius.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/Order.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/OrderLine.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/OrderLinePk.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/Parent.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/ParentPk.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/Presenter.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/Product.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/TvMagazin.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/TvMagazinPk.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/TvProgram.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/TvProgramIdClass.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/Boy.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/Brand.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/Character.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/CollectionElementTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/CountryAttitude.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/LocalizedString.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/Matrix.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/TestCourse.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/Toy.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/A.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/B.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/C.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/DeepCollectionElementTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/indexedCollection/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/indexedCollection/Contact.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/indexedCollection/IndexedCollectionOfElementsTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/indexedCollection/Sale.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/configuration/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/configuration/ConfigurationTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/configuration/orm.xml
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/configuration/package-info.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/duplicatedgenerator/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/duplicatedgenerator/DuplicateTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/duplicatedgenerator/Flight.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/duplicatedgenerator/orm.xml
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Address.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/AddressType.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Book.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/CorpType.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Country.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Deal.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/EmbeddedTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/FixedLeg.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/FloatLeg.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/InternetProvider.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Leg.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/LegalStructure.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Manager.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Nationality.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/NotonialDeal.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Person.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/RegionalArticle.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/RegionalArticlePk.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/SpreadDeal.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Summary.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Swap.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/VanillaSwap.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Address.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/BasicHibernateAnnotationsTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Bid.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/CasterStringType.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/CommunityBid.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Country.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Flight.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Forest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Java5FeaturesTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Length.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/MonetaryAmount.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/MonetaryAmountUserType.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/PropertyDefaultMappingsTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Race.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Ransom.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Starred.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Tree.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/WashingMachine.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/ZipCode.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/package-info.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entitynonentity/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entitynonentity/Cellular.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entitynonentity/Communication.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entitynonentity/EntityNonEntityTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entitynonentity/GSM.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entitynonentity/Interaction.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entitynonentity/Phone.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entitynonentity/Voice.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fetch/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fetch/Branch.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fetch/FetchingTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fetch/Leaf.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fetch/Person.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fetch/Stay.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/A.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/A_PK.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/B.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/C.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/ClassA.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/ClassB.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/ClassC.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/ClassD.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/D.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/D_PK.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/FkCircularityTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/Classes.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/DNA.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/Dummy.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/EmbeddedGenericsTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/Gene.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/GenericsTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/Item.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/Paper.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/PaperType.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/Price.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/PricedStuff.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/SomeGuy.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/State.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/StateType.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/Stuff.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/UnresolvedTypeTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/WildEntity.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/Child.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/ChildHierarchy1.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/ChildHierarchy2.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/ChildHierarchy22.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/GenericsInheritanceTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/Parent.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/ParentHierarchy1.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/ParentHierarchy2.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/ParentHierarchy22.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/hibernate.cfg.xml
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/EnumIdTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/IdClassTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/IdTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/JoinColumnOverrideTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/UUIDGenerator.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Ball.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/BreakDance.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Bunny.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Computer.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Department.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Dog.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/FirTree.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Footballer.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/FootballerPk.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Furniture.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/GoalKeeper.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Home.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Location.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/MilitaryBuilding.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Monkey.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Phone.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Planet.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/PlanetCheatSheet.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/PointyTooth.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Shoe.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/SoundSystem.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Store.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Tower.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Tree.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/TwinkleToes.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/package-info.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/EnumIdTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/IdClassTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/IdTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/JoinColumnOverrideTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/UUIDGenerator.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Ball.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/BreakDance.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Bunny.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Computer.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Department.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Dog.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/FirTree.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Footballer.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/FootballerPk.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Furniture.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/GoalKeeper.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Home.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Location.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/MilitaryBuilding.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Monkey.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Phone.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Planet.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/PlanetCheatSheet.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/PointyTooth.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Shoe.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/SoundSystem.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Store.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Tower.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Tree.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/TwinkleToes.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/package-info.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/identifiercollection/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/identifiercollection/IdentifierCollectionTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/identifiercollection/Passport.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/identifiercollection/Stamp.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/BasketItems.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/BasketItemsPK.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/Card.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/CardField.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/CardKey.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/Customer.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/Customers.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/IdManyToOneTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/Project.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/ShoppingBaskets.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/ShoppingBasketsPK.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/Store.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/StoreCustomer.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/StoreCustomerPK.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/A.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/Acces.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/AlphabeticalIdManyToOneTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/AlphabeticalManyToOneTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/B.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/BId.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/Benefserv.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/C.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/CId.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/Droitacces.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/Service.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/immutable/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/immutable/Country.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/immutable/Foobar.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/immutable/ImmutableTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/immutable/State.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/AddressBook.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/AddressEntry.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/AddressEntryPk.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/AlphabeticalDirectory.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Atmosphere.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Drawer.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Dress.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Gas.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/GasKey.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Generation.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/GenerationGroup.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/GenerationUser.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/IndexedCollectionTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/MapKeyTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/News.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Newspaper.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Painter.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Painting.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/PaintingPk.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/PressReleaseAgency.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Software.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Trainee.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Training.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Version.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Wardrobe.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/Apple.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/Carrot.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/Fruit.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/SubclassTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/Tomato.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/Vegetable.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/VegetablePk.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Alarm.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Asset.hbm.xml
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Asset.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Clothing.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Document.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/EventInformation.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/File.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/FinancialAsset.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Folder.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/JoinedSubclassAndSecondaryTable.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/JoinedSubclassTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Parent.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Pool.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/ProgramExecution.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/PropertyAsset.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Sweater.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/SwimmingPool.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/SymbolicLink.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/mixed/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/mixed/Document.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/mixed/File.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/mixed/Folder.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/mixed/SubclassTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/mixed/SymbolicLink.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/singletable/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/singletable/Building.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/singletable/Funk.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/singletable/House.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/singletable/Music.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/singletable/Noise.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/singletable/PaperTrash.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/singletable/Rock.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/singletable/Trash.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/union/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/union/Document.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/union/File.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/union/Folder.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/union/SubclassTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/union/SymbolicLink.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/interfaces/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/interfaces/Contact.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/interfaces/ContactImpl.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/interfaces/InterfacesTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/interfaces/User.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/interfaces/UserImpl.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/A.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/B.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/C.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/Cat.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/Death.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/Dog.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/DogPk.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/JoinTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/Life.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/loader/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/loader/Loader.hbm.xml
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/loader/LoaderTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/loader/Player.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/loader/Team.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/lob/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/lob/Book.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/lob/CompiledCode.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/lob/Editor.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/lob/LobTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Building.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/BuildingCompany.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Cat.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/CatPk.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/City.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Company.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Contractor.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Employee.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Employer.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Friend.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Group.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/GroupWithSet.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Inspector.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/InspectorPrefixes.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/KnownClient.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Man.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/ManPk.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/ManyToManyTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Permission.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Store.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Supplier.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Woman.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/WomanPk.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Zone.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/BiggestForest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Car.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Carz.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Child.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Color.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Customer.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Deal.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/DistrictUser.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/ForestType.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Frame.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Lens.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Lotz.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/LotzPK.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/ManyToOneJoinTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/ManyToOneOnNonPkTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/ManyToOneTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Node.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/NodePk.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Order.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/OrderLine.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Parent.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/ParentPk.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/TreeType.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/User.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/UserPK.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/referencedcolumnname/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/referencedcolumnname/GenericObject.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/referencedcolumnname/Item.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/referencedcolumnname/ManyToOneReferencedColumnNameTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/referencedcolumnname/Vendor.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/referencedcolumnname/WarehouseItem.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/referencedcolumnname/ZItemCost.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/namingstrategy/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/namingstrategy/Address.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/namingstrategy/DummyNamingStrategy.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/namingstrategy/NamingStrategyTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/namingstrategy/Person.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/naturalid/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/naturalid/Citizen.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/naturalid/NaturalIdOnManyToOne.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/naturalid/NaturalIdOnSingleManyToOneTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/naturalid/NaturalIdTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/naturalid/State.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/notfound/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/notfound/Coin.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/notfound/Currency.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/notfound/NotFoundTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Child.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/City.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Monkey.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/OneToManyTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Order.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/OrderByTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/OrderID.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/OrderItem.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/OrderItemID.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Organisation.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/OrganisationUser.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Parent.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/ParentPk.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Person.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/PoliticalParty.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Politician.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Soldier.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Street.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Tiger.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Trainer.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Troop.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/Address.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/Body.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/Client.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/Computer.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/ComputerPk.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/Heart.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/OneToOneErrorTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/OneToOneTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/Owner.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/OwnerAddress.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/Party.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/PartyAffiliate.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/SerialNumber.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/SerialNumberPk.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/Show.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/ShowDescription.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/Trousers.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/TrousersZip.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/primarykey/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/primarykey/Address.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/primarykey/NullablePrimaryKeyTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/primarykey/Person.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/orm.xml
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/override/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/override/AssociationOverrideTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/override/Location.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/override/Move.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/override/Trip.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/persister/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/persister/Card.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/persister/CollectionPersister.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/persister/Deck.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/persister/EntityPersister.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/persister/PersisterTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/polymorphism/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/polymorphism/Car.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/polymorphism/MovingThing.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/polymorphism/PolymorphismTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/polymorphism/SportCar.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/Area.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/Captain.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/CasimirParticle.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/Chaos.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/Dictionary.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/Dimensions.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/Identity.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/Mark.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/Night.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/QueryAndSQLTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/SpaceShip.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/SynonymousDictionary.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/orm.xml
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/quote/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/quote/QuoteTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/quote/Role.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/quote/User.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/Bag.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/Clothes.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/House.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/Inhabitant.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/Item.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/ItemCost.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/Luggage.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/Postman.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/Rambler.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/ReferencedColumnNameTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/Vendor.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/WarehouseItem.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/Administration.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/Availability.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/BusTrip.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/BusTripPk.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/Competition.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/EJB3OverridenAnnotationReaderTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/LogListener.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/Match.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/Organization.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/OtherLogListener.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/SocialSecurityMoralAccount.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/SocialSecurityNumber.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/SocialSecurityPhysicalAccount.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/TennisMatch.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/XMLContextTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/metadata-complete.xml
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/orm.xml
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/strategy/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/strategy/Location.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/strategy/Storm.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/strategy/StrategyTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tableperclass/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tableperclass/Component.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tableperclass/Machine.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tableperclass/Product.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tableperclass/Robot.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tableperclass/T800.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tableperclass/TablePerClassTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/target/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/target/Brand.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/target/Luggage.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/target/LuggageImpl.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/target/Owner.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/target/OwnerImpl.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/target/Size.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/target/SizeImpl.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/target/TargetTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/Country.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/Cuisine.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/DataProxyHandler.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/DynamicComponentTuplizer.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/DynamicEntityTuplizer.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/DynamicInstantiator.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/EntityNameInterceptor.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/ProxyHelper.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/TuplizerTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/type/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/type/Dvd.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/type/MyOid.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/type/MyOidGenerator.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/type/MyOidType.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/type/TypeTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/various/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/various/Antenna.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/various/Conductor.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/various/GeneratedTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/various/IndexTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/various/ProfessionalAgreement.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/various/Truck.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/various/Vehicule.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/various/VersionTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/CarModel.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/Ejb3XmlTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/Light.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/Lighter.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/Manufacturer.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/Model.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/orm.xml
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/orm2.xml
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/orm3.xml
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/A.hbm.xml
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/A.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/AImpl.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/B.hbm.xml
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/B.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/BImpl.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/CloudType.hbm.xml
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/CloudType.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/Government.hbm.xml
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/Government.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/HbmTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/HbmWithIdentityTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/PrimeMinister.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/Sky.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/Z.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/ZImpl.java
Removed:
annotations/branches/v3_4_0_GA_CP/src/test/org/
Log:
JBPAPP-3150 change the build tool of Hibernate Annotations(eap 5 cp branch)
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/A320.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/A320.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/A320.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,23 @@
+//$Id: A320.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations;
+
+import javax.persistence.DiscriminatorValue;
+import javax.persistence.Entity;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@DiscriminatorValue("A320")
+@Entity()
+public class A320 extends Plane {
+ private String javaEmbeddedVersion;
+
+ public String getJavaEmbeddedVersion() {
+ return javaEmbeddedVersion;
+ }
+
+ public void setJavaEmbeddedVersion(String string) {
+ javaEmbeddedVersion = string;
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/A320b.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/A320b.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/A320b.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,12 @@
+//$Id: A320b.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations;
+
+import javax.persistence.Entity;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity()
+public class A320b extends A320 {
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/AlternativeNamingStrategy.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/AlternativeNamingStrategy.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/AlternativeNamingStrategy.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,73 @@
+//$Id: AlternativeNamingStrategy.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations;
+
+import org.hibernate.cfg.EJB3NamingStrategy;
+import org.hibernate.cfg.NamingStrategy;
+import org.hibernate.util.StringHelper;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class AlternativeNamingStrategy extends EJB3NamingStrategy {
+ public static NamingStrategy INSTANCE = new AlternativeNamingStrategy();
+
+ public String classToTableName(String className) {
+ return tableName( StringHelper.unqualify( className ) );
+ }
+
+ public String propertyToColumnName(String propertyName) {
+ return columnName( StringHelper.unqualify( propertyName ) );
+ }
+
+ public String tableName(String tableName) {
+ return "table_" + tableName;
+ }
+
+ public String columnName(String columnName) {
+ return "f_" + columnName;
+ }
+
+ public String propertyToTableName(String className, String propertyName) {
+ return tableName( StringHelper.unqualify( className ) + "_" + StringHelper.unqualify( propertyName ) );
+ }
+
+ public String logicalColumnName(String columnName, String propertyName) {
+ return StringHelper.isNotEmpty( columnName ) ? columnName : propertyName;
+ }
+
+ public String collectionTableName(
+ String ownerEntity, String ownerEntityTable, String associatedEntity, String associatedEntityTable,
+ String propertyName
+ ) {
+ return tableName(
+ new StringBuilder( ownerEntityTable ).append( "_" )
+ .append(
+ associatedEntityTable != null ?
+ associatedEntityTable :
+ StringHelper.unqualify( propertyName )
+ ).toString()
+ );
+ }
+
+ public String logicalCollectionTablelName(
+ String tableName,
+ String ownerEntityTable, String associatedEntityTable, String propertyName
+ ) {
+ if ( tableName != null ) {
+ return tableName;
+ }
+ else {
+ //use of a stringbuffer to workaround a JDK bug
+ return new StringBuffer( ownerEntityTable ).append( "_" )
+ .append(
+ associatedEntityTable != null ?
+ associatedEntityTable :
+ StringHelper.unqualify( propertyName )
+ ).toString();
+ }
+ }
+
+ public String logicalCollectionColumnName(String columnName, String propertyName, String referencedColumn) {
+ return StringHelper.isNotEmpty( columnName ) ? columnName : propertyName + "_" + referencedColumn;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/AmericaCupClass.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/AmericaCupClass.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/AmericaCupClass.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,26 @@
+//$Id: AmericaCupClass.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations;
+
+import javax.persistence.Entity;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+import javax.persistence.PrimaryKeyJoinColumn;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@PrimaryKeyJoinColumn(name = "BOAT_ID")
+public class AmericaCupClass extends Boat {
+ private Country country;
+
+ @ManyToOne()
+ @JoinColumn(name = "COUNTRY_ID")
+ public Country getCountry() {
+ return country;
+ }
+
+ public void setCountry(Country country) {
+ this.country = country;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Boat.hbm.xml
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Boat.hbm.xml (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Boat.hbm.xml 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,26 @@
+<?xml version="1.0"?>
+<!DOCTYPE hibernate-mapping PUBLIC
+ "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+ "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
+
+<!--
+
+ Used to demonstrate the declarative configuration
+ of both hbm files and annotated classes
+ See hibernate.cfg.xml and ConfigurationTest
+
+-->
+
+<hibernate-mapping package="org.hibernate.test.annotations">
+
+ <class name="Boat" table="BoatInXml">
+
+ <id name="id">
+ <generator class="native"/>
+ </id>
+
+ <property name="size" column="boat_size"/>
+
+ </class>
+
+</hibernate-mapping>
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Boat.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Boat.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Boat.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,57 @@
+//$Id: Boat.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations;
+
+import java.io.Serializable;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+
+
+/**
+ * Boat class. Mapped in a Joined manner
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity()
+@Inheritance(
+ strategy = InheritanceType.JOINED
+)
+public class Boat implements Serializable {
+ private Integer id;
+ private int size;
+ private int weight;
+
+ public Boat() {
+ super();
+ }
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ @Column(name = "boat_size")
+ public int getSize() {
+ return size;
+ }
+
+ public void setId(Integer integer) {
+ id = integer;
+ }
+
+ public void setSize(int i) {
+ size = i;
+ }
+
+ public int getWeight() {
+ return weight;
+ }
+
+ public void setWeight(int weight) {
+ this.weight = weight;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Company.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Company.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Company.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,46 @@
+//$Id: Company.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations;
+
+import java.io.Serializable;
+import java.util.Date;
+import java.util.Set;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+
+/**
+ * Corporate like Air France
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity(name = "Corporation")
+public class Company implements Serializable {
+ private Integer id;
+ private String name;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+
+ public void setId(Integer integer) {
+ id = integer;
+ }
+
+
+ public void setName(String string) {
+ name = string;
+ }
+
+ //should be treated as getter
+ private int[] getWorkingHoursPerWeek(Set<Date> holidayDays) {
+ return null;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/ConfigurationTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/ConfigurationTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/ConfigurationTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,155 @@
+//$Id: ConfigurationTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations;
+
+import org.hibernate.HibernateException;
+import org.hibernate.MappingException;
+import org.hibernate.Query;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.hibernate.Transaction;
+import org.hibernate.cfg.AnnotationConfiguration;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.cfg.Environment;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class ConfigurationTest extends junit.framework.TestCase {
+ public void testDeclarativeMix() throws Exception {
+ AnnotationConfiguration cfg = new AnnotationConfiguration();
+ cfg.configure( "org/hibernate/test/annotations/hibernate.cfg.xml" );
+ cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
+ SessionFactory sf = cfg.buildSessionFactory();
+ assertNotNull( sf );
+ Session s = sf.openSession();
+ Transaction tx = s.beginTransaction();
+ Query q = s.createQuery( "from Boat" );
+ assertEquals( 0, q.list().size() );
+ q = s.createQuery( "from Plane" );
+ assertEquals( 0, q.list().size() );
+ tx.commit();
+ s.close();
+ sf.close();
+ }
+
+ public void testIgnoringHbm() throws Exception {
+ AnnotationConfiguration cfg = new AnnotationConfiguration();
+ cfg.configure( "org/hibernate/test/annotations/hibernate.cfg.xml" );
+ cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
+ cfg.setProperty( AnnotationConfiguration.ARTEFACT, "class, whatever" );
+ SessionFactory sf = cfg.buildSessionFactory();
+ assertNotNull( sf );
+ Session s = sf.openSession();
+ Transaction tx = s.beginTransaction();
+ Query q;
+ try {
+ s.createQuery( "from Boat" ).list();
+ fail( "Boat should not be mapped" );
+ }
+ catch (HibernateException e) {
+ //all good
+ }
+ q = s.createQuery( "from Plane" );
+ assertEquals( 0, q.list().size() );
+ tx.commit();
+ s.close();
+ sf.close();
+ }
+
+ public void testPrecedenceHbm() throws Exception {
+ AnnotationConfiguration cfg = new AnnotationConfiguration();
+ cfg.configure( "org/hibernate/test/annotations/hibernate.cfg.xml" );
+ cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
+ cfg.addAnnotatedClass( Boat.class );
+ SessionFactory sf = cfg.buildSessionFactory();
+ assertNotNull( sf );
+ Session s = sf.openSession();
+ s.getTransaction().begin();
+ Boat boat = new Boat();
+ boat.setSize( 12 );
+ boat.setWeight( 34 );
+ s.persist( boat );
+ s.getTransaction().commit();
+ s.clear();
+ Transaction tx = s.beginTransaction();
+ boat = (Boat) s.get( Boat.class, boat.getId() );
+ assertTrue( "Annotation has precedence", 34 != boat.getWeight() );
+ s.delete( boat );
+ //s.getTransaction().commit();
+ tx.commit();
+ s.close();
+ sf.close();
+ }
+
+ public void testPrecedenceAnnotation() throws Exception {
+ AnnotationConfiguration cfg = new AnnotationConfiguration();
+ cfg.configure( "org/hibernate/test/annotations/hibernate.cfg.xml" );
+ cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
+ cfg.setProperty( AnnotationConfiguration.ARTEFACT, "class, hbm" );
+ cfg.addAnnotatedClass( Boat.class );
+ SessionFactory sf = cfg.buildSessionFactory();
+ assertNotNull( sf );
+ Session s = sf.openSession();
+ s.getTransaction().begin();
+ Boat boat = new Boat();
+ boat.setSize( 12 );
+ boat.setWeight( 34 );
+ s.persist( boat );
+ s.getTransaction().commit();
+ s.clear();
+ Transaction tx = s.beginTransaction();
+ boat = (Boat) s.get( Boat.class, boat.getId() );
+ assertTrue( "Annotation has precedence", 34 == boat.getWeight() );
+ s.delete( boat );
+ tx.commit();
+ s.close();
+ sf.close();
+ }
+
+ public void testDeclarativeAnnWoAnnConfig() throws Exception {
+ Configuration cfg = new Configuration();
+ try {
+ cfg.configure( "org/hibernate/test/annotations/hibernate.cfg.xml" );
+ fail( "Configuration object should fail when finding annotated elements declarations" );
+ }
+ catch (MappingException e) {
+ //success
+ }
+ }
+
+ public void testHbmWithSubclassExtends() throws Exception {
+ AnnotationConfiguration cfg = new AnnotationConfiguration();
+ cfg.configure( "org/hibernate/test/annotations/hibernate.cfg.xml" );
+ cfg.addClass( Ferry.class );
+ cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
+ SessionFactory sf = cfg.buildSessionFactory();
+ assertNotNull( sf );
+ Session s = sf.openSession();
+ Transaction tx = s.beginTransaction();
+ Query q = s.createQuery( "from Ferry" );
+ assertEquals( 0, q.list().size() );
+ q = s.createQuery( "from Plane" );
+ assertEquals( 0, q.list().size() );
+ tx.commit();
+ s.close();
+ sf.close();
+ }
+
+ public void testAnnReferencesHbm() throws Exception {
+ AnnotationConfiguration cfg = new AnnotationConfiguration();
+ cfg.configure( "org/hibernate/test/annotations/hibernate.cfg.xml" );
+ cfg.addAnnotatedClass( Port.class );
+ cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
+ SessionFactory sf = cfg.buildSessionFactory();
+ assertNotNull( sf );
+ Session s = sf.openSession();
+ Transaction tx = s.beginTransaction();
+ Query q = s.createQuery( "from Boat" );
+ assertEquals( 0, q.list().size() );
+ q = s.createQuery( "from Port" );
+ assertEquals( 0, q.list().size() );
+ tx.commit();
+ s.close();
+ sf.close();
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Country.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Country.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Country.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,47 @@
+//$Id: Country.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations;
+
+/**
+ * @author Emmanuel Bernard
+ */
+
+import java.io.Serializable;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+@Entity()
+public class Country implements Serializable {
+ private Integer id;
+ private String name;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setId(Integer integer) {
+ id = integer;
+ }
+
+ public void setName(String string) {
+ name = string;
+ }
+
+ public int hashCode() {
+ return name == null ? 0 : name.hashCode();
+ }
+
+ public boolean equals(Object obj) {
+ if ( obj == this ) return true;
+ if ( ! ( obj instanceof Country ) ) return false;
+ Country that = (Country) obj;
+ if ( this.name == null ) return false;
+ return this.name.equals( that.name );
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Customer.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Customer.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Customer.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,88 @@
+//$Id: Customer.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations;
+
+import java.io.Serializable;
+import java.util.Collection;
+import java.util.SortedSet;
+import javax.persistence.CascadeType;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.OneToMany;
+import javax.persistence.OneToOne;
+
+import org.hibernate.annotations.Cascade;
+import static org.hibernate.annotations.CascadeType.ALL;
+import org.hibernate.annotations.Sort;
+import org.hibernate.annotations.SortType;
+
+
+/**
+ * Company customer
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Customer implements Serializable {
+ Long id;
+ String name;
+ SortedSet<Ticket> tickets;
+ Collection discountTickets;
+ Passport passport;
+
+ public Customer() {
+ }
+
+ @Id
+ @GeneratedValue
+ public Long getId() {
+ return id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setId(Long long1) {
+ id = long1;
+ }
+
+ public void setName(String string) {
+ name = string;
+ }
+
+ @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
+ @JoinColumn(name = "CUST_ID")
+ @Sort(type = SortType.COMPARATOR, comparator = TicketComparator.class)
+ public SortedSet<Ticket> getTickets() {
+ return tickets;
+ }
+
+ public void setTickets(SortedSet<Ticket> tickets) {
+ this.tickets = tickets;
+ }
+
+ @OneToMany(targetEntity = org.hibernate.test.annotations.Discount.class,
+ cascade = CascadeType.ALL, mappedBy = "owner")
+ @Cascade({ALL})
+ public Collection getDiscountTickets() {
+ return discountTickets;
+ }
+
+ public void setDiscountTickets(Collection collection) {
+ discountTickets = collection;
+ }
+
+ @OneToOne(cascade = CascadeType.ALL)
+ public Passport getPassport() {
+ return passport;
+ }
+
+ public void setPassport(Passport passport) {
+ this.passport = passport;
+ }
+
+}
+
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Discount.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Discount.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Discount.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,58 @@
+//$Id: Discount.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations;
+
+import java.io.Serializable;
+import javax.persistence.CascadeType;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+
+
+/**
+ * Discount ticket a client can use when buying tickets
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Discount implements Serializable {
+
+ private Long id;
+ private double discount;
+ private Customer owner;
+
+
+ @Column(precision = 5, scale = 2)
+ public double getDiscount() {
+ return discount;
+ }
+
+ @Id
+ @GeneratedValue
+ public Long getId() {
+ return id;
+ }
+
+ public void setDiscount(double i) {
+ discount = i;
+ }
+
+ public void setId(Long long1) {
+ id = long1;
+ }
+
+ @ManyToOne(cascade = {CascadeType.ALL}, fetch = FetchType.LAZY)
+ @JoinColumn(name = "CUSTOMER_ID")
+ public Customer getOwner() {
+ return owner;
+ }
+
+ public void setOwner(Customer customer) {
+ owner = customer;
+ }
+
+}
+
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/EntityTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/EntityTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/EntityTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,385 @@
+//$Id: EntityTest.java 16418 2009-04-23 09:55:33Z jcosta(a)redhat.com $
+package org.hibernate.test.annotations;
+
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.List;
+import java.util.TimeZone;
+
+import org.hibernate.Hibernate;
+import org.hibernate.HibernateException;
+import org.hibernate.Query;
+import org.hibernate.Session;
+import org.hibernate.StaleStateException;
+import org.hibernate.Transaction;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class EntityTest extends TestCase {
+
+ public EntityTest(String x) {
+ super( x );
+ }
+
+ public void testLoad() throws Exception {
+ //put an object in DB
+ assertEquals( "Flight", getCfg().getClassMapping( Flight.class.getName() ).getTable().getName() );
+
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Flight firstOne = new Flight();
+ firstOne.setId( new Long( 1 ) );
+ firstOne.setName( "AF3202" );
+ firstOne.setDuration( new Long( 1000000 ) );
+ firstOne.setDurationInSec( 2000 );
+ s.save( firstOne );
+ s.flush();
+ tx.commit();
+ s.close();
+
+ //read it
+ s = openSession();
+ tx = s.beginTransaction();
+ firstOne = (Flight) s.get( Flight.class, new Long( 1 ) );
+ assertNotNull( firstOne );
+ assertEquals( new Long( 1 ), firstOne.getId() );
+ assertEquals( "AF3202", firstOne.getName() );
+ assertEquals( new Long( 1000000 ), firstOne.getDuration() );
+ assertFalse( "Transient is not working", 2000l == firstOne.getDurationInSec() );
+ tx.commit();
+ s.close();
+ }
+
+ public void testColumn() throws Exception {
+ //put an object in DB
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Flight firstOne = new Flight();
+ firstOne.setId( new Long( 1 ) );
+ firstOne.setName( "AF3202" );
+ firstOne.setDuration( new Long( 1000000 ) );
+ firstOne.setDurationInSec( 2000 );
+ s.save( firstOne );
+ s.flush();
+ tx.commit();
+ s.close();
+
+
+ s = openSession();
+ tx = s.beginTransaction();
+ firstOne = new Flight();
+ firstOne.setId( new Long( 1 ) );
+ firstOne.setName( null );
+
+ try {
+ s.save( firstOne );
+ tx.commit();
+ fail( "Name column should be not null" );
+ }
+ catch (HibernateException e) {
+ //fine
+ }
+ finally {
+ s.close();
+ }
+
+ //insert an object and check that name is not updatable
+ s = openSession();
+ tx = s.beginTransaction();
+ firstOne = new Flight();
+ firstOne.setId( new Long( 1 ) );
+ firstOne.setName( "AF3202" );
+ firstOne.setTriggeredData( "should not be insertable" );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ firstOne = (Flight) s.get( Flight.class, new Long( 1 ) );
+ assertNotNull( firstOne );
+ assertEquals( new Long( 1 ), firstOne.getId() );
+ assertEquals( "AF3202", firstOne.getName() );
+ assertFalse( "should not be insertable".equals( firstOne.getTriggeredData() ) );
+ firstOne.setName( "BA1234" );
+ firstOne.setTriggeredData( "should not be updatable" );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ firstOne = (Flight) s.get( Flight.class, new Long( 1 ) );
+ assertNotNull( firstOne );
+ assertEquals( new Long( 1 ), firstOne.getId() );
+ assertEquals( "AF3202", firstOne.getName() );
+ assertFalse( "should not be updatable".equals( firstOne.getTriggeredData() ) );
+ tx.commit();
+ s.close();
+ }
+
+ public void testColumnUnique() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Sky sky = new Sky();
+ sky.id = new Long( 2 );
+ sky.color = "blue";
+ sky.day = "monday";
+ sky.month = "January";
+
+ Sky sameSky = new Sky();
+ sameSky.id = new Long( 3 );
+ sameSky.color = "blue";
+ sky.day = "tuesday";
+ sky.month = "January";
+
+ try {
+ s.save( sky );
+ s.flush();
+ s.save( sameSky );
+ tx.commit();
+ fail( "unique constraints not respected" );
+ }
+ catch (HibernateException e) {
+ //success
+ }
+ finally {
+ if ( tx != null ) tx.rollback();
+ s.close();
+ }
+ }
+
+ public void testUniqueConstraint() throws Exception {
+ int id = 5;
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Sky sky = new Sky();
+ sky.id = new Long( id++ );
+ sky.color = "green";
+ sky.day = "monday";
+ sky.month = "March";
+
+ Sky otherSky = new Sky();
+ otherSky.id = new Long( id++ );
+ otherSky.color = "red";
+ otherSky.day = "friday";
+ otherSky.month = "March";
+
+ Sky sameSky = new Sky();
+ sameSky.id = new Long( id++ );
+ sameSky.color = "green";
+ sameSky.day = "monday";
+ sameSky.month = "March";
+
+ s.save( sky );
+ s.flush();
+
+ s.save( otherSky );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ try {
+ s.save( sameSky );
+ tx.commit();
+ fail( "unique constraints not respected" );
+ }
+ catch (HibernateException e) {
+ //success
+ }
+ finally {
+ if ( tx != null ) tx.rollback();
+ s.close();
+ }
+ }
+
+ public void testVersion() throws Exception {
+// put an object in DB
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Flight firstOne = new Flight();
+ firstOne.setId( new Long( 2 ) );
+ firstOne.setName( "AF3202" );
+ firstOne.setDuration( new Long( 500 ) );
+ s.save( firstOne );
+ s.flush();
+ tx.commit();
+ s.close();
+
+ //read it
+ s = openSession();
+ tx = s.beginTransaction();
+ firstOne = (Flight) s.get( Flight.class, new Long( 2 ) );
+ tx.commit();
+ s.close();
+
+ //read it again
+ s = openSession();
+ tx = s.beginTransaction();
+ Flight concurrentOne = (Flight) s.get( Flight.class, new Long( 2 ) );
+ concurrentOne.setDuration( new Long( 1000 ) );
+ s.update( concurrentOne );
+ tx.commit();
+ s.close();
+ assertFalse( firstOne == concurrentOne );
+ assertFalse( firstOne.getVersion().equals( concurrentOne.getVersion() ) );
+
+ //reattach the first one
+ s = openSession();
+ tx = s.beginTransaction();
+ firstOne.setName( "Second access" );
+ s.update( firstOne );
+ try {
+ tx.commit();
+ fail( "Optimistic locking should work" );
+ }
+ catch (StaleStateException e) {
+ //fine
+ }
+ finally {
+ if ( tx != null ) tx.rollback();
+ s.close();
+ }
+
+ }
+
+ public void testFieldAccess() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Sky sky = new Sky();
+ sky.id = new Long( 1 );
+ sky.color = "black";
+ Sky.area = "Paris";
+ sky.day = "23";
+ sky.month = "1";
+ s.save( sky );
+ tx.commit();
+ s.close();
+ Sky.area = "London";
+
+ s = openSession();
+ tx = s.beginTransaction();
+ sky = (Sky) s.get( Sky.class, sky.id );
+ assertNotNull( sky );
+ assertEquals( "black", sky.color );
+ assertFalse( "Paris".equals( Sky.area ) );
+ tx.commit();
+ s.close();
+ }
+
+ public void testEntityName() throws Exception {
+ assertEquals( "Corporation", getCfg().getClassMapping( Company.class.getName() ).getTable().getName() );
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Company comp = new Company();
+ s.persist( comp );
+ comp.setName( "JBoss Inc" );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ List result = s.createQuery( "from Corporation" ).list();
+ assertNotNull( result );
+ assertEquals( 1, result.size() );
+ tx.commit();
+ s.close();
+
+ }
+
+ public void testNonGetter() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Flight airFrance = new Flight();
+ airFrance.setId( new Long( 747 ) );
+ airFrance.setName( "Paris-Amsterdam" );
+ airFrance.setDuration( new Long( 10 ) );
+ airFrance.setFactor( 25 );
+ s.persist( airFrance );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ airFrance = (Flight) s.get( Flight.class, airFrance.getId() );
+ assertNotNull( airFrance );
+ assertEquals( new Long( 10 ), airFrance.getDuration() );
+ assertFalse( 25 == airFrance.getFactor( false ) );
+ s.delete( airFrance );
+ tx.commit();
+ s.close();
+ }
+
+ public void testTemporalType() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Flight airFrance = new Flight();
+ airFrance.setId( new Long( 747 ) );
+ airFrance.setName( "Paris-Amsterdam" );
+ airFrance.setDuration( new Long( 10 ) );
+ airFrance.setDepartureDate( new Date( 05, 06, 21, 10, 0, 0 ) );
+ airFrance.setAlternativeDepartureDate( new GregorianCalendar( 2006, 02, 03, 10, 00 ) );
+ airFrance.getAlternativeDepartureDate().setTimeZone( TimeZone.getTimeZone( "GMT" ) );
+ airFrance.setBuyDate( new java.sql.Timestamp(122367443) );
+ airFrance.setFactor( 25 );
+ s.persist( airFrance );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ Query q = s.createQuery( "from Flight f where f.departureDate = :departureDate" );
+ q.setParameter( "departureDate", airFrance.getDepartureDate(), Hibernate.DATE );
+ Flight copyAirFrance = (Flight) q.uniqueResult();
+ assertNotNull( copyAirFrance );
+ assertEquals(
+ new Date( 05, 06, 21 ),
+ copyAirFrance.getDepartureDate()
+ );
+ assertEquals( copyAirFrance.getBuyDate().getTime() / 1000 , airFrance.getBuyDate().getTime() / 1000 );
+
+ s.delete( copyAirFrance );
+ tx.commit();
+ s.close();
+ }
+
+ public void testBasic() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Flight airFrance = new Flight();
+ airFrance.setId( new Long( 747 ) );
+ airFrance.setName( "Paris-Amsterdam" );
+ airFrance.setDuration( null );
+ try {
+ s.persist( airFrance );
+ tx.commit();
+ fail( "Basic(optional=false) fails" );
+ }
+ catch (Exception e) {
+ //success
+ if ( tx != null ) tx.rollback();
+ }
+ finally {
+ s.close();
+ }
+ }
+
+ /**
+ * @see org.hibernate.test.annotations.TestCase#getMappings()
+ */
+ protected Class[] getMappings() {
+ return new Class[]{
+ Flight.class,
+ Company.class,
+ Sky.class
+ };
+ }
+
+}
+
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Ferry.hbm.xml
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Ferry.hbm.xml (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Ferry.hbm.xml 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,23 @@
+<?xml version="1.0"?>
+<!DOCTYPE hibernate-mapping PUBLIC
+ "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+ "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
+
+<!--
+
+ Used to test the interaction of hbm files with a subclass
+ extends attribute and annotated classes.
+
+ See ConfigurationTest
+
+-->
+
+<hibernate-mapping package="org.hibernate.test.annotations">
+
+ <joined-subclass name="Ferry" table="FerryJoined" extends="org.hibernate.test.annotations.Boat">
+ <key column="id"/>
+ <property name="sea"/>
+
+ </joined-subclass>
+
+</hibernate-mapping>
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Ferry.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Ferry.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Ferry.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,22 @@
+//$Id: Ferry.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations;
+
+import javax.persistence.Entity;
+
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity()
+public class Ferry extends Boat {
+ private String sea;
+
+ public String getSea() {
+ return sea;
+ }
+
+ public void setSea(String string) {
+ sea = string;
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Flight.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Flight.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Flight.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,149 @@
+//$Id: Flight.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations;
+
+import java.io.Serializable;
+import java.util.Calendar;
+import java.util.Date;
+import javax.persistence.Basic;
+import javax.persistence.CascadeType;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.Id;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+import javax.persistence.Temporal;
+import javax.persistence.TemporalType;
+import javax.persistence.Transient;
+import javax.persistence.Version;
+
+/**
+ * Flight
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity()
+@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
+public class Flight implements Serializable {
+ Long id;
+ String name;
+ transient Long duration;
+ long durationInSec;
+ Integer version;
+ Company company;
+ String triggeredData;
+ long factor;
+ Date departureDate;
+ java.sql.Timestamp buyDate;
+ Calendar alternativeDepartureDate;
+
+ @Id
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long long1) {
+ id = long1;
+ }
+
+ @Column(name = "flight_name", nullable = false, updatable = false, length = 50)
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String string) {
+ name = string;
+ }
+
+ @Basic(fetch = FetchType.LAZY, optional = false)
+ public Long getDuration() {
+ return duration;
+ }
+
+ @Basic
+ @Temporal(TemporalType.DATE)
+ public Date getDepartureDate() {
+ return departureDate;
+ }
+
+ public void setDepartureDate(Date departureDate) {
+ this.departureDate = departureDate;
+ }
+
+
+ public void setDuration(Long l) {
+ duration = l;
+ //durationInSec = duration / 1000;
+ }
+
+ @Transient
+ public long getDurationInSec() {
+ return durationInSec;
+ }
+
+ public void setDurationInSec(long l) {
+ durationInSec = l;
+ }
+
+ @Version
+ @Column(name = "OPTLOCK")
+ public Integer getVersion() {
+ return version;
+ }
+
+ public void setVersion(Integer i) {
+ version = i;
+ }
+
+ @ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
+ @JoinColumn(name = "COMP_ID")
+ public Company getCompany() {
+ return company;
+ }
+
+ public void setCompany(Company company) {
+ this.company = company;
+ }
+
+ @Column(insertable = false, updatable = false)
+ public String getTriggeredData() {
+ return triggeredData;
+ }
+
+ public void setTriggeredData(String string) {
+ triggeredData = string;
+ }
+
+ public void getIsNotAGetter() {
+ //do nothing
+ }
+
+ public long getFactor(boolean x10) {
+ //this is not a getter should not be persisted
+ return factor * ( 1 + ( x10 == true ? 9 : 0 ) );
+ }
+
+ public void setFactor(long factor) {
+ this.factor = factor;
+ }
+
+ @Temporal(TemporalType.TIMESTAMP)
+ public Calendar getAlternativeDepartureDate() {
+ return alternativeDepartureDate;
+ }
+
+ public void setAlternativeDepartureDate(Calendar alternativeDepartureDate) {
+ this.alternativeDepartureDate = alternativeDepartureDate;
+ }
+
+ public java.sql.Timestamp getBuyDate() {
+ return buyDate;
+ }
+
+ public void setBuyDate(java.sql.Timestamp buyDate) {
+ this.buyDate = buyDate;
+ }
+
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/FlyingObject.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/FlyingObject.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/FlyingObject.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,54 @@
+//$Id: FlyingObject.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations;
+
+import java.io.Serializable;
+import javax.persistence.Column;
+import javax.persistence.MappedSuperclass;
+import javax.persistence.Transient;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@MappedSuperclass
+public abstract class FlyingObject extends Thing implements Serializable {
+ private String serial;
+ private int altitude;
+ private int metricAltitude;
+ private String color = "white";
+
+
+ public int getAltitude() {
+ return altitude;
+ }
+
+ public void setAltitude(int i) {
+ altitude = i;
+ }
+
+ @Transient
+ public int getMetricAltitude() {
+ return metricAltitude;
+ }
+
+ public void setMetricAltitude(int i) {
+ metricAltitude = i;
+ }
+
+ @Column(name = "serialnbr")
+ public String getSerial() {
+ return serial;
+ }
+
+ public void setSerial(String serial) {
+ this.serial = serial;
+ }
+
+ @Column(nullable = false)
+ public String getColor() {
+ return color;
+ }
+
+ public void setColor(String color) {
+ this.color = color;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/IncorrectEntity.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/IncorrectEntity.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/IncorrectEntity.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,20 @@
+//$Id: IncorrectEntity.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations;
+
+import javax.persistence.Entity;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class IncorrectEntity {
+ private String name;
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/JoinedSubclassTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/JoinedSubclassTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/JoinedSubclassTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,110 @@
+//$Id: JoinedSubclassTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations;
+
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.annotations.inheritance.Carrot;
+import org.hibernate.test.annotations.inheritance.Tomato;
+import org.hibernate.test.annotations.inheritance.Vegetable;
+import org.hibernate.test.annotations.inheritance.VegetablePk;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class JoinedSubclassTest extends TestCase {
+
+ public JoinedSubclassTest(String x) {
+ super( x );
+ }
+
+ public void testDefaultValues() {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Ferry f = new Ferry();
+ f.setSize( 2 );
+ f.setSea( "Channel" );
+ s.persist( f );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ f = (Ferry) s.get( Ferry.class, f.getId() );
+ assertNotNull( f );
+ assertEquals( "Channel", f.getSea() );
+ assertEquals( 2, f.getSize() );
+ s.delete( f );
+ tx.commit();
+ s.close();
+ }
+
+ public void testDeclaredValues() {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Country c = new Country();
+ c.setName( "France" );
+ AmericaCupClass f = new AmericaCupClass();
+ f.setSize( 2 );
+ f.setCountry( c );
+ s.persist( c );
+ s.persist( f );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ f = (AmericaCupClass) s.get( AmericaCupClass.class, f.getId() );
+ assertNotNull( f );
+ assertEquals( c, f.getCountry() );
+ assertEquals( 2, f.getSize() );
+ s.delete( f );
+ s.delete( f.getCountry() );
+ tx.commit();
+ s.close();
+ }
+
+ public void testCompositePk() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Carrot c = new Carrot();
+ VegetablePk pk = new VegetablePk();
+ pk.setFarmer( "Bill" );
+ pk.setHarvestDate( "2004-08-15" );
+ c.setId( pk );
+ c.setLength( 23 );
+ s.persist( c );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ Vegetable v = (Vegetable) s.createCriteria( Vegetable.class ).uniqueResult();
+ assertTrue( v instanceof Carrot );
+ Carrot result = (Carrot) v;
+ assertEquals( 23, result.getLength() );
+ tx.commit();
+ s.close();
+ }
+
+ /**
+ * @see org.hibernate.test.annotations.TestCase#getMappings()
+ */
+ protected Class[] getMappings() {
+ return new Class[]{
+ Boat.class,
+ Ferry.class,
+ AmericaCupClass.class,
+ Country.class,
+ Vegetable.class,
+ Carrot.class,
+ Tomato.class
+ };
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Passport.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Passport.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Passport.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,49 @@
+//$Id: Passport.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations;
+
+import java.io.Serializable;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.OneToOne;
+
+/**
+ * International passport
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Passport implements Serializable {
+
+ private Long id;
+ private String number;
+ private Customer owner;
+
+ @Id
+ public Long getId() {
+ return id;
+ }
+
+ @Column(name = "passport_number")
+ public String getNumber() {
+ return number;
+ }
+
+ @OneToOne(mappedBy = "passport")
+ public Customer getOwner() {
+ return owner;
+ }
+
+ public void setId(Long long1) {
+ id = long1;
+ }
+
+ public void setNumber(String string) {
+ number = string;
+ }
+
+ public void setOwner(Customer customer) {
+ owner = customer;
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Plane.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Plane.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Plane.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,58 @@
+//$Id: Plane.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations;
+
+import javax.persistence.AttributeOverride;
+import javax.persistence.Column;
+import javax.persistence.DiscriminatorColumn;
+import javax.persistence.DiscriminatorType;
+import javax.persistence.DiscriminatorValue;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+import javax.persistence.NamedQuery;
+import javax.persistence.QueryHint;
+
+/**
+ * Plane class
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity()
+@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
+@DiscriminatorColumn(name = "planetype", length = 100, discriminatorType = DiscriminatorType.STRING)
+@DiscriminatorValue("Plane")
+@AttributeOverride(name = "altitude", column = @Column(name = "fld_altitude"))
+@NamedQuery(name = "plane.byId", query = "from Plane where id = :id",
+ hints = {@QueryHint(name = "org.hibernate.cacheable", value = "true"),
+ @QueryHint(name = "org.hibernate.cacheRegion", value = "testedCacheRegion"),
+ @QueryHint(name = "org.hibernate.timeout", value = "100"),
+ @QueryHint(name = "org.hibernate.fetchSize", value = "1"),
+ @QueryHint(name = "org.hibernate.flushMode", value = "Commit"),
+ @QueryHint(name = "org.hibernate.cacheMode", value = "NORMAL"),
+ @QueryHint(name = "org.hibernate.comment", value = "Plane by id")})
+public class Plane extends FlyingObject {
+
+ private Long id;
+ private int nbrofSeats;
+
+ @Id
+ @GeneratedValue
+ public Long getId() {
+ return id;
+ }
+
+ public int getNbrOfSeats() {
+ return nbrofSeats;
+ }
+
+ public void setId(Long long1) {
+ id = long1;
+ }
+
+ public void setNbrOfSeats(int i) {
+ nbrofSeats = i;
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Port.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Port.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Port.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,37 @@
+//$Id: Port.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations;
+
+import java.util.Set;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.OneToMany;
+
+/**
+ * Used to test that annotated classes can have one-to-many
+ * relationships with hbm loaded classes.
+ */
+@Entity()
+public class Port {
+ private Long id;
+ private Set<Boat> boats;
+
+ @Id
+ @GeneratedValue
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long long1) {
+ id = long1;
+ }
+
+ @OneToMany
+ public Set<Boat> getBoats() {
+ return boats;
+ }
+
+ public void setBoats(Set<Boat> boats) {
+ this.boats = boats;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/RequiresDialect.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/RequiresDialect.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/RequiresDialect.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,20 @@
+// $Id: RequiresDialect.java 15025 2008-08-11 09:14:39Z hardy.ferentschik $
+package org.hibernate.test.annotations;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+import org.hibernate.dialect.Dialect;
+
+/**
+ * Annotations used to mark a test to be specific to a given dialect.
+ *
+ * @author Hardy Ferentschik
+ */
+(a)Target({ElementType.METHOD, ElementType.TYPE})
+(a)Retention(RetentionPolicy.RUNTIME)
+public @interface RequiresDialect {
+ Class<? extends Dialect>[] value();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/SafeMappingTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/SafeMappingTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/SafeMappingTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,25 @@
+//$Id: SafeMappingTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations;
+
+import org.hibernate.AnnotationException;
+import org.hibernate.SessionFactory;
+import org.hibernate.cfg.AnnotationConfiguration;
+import org.hibernate.cfg.Environment;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class SafeMappingTest extends junit.framework.TestCase {
+ public void testDeclarativeMix() throws Exception {
+ AnnotationConfiguration cfg = new AnnotationConfiguration();
+ cfg.addAnnotatedClass( IncorrectEntity.class );
+ cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
+ try {
+ SessionFactory sf = cfg.buildSessionFactory();
+ fail( "Entity wo id should fail" );
+ }
+ catch (AnnotationException e) {
+ //success
+ }
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/SecuredBindingTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/SecuredBindingTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/SecuredBindingTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,44 @@
+//$Id: SecuredBindingTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations;
+
+import java.util.Properties;
+
+import junit.framework.TestCase;
+import org.hibernate.HibernateException;
+import org.hibernate.SessionFactory;
+import org.hibernate.cfg.AnnotationConfiguration;
+import org.hibernate.cfg.Environment;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class SecuredBindingTest extends TestCase {
+
+ public SecuredBindingTest(String x) {
+ super( x );
+ }
+
+ public void testConfigurationMethods() throws Exception {
+ AnnotationConfiguration ac = new AnnotationConfiguration();
+ Properties p = new Properties();
+ p.put( Environment.DIALECT, "org.hibernate.dialect.HSQLDialect" );
+ p.put( "hibernate.connection.driver_class", "org.hsqldb.jdbcDrive" );
+ p.put( "hibernate.connection.url", "jdbc:hsqldb:." );
+ p.put( "hibernate.connection.username", "sa" );
+ p.put( "hibernate.connection.password", "" );
+ p.put( "hibernate.show_sql", "true" );
+ ac.setProperties( p );
+ ac.addAnnotatedClass( Plane.class );
+ SessionFactory sf;
+ try {
+ sf = ac.buildSessionFactory();
+ fail( "Driver property overriding should work" );
+ sf.close();
+ }
+ catch (HibernateException he) {
+ //success
+ }
+
+ }
+}
+
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Sky.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Sky.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Sky.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,28 @@
+//$Id: Sky.java 16418 2009-04-23 09:55:33Z jcosta(a)redhat.com $
+package org.hibernate.test.annotations;
+
+import java.io.Serializable;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.Table;
+import javax.persistence.UniqueConstraint;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Table(name = "tbl_sky",
+ uniqueConstraints = {@UniqueConstraint(columnNames = {"month", "day"})}
+)
+public class Sky implements Serializable {
+ @Id
+ protected Long id;
+ @Column(unique = true, columnDefinition = "varchar(250)", nullable = false)
+ protected String color;
+ @Column(nullable = false)
+ protected String day;
+ @Column(name = "MONTH", nullable = false)
+ protected String month;
+ static protected String area;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/TestCase.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/TestCase.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/TestCase.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,292 @@
+//$Id: TestCase.java 17724 2009-10-13 15:47:59Z stliu $
+package org.hibernate.test.annotations;
+
+import java.io.InputStream;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.hibernate.HibernateException;
+import org.hibernate.Interceptor;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.hibernate.cfg.AnnotationConfiguration;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.cfg.Environment;
+import org.hibernate.dialect.Dialect;
+import org.hibernate.jdbc.Work;
+import org.hibernate.tool.hbm2ddl.SchemaExport;
+
+/**
+ * A base class for all tests.
+ *
+ * @author Emmnauel Bernand
+ * @author Hardy Ferentschik
+ */
+public abstract class TestCase extends junit.framework.TestCase {
+
+ public static final Logger log = LoggerFactory.getLogger( TestCase.class );
+
+ private static SessionFactory sessions;
+ private static AnnotationConfiguration cfg;
+ private static Class<?> lastTestClass;
+ private Session session;
+
+ /**
+ * The test method.
+ */
+ private Method runMethod = null;
+
+ /**
+ * Flag indicating whether the test should be run or skipped.
+ */
+ private boolean runTest = true;
+
+ /**
+ * List of required dialect for the current {@code runMethod}. If the list is empty any dialect is allowed.
+ * Otherwise the current dialect or a superclass of the current dialect must be in the list.
+ */
+ private final Set<Class<? extends Dialect>> requiredDialectList = new HashSet<Class<? extends Dialect>>();
+
+ public TestCase() {
+ super();
+ }
+
+ public TestCase(String x) {
+ super( x );
+ }
+
+ protected void buildSessionFactory(Class<?>[] classes, String[] packages, String[] xmlFiles) throws Exception {
+
+ if ( getSessions() != null ) {
+ getSessions().close();
+ }
+ try {
+ setCfg( new AnnotationConfiguration() );
+ configure( cfg );
+ if ( recreateSchema() ) {
+ cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
+ }
+ for ( String aPackage : packages ) {
+ getCfg().addPackage( aPackage );
+ }
+ for ( Class<?> aClass : classes ) {
+ getCfg().addAnnotatedClass( aClass );
+ }
+ for ( String xmlFile : xmlFiles ) {
+ InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream( xmlFile );
+ getCfg().addInputStream( is );
+ }
+ setSessions( getCfg().buildSessionFactory( /* new TestInterceptor() */ ) );
+ }
+ catch ( Exception e ) {
+ e.printStackTrace();
+ throw e;
+ }
+ }
+
+ protected void setUp() throws Exception {
+ runMethod = findTestMethod();
+ setRunTestFlag( runMethod );
+ if ( runTest ) {
+ if ( getSessions() == null || lastTestClass != getClass() ) {
+ buildSessionFactory( getMappings(), getAnnotatedPackages(), getXmlFiles() );
+ lastTestClass = getClass();
+ }
+ else {
+ runSchemaGeneration();
+ }
+ }
+ }
+
+ protected void runTest() throws Throwable {
+ try {
+ if ( runTest ) {
+ runTestMethod( runMethod );
+ handleUnclosedSession();
+ }
+ }
+ catch ( Throwable e ) {
+ closeSession( e );
+ }
+ }
+
+ private void setRunTestFlag(Method runMethod) {
+ updateRequiredDialectList( runMethod );
+
+ if ( runForCurrentDialect() ) {
+ runTest = true;
+ }
+ else {
+ log.warn(
+ "Skipping test {}, because test does not apply for dialect {}", runMethod.getName(), Dialect
+ .getDialect().getClass()
+ );
+ runTest = false;
+ }
+ }
+
+ private void updateRequiredDialectList(Method runMethod) {
+ requiredDialectList.clear();
+
+ RequiresDialect requiresDialectMethodAnn = runMethod.getAnnotation( RequiresDialect.class );
+ if ( requiresDialectMethodAnn != null ) {
+ Class<? extends Dialect>[] requiredDialects = requiresDialectMethodAnn.value();
+ requiredDialectList.addAll( Arrays.asList( requiredDialects ) );
+ }
+
+ RequiresDialect requiresDialectClassAnn = getClass().getAnnotation( RequiresDialect.class );
+ if ( requiresDialectClassAnn != null ) {
+ Class<? extends Dialect>[] requiredDialects = requiresDialectClassAnn.value();
+ requiredDialectList.addAll( Arrays.asList( requiredDialects ) );
+ }
+ }
+
+ protected boolean runForCurrentDialect() {
+ if ( requiredDialectList.isEmpty() ) {
+ return true;
+ }
+ else {
+ // check whether the current dialect is assignableFrom from any of the specified required dialects.
+ for ( Class<? extends Dialect> dialect : requiredDialectList ) {
+ if ( dialect.isAssignableFrom( Dialect.getDialect().getClass() ) ) {
+ return true;
+ }
+ }
+ return false;
+ }
+ }
+
+ private void runTestMethod(Method runMethod) throws Throwable {
+ try {
+ runMethod.invoke( this, new Class[0] );
+ }
+ catch ( InvocationTargetException e ) {
+ e.fillInStackTrace();
+ throw e.getTargetException();
+ }
+ catch ( IllegalAccessException e ) {
+ e.fillInStackTrace();
+ throw e;
+ }
+ }
+
+ private Method findTestMethod() {
+ String fName = getName();
+ assertNotNull( fName );
+ Method runMethod = null;
+ try {
+ runMethod = getClass().getMethod( fName, null );
+ }
+ catch ( NoSuchMethodException e ) {
+ fail( "Method \"" + fName + "\" not found" );
+ }
+ if ( !Modifier.isPublic( runMethod.getModifiers() ) ) {
+ fail( "Method \"" + fName + "\" should be public" );
+ }
+ return runMethod;
+ }
+
+ private void handleUnclosedSession() {
+ if ( session != null && session.isOpen() ) {
+ if ( session.isConnected() ) {
+ session.doWork( new RollbackWork() );
+ }
+ session.close();
+ session = null;
+ fail( "unclosed session" );
+ }
+ else {
+ session = null;
+ }
+ }
+
+ private void closeSession(Throwable e) throws Throwable {
+ try {
+ if ( session != null && session.isOpen() ) {
+ if ( session.isConnected() ) {
+ session.doWork( new RollbackWork() );
+ }
+ session.close();
+ }
+ }
+ catch ( Exception ignore ) {
+ }
+ try {
+ if ( sessions != null ) {
+ sessions.close();
+ sessions = null;
+ }
+ }
+ catch ( Exception ignore ) {
+ }
+ throw e;
+ }
+
+ public Session openSession() throws HibernateException {
+ session = getSessions().openSession();
+ return session;
+ }
+
+ public Session openSession(Interceptor interceptor) throws HibernateException {
+ session = getSessions().openSession( interceptor );
+ return session;
+ }
+
+ protected abstract Class<?>[] getMappings();
+
+ protected String[] getAnnotatedPackages() {
+ return new String[] { };
+ }
+
+ protected String[] getXmlFiles() {
+ return new String[] { };
+ }
+
+ private void setSessions(SessionFactory sessions) {
+ TestCase.sessions = sessions;
+ }
+
+ protected SessionFactory getSessions() {
+ return sessions;
+ }
+
+ protected Dialect getDialect() {
+ return Dialect.getDialect();
+ }
+
+ protected static void setCfg(AnnotationConfiguration cfg) {
+ TestCase.cfg = cfg;
+ }
+
+ protected static AnnotationConfiguration getCfg() {
+ return cfg;
+ }
+
+ protected void configure(Configuration cfg) {
+ }
+
+ protected boolean recreateSchema() {
+ return true;
+ }
+
+ protected void runSchemaGeneration() {
+ SchemaExport export = new SchemaExport( cfg );
+ export.create( true, true );
+ }
+
+ public class RollbackWork implements Work {
+
+ public void execute(Connection connection) throws SQLException {
+ connection.rollback();
+ }
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Thing.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Thing.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Thing.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,21 @@
+//$Id: Thing.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations;
+
+import javax.persistence.MappedSuperclass;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@MappedSuperclass
+public class Thing {
+ private boolean isAlive;
+
+ public boolean isAlive() {
+ return isAlive;
+ }
+
+ public void setAlive(boolean alive) {
+ isAlive = alive;
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Ticket.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Ticket.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/Ticket.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,58 @@
+//$Id: Ticket.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations;
+
+import java.io.Serializable;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * Flight ticket
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Ticket implements Serializable {
+ Long id;
+ String number;
+
+ public Ticket() {
+ }
+
+ @Id
+ @GeneratedValue
+ public Long getId() {
+ return id;
+ }
+
+ @Column(name = "ticket_number")
+ public String getNumber() {
+ return number;
+ }
+
+ public void setId(Long long1) {
+ id = long1;
+ }
+
+ public void setNumber(String string) {
+ number = string;
+ }
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( !( o instanceof Ticket ) ) return false;
+
+ final Ticket ticket = (Ticket) o;
+
+ if ( !number.equals( ticket.number ) ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ return number.hashCode();
+ }
+
+}
+
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/TicketComparator.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/TicketComparator.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/TicketComparator.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,20 @@
+//$Id: TicketComparator.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations;
+
+import java.util.Comparator;
+
+/**
+ * Ticket comparator ordering longest first
+ *
+ * @author Emmanuel Bernard
+ */
+public class TicketComparator implements Comparator<Ticket> {
+
+ public int compare(Ticket ticket, Ticket ticket1) {
+ if ( ticket == null || ticket1 == null ) {
+ throw new IllegalStateException( "Ticket comparison only available through non null tickets" );
+ }
+ return ticket1.getNumber().length() - ticket.getNumber().length();
+
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/access/AccessTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/access/AccessTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/access/AccessTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,128 @@
+//$Id: AccessTest.java 15025 2008-08-11 09:14:39Z hardy.ferentschik $
+package org.hibernate.test.annotations.access;
+
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class AccessTest extends TestCase {
+
+ public void testSuperclassOverriding() throws Exception {
+ Furniture fur = new Furniture();
+ fur.setColor( "Black" );
+ fur.setName( "Beech" );
+ fur.isAlive = true;
+ Session s = openSession();
+ s.persist( fur );
+ Transaction tx = s.beginTransaction();
+ tx.commit();
+ s.clear();
+ tx = s.beginTransaction();
+ fur = (Furniture) s.get( Furniture.class, fur.getId() );
+ assertFalse( fur.isAlive );
+ assertNotNull( fur.getColor() );
+ s.delete( fur );
+ tx.commit();
+ s.close();
+ }
+
+ public void testSuperclassNonOverriding() throws Exception {
+ Furniture fur = new Furniture();
+ fur.setGod( "Buddha" );
+ Session s = openSession();
+ s.persist( fur );
+ Transaction tx = s.beginTransaction();
+ tx.commit();
+ s.clear();
+ tx = s.beginTransaction();
+ fur = (Furniture) s.get( Furniture.class, fur.getId() );
+ assertNotNull( fur.getGod() );
+ s.delete( fur );
+ tx.commit();
+ s.close();
+ }
+
+ public void testPropertyOverriding() throws Exception {
+ Furniture fur = new Furniture();
+ fur.weight = 3;
+ Session s = openSession();
+ s.persist( fur );
+ Transaction tx = s.beginTransaction();
+ tx.commit();
+ s.clear();
+ tx = s.beginTransaction();
+ fur = (Furniture) s.get( Furniture.class, fur.getId() );
+ assertEquals( 5, fur.weight );
+ s.delete( fur );
+ tx.commit();
+ s.close();
+
+ }
+
+ public void testNonOverridenSubclass() throws Exception {
+ Chair chair = new Chair();
+ chair.setPillow( "Blue" );
+ Session s = openSession();
+ s.persist( chair );
+ Transaction tx = s.beginTransaction();
+ tx.commit();
+ s.clear();
+ tx = s.beginTransaction();
+ chair = (Chair) s.get( Chair.class, chair.getId() );
+ assertNull( chair.getPillow() );
+ s.delete( chair );
+ tx.commit();
+ s.close();
+
+ }
+
+ public void testOverridenSubclass() throws Exception {
+ BigBed bed = new BigBed();
+ bed.size = 5;
+ bed.setQuality( "good" );
+ Session s = openSession();
+ s.persist( bed );
+ Transaction tx = s.beginTransaction();
+ tx.commit();
+ s.clear();
+ tx = s.beginTransaction();
+ bed = (BigBed) s.get( BigBed.class, bed.getId() );
+ assertEquals( 5, bed.size );
+ assertNull( bed.getQuality() );
+ s.delete( bed );
+ tx.commit();
+ s.close();
+
+ }
+
+ public void testFieldsOverriding() throws Exception {
+ Gardenshed gs = new Gardenshed();
+ gs.floors = 4;
+ Session s = openSession();
+ s.persist( gs );
+ Transaction tx = s.beginTransaction();
+ tx.commit();
+ s.clear();
+ tx = s.beginTransaction();
+ gs = (Gardenshed) s.get( Gardenshed.class, gs.getId() );
+ assertEquals( 4, gs.floors );
+ assertEquals( 6, gs.getFloors() );
+ s.delete( gs );
+ tx.commit();
+ s.close();
+
+ }
+
+ protected Class[] getMappings() {
+ return new Class[]{
+ Bed.class,
+ Chair.class,
+ Furniture.class,
+ BigBed.class,
+ Gardenshed.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/access/Bed.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/access/Bed.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/access/Bed.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,25 @@
+//$Id: Bed.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.access;
+
+import javax.persistence.Entity;
+import javax.persistence.Transient;
+
+import org.hibernate.annotations.AccessType;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@AccessType("property")
+public class Bed extends Furniture {
+ String quality;
+
+ @Transient
+ public String getQuality() {
+ return quality;
+ }
+
+ public void setQuality(String quality) {
+ this.quality = quality;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/access/BigBed.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/access/BigBed.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/access/BigBed.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,14 @@
+//$Id: BigBed.java 15073 2008-08-14 17:32:44Z epbernard $
+package org.hibernate.test.annotations.access;
+
+import javax.persistence.Entity;
+import javax.persistence.Column;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class BigBed extends Bed {
+ @Column(name="bed_size")
+ public int size;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/access/Chair.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/access/Chair.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/access/Chair.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,23 @@
+//$Id: Chair.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.access;
+
+import javax.persistence.Entity;
+import javax.persistence.Transient;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Chair extends Furniture {
+
+ @Transient
+ private String pillow;
+
+ public String getPillow() {
+ return pillow;
+ }
+
+ public void setPillow(String pillow) {
+ this.pillow = pillow;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/access/Furniture.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/access/Furniture.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/access/Furniture.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,51 @@
+//$Id: Furniture.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.access;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.Transient;
+
+import org.hibernate.annotations.AccessType;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@AccessType("field")
+public class Furniture extends Woody {
+ @Id
+ @GeneratedValue
+ private Integer id;
+
+ private String brand;
+
+ @Transient
+ public String getBrand() {
+ return brand;
+ }
+
+ public void setBrand(String brand) {
+ this.brand = brand;
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+
+ @AccessType("property")
+ public long weight;
+
+ public long getWeight() {
+ return weight + 1;
+ }
+
+ public void setWeight(long weight) {
+ this.weight = weight + 1;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/access/Gardenshed.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/access/Gardenshed.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/access/Gardenshed.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,55 @@
+//$Id: Gardenshed.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.access;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.Transient;
+
+import org.hibernate.annotations.AccessType;
+
+/**
+ * This is the opposite of the Furniture test, as this tries to override the class AccessType("property") with
+ * the property AccessType("field").
+ *
+ * @author Dennis Fleurbaaij
+ * @since 2007-05-31
+ */
+@Entity
+@AccessType( "property" )
+public class Gardenshed
+ extends
+ Woody {
+ private Integer id;
+ private String brand;
+ public long floors;
+
+ @Transient
+ public String getBrand() {
+ return brand;
+ }
+
+ public void setBrand(String brand) {
+ this.brand = brand;
+ }
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ // These 2 functions should not return in Hibernate, but the value should come from the field "floors"
+ @AccessType( "field" )
+ public long getFloors() {
+ return this.floors + 2;
+ }
+
+ public void setFloors(long floors) {
+ this.floors = floors + 2;
+ }
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/access/Thingy.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/access/Thingy.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/access/Thingy.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,22 @@
+//$Id: Thingy.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.access;
+
+import javax.persistence.MappedSuperclass;
+import javax.persistence.Transient;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@MappedSuperclass
+public class Thingy {
+ private String god;
+
+ @Transient
+ public String getGod() {
+ return god;
+ }
+
+ public void setGod(String god) {
+ this.god = god;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/access/Woody.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/access/Woody.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/access/Woody.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,33 @@
+//$Id: Woody.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.access;
+
+import javax.persistence.MappedSuperclass;
+
+import org.hibernate.annotations.AccessType;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@MappedSuperclass
+@AccessType("property")
+public class Woody extends Thingy {
+ private String color;
+ private String name;
+ public boolean isAlive; //shouldn't be persistent
+
+ public String getColor() {
+ return color;
+ }
+
+ public void setColor(String color) {
+ this.color = color;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/AnyTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/AnyTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/AnyTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,158 @@
+package org.hibernate.test.annotations.any;
+
+import org.hibernate.Query;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.annotations.TestCase;
+
+public class AnyTest extends TestCase {
+
+ public void testDefaultAnyAssociation() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+
+ PropertySet set1 = new PropertySet( "string" );
+ Property property = new StringProperty( "name", "Alex" );
+ set1.setSomeProperty( property );
+ set1.addGeneratedProperty( property );
+ s.save( set1 );
+
+ PropertySet set2 = new PropertySet( "integer" );
+ property = new IntegerProperty( "age", 33 );
+ set2.setSomeProperty( property );
+ set2.addGeneratedProperty( property );
+ s.save( set2 );
+
+ s.flush();
+ s.clear();
+
+ Query q = s
+ .createQuery( "select s from PropertySet s where name = :name" );
+ q.setString( "name", "string" );
+ PropertySet result = (PropertySet) q.uniqueResult();
+
+ assertNotNull( result );
+ assertNotNull( result.getSomeProperty() );
+ assertTrue( result.getSomeProperty() instanceof StringProperty );
+ assertEquals( "Alex", result.getSomeProperty().asString() );
+ assertNotNull( result.getGeneralProperties() );
+ assertEquals( 1, result.getGeneralProperties().size() );
+ assertEquals( "Alex", result.getGeneralProperties().get( 0 ).asString() );
+
+ q.setString( "name", "integer" );
+ result = (PropertySet) q.uniqueResult();
+ assertNotNull( result );
+ assertNotNull( result.getSomeProperty() );
+ assertTrue( result.getSomeProperty() instanceof IntegerProperty );
+ assertEquals( "33", result.getSomeProperty().asString() );
+ assertNotNull( result.getGeneralProperties() );
+ assertEquals( 1, result.getGeneralProperties().size() );
+ assertEquals( "33", result.getGeneralProperties().get( 0 ).asString() );
+
+ t.rollback();
+ s.close();
+ }
+
+ public void testManyToAnyWithMap() throws Exception {
+
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+
+ PropertyMap map = new PropertyMap( "sample" );
+ map.getProperties().put( "name", new StringProperty( "name", "Alex" ) );
+ map.getProperties().put( "age", new IntegerProperty( "age", 33 ) );
+
+ s.save( map );
+
+ s.flush();
+ s.clear();
+
+ Query q = s
+ .createQuery( "SELECT map FROM PropertyMap map WHERE map.name = :name" );
+ q.setString( "name", "sample" );
+ PropertyMap actualMap = (PropertyMap) q.uniqueResult();
+
+ assertNotNull( actualMap );
+ assertNotNull( actualMap.getProperties() );
+
+ Property property = actualMap.getProperties().get( "name" );
+ assertNotNull( property );
+ assertTrue( property instanceof StringProperty );
+ assertEquals( "Alex", property.asString() );
+
+ property = actualMap.getProperties().get( "age" );
+ assertNotNull( property );
+ assertTrue( property instanceof IntegerProperty );
+ assertEquals( "33", property.asString() );
+
+ t.rollback();
+ s.close();
+
+ }
+
+ public void testMetaDataUseWithManyToAny() throws Exception {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+
+ PropertyList list = new PropertyList( "sample" );
+ StringProperty stringProperty = new StringProperty( "name", "Alex" );
+ IntegerProperty integerProperty = new IntegerProperty( "age", 33 );
+ LongProperty longProperty = new LongProperty( "distance", 121L );
+ CharProperty charProp = new CharProperty( "Est", 'E' );
+
+ list.setSomeProperty( longProperty );
+
+ list.addGeneratedProperty( stringProperty );
+ list.addGeneratedProperty( integerProperty );
+ list.addGeneratedProperty( longProperty );
+ list.addGeneratedProperty( charProp );
+
+ s.save( list );
+
+ s.flush();
+ s.clear();
+
+ Query q = s
+ .createQuery( "SELECT list FROM PropertyList list WHERE list.name = :name" );
+ q.setString( "name", "sample" );
+ PropertyList<Property> actualList = (PropertyList<Property>) q
+ .uniqueResult();
+
+ assertNotNull( actualList );
+ assertNotNull( actualList.getGeneralProperties() );
+ assertEquals( 4, actualList.getGeneralProperties().size() );
+
+ Property property = actualList.getSomeProperty();
+ assertNotNull( property );
+ assertTrue( property instanceof LongProperty );
+ assertEquals( "121", property.asString() );
+
+ assertEquals( "Alex", actualList.getGeneralProperties().get( 0 )
+ .asString() );
+ assertEquals( "33", actualList.getGeneralProperties().get( 1 ).asString() );
+ assertEquals( "121", actualList.getGeneralProperties().get( 2 ).asString() );
+ assertEquals( "E", actualList.getGeneralProperties().get( 3 ).asString() );
+
+ t.rollback();
+ s.close();
+ }
+
+ @Override
+ protected Class[] getMappings() {
+ return new Class[] {
+ StringProperty.class,
+ IntegerProperty.class,
+ LongProperty.class,
+ PropertySet.class,
+ PropertyMap.class,
+ PropertyList.class,
+ CharProperty.class
+ };
+ }
+
+ protected String[] getAnnotatedPackages() {
+ return new String[] {
+ "org.hibernate.test.annotations.any"
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/CharProperty.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/CharProperty.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/CharProperty.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,57 @@
+package org.hibernate.test.annotations.any;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+@Entity
+@Table( name = "char_property" )
+public class CharProperty implements Property {
+ private Integer id;
+
+ private String name;
+
+ private Character value;
+
+ public CharProperty() {
+ super();
+ }
+
+ public CharProperty(String name, Character value) {
+ super();
+ this.name = name;
+ this.value = value;
+ }
+
+ public String asString() {
+ return Character.toString( value );
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public Character getValue() {
+ return value;
+ }
+
+ public void setValue(Character value) {
+ this.value = value;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/IntegerProperty.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/IntegerProperty.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/IntegerProperty.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,56 @@
+package org.hibernate.test.annotations.any;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+@Entity
+@Table(name="int_property")
+public class IntegerProperty implements Property {
+ private Integer id;
+ private String name;
+ private Integer value;
+
+ public IntegerProperty() {
+ super();
+ }
+
+ public IntegerProperty(String name, Integer value) {
+ super();
+ this.name = name;
+ this.value = value;
+ }
+
+ public String asString() {
+ return Integer.toString(value);
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public Integer getValue() {
+ return value;
+ }
+
+ public void setValue(Integer value) {
+ this.value = value;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/LongProperty.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/LongProperty.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/LongProperty.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,57 @@
+package org.hibernate.test.annotations.any;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+@Entity
+@Table(name = "long_property")
+public class LongProperty implements Property {
+ private Integer id;
+
+ private String name;
+
+ private Long value;
+
+ public LongProperty() {
+ super();
+ }
+
+ public LongProperty(String name, Long value) {
+ super();
+ this.name = name;
+ this.value = value;
+ }
+
+ public String asString() {
+ return Long.toString(value);
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public Long getValue() {
+ return value;
+ }
+
+ public void setValue(Long value) {
+ this.value = value;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/Property.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/Property.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/Property.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,7 @@
+package org.hibernate.test.annotations.any;
+
+public interface Property {
+
+ public String getName();
+ public String asString();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/PropertyList.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/PropertyList.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/PropertyList.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,85 @@
+package org.hibernate.test.annotations.any;
+
+import java.util.ArrayList;
+import java.util.List;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.Table;
+import javax.persistence.JoinTable;
+import javax.persistence.Column;
+import javax.persistence.JoinColumn;
+
+import org.hibernate.annotations.ManyToAny;
+import org.hibernate.annotations.Cascade;
+import org.hibernate.annotations.IndexColumn;
+import org.hibernate.annotations.Any;
+import org.hibernate.annotations.CascadeType;
+
+@Entity
+@Table( name = "property_list" )
+public class PropertyList<T extends Property> {
+ private Integer id;
+
+ private String name;
+
+ private T someProperty;
+
+ private List<T> generalProperties = new ArrayList<T>();
+
+ public PropertyList() {
+ super();
+ }
+
+ public PropertyList(String name) {
+ this.name = name;
+ }
+
+ @ManyToAny( metaDef = "Property", metaColumn = @Column(name = "property_type") )
+ @Cascade( { org.hibernate.annotations.CascadeType.ALL })
+ @JoinTable(name = "list_properties",
+ joinColumns = @JoinColumn(name = "obj_id"),
+ inverseJoinColumns = @JoinColumn(name = "property_id")
+ )
+ @IndexColumn(name = "prop_index")
+ public List<T> getGeneralProperties() {
+ return generalProperties;
+ }
+
+ public void setGeneralProperties(List<T> generalProperties) {
+ this.generalProperties = generalProperties;
+ }
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @Any( metaDef = "Property", metaColumn = @Column(name = "property_type") )
+ @Cascade( CascadeType.ALL )
+ @JoinColumn(name = "property_id")
+ public T getSomeProperty() {
+ return someProperty;
+ }
+
+ public void setSomeProperty(T someProperty) {
+ this.someProperty = someProperty;
+ }
+
+ public void addGeneratedProperty(T property) {
+ this.generalProperties.add( property );
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/PropertyMap.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/PropertyMap.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/PropertyMap.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,74 @@
+package org.hibernate.test.annotations.any;
+
+import java.util.HashMap;
+import java.util.Map;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinTable;
+import javax.persistence.Table;
+
+import org.hibernate.annotations.AnyMetaDef;
+import org.hibernate.annotations.Cascade;
+import org.hibernate.annotations.ManyToAny;
+import org.hibernate.annotations.MapKey;
+import org.hibernate.annotations.MetaValue;
+
+@Entity
+@Table( name = "property_map" )
+public class PropertyMap {
+ private Integer id;
+ private String name;
+
+ private Map<String, Property> properties = new HashMap<String, Property>();
+
+ public PropertyMap(String name) {
+ this.name = name;
+ }
+
+ public PropertyMap() {
+ super();
+ }
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @ManyToAny( metaColumn = @Column( name = "property_type" ) )
+ @AnyMetaDef(
+ idType = "integer", metaType = "string",
+ metaValues = {
+ @MetaValue( value = "S", targetEntity = StringProperty.class ),
+ @MetaValue( value = "I", targetEntity = IntegerProperty.class ) } )
+ @Cascade( org.hibernate.annotations.CascadeType.ALL )
+ @JoinTable(
+ name = "map_properties",
+ joinColumns = @JoinColumn( name = "map_id" ),
+ inverseJoinColumns = @JoinColumn( name = "property_id" ) )
+ @MapKey( columns = { @Column( name = "map_key" ) } )
+ public Map<String, Property> getProperties() {
+ return properties;
+ }
+
+ public void setProperties(Map<String, Property> properties) {
+ this.properties = properties;
+ }
+
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/PropertySet.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/PropertySet.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/PropertySet.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,90 @@
+package org.hibernate.test.annotations.any;
+
+import java.util.ArrayList;
+import java.util.List;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinTable;
+import javax.persistence.Table;
+
+import org.hibernate.annotations.Any;
+import org.hibernate.annotations.AnyMetaDef;
+import org.hibernate.annotations.Cascade;
+import org.hibernate.annotations.CascadeType;
+import org.hibernate.annotations.ManyToAny;
+import org.hibernate.annotations.MetaValue;
+
+@Entity
+@Table( name = "property_set" )
+public class PropertySet {
+ private Integer id;
+ private String name;
+ private Property someProperty;
+
+ private List<Property> generalProperties = new ArrayList<Property>();
+
+ public PropertySet() {
+ super();
+ }
+
+ public PropertySet(String name) {
+ this.name = name;
+ }
+
+ @ManyToAny(
+ metaColumn = @Column( name = "property_type" ) )
+ @AnyMetaDef( idType = "integer", metaType = "string",
+ metaValues = {
+ @MetaValue( value = "S", targetEntity = StringProperty.class ),
+ @MetaValue( value = "I", targetEntity = IntegerProperty.class ) } )
+ @Cascade( { org.hibernate.annotations.CascadeType.ALL } )
+ @JoinTable( name = "obj_properties", joinColumns = @JoinColumn( name = "obj_id" ),
+ inverseJoinColumns = @JoinColumn( name = "property_id" ) )
+ public List<Property> getGeneralProperties() {
+ return generalProperties;
+ }
+
+ public void setGeneralProperties(List<Property> generalProperties) {
+ this.generalProperties = generalProperties;
+ }
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @Any( metaColumn = @Column( name = "property_type" ) )
+ @Cascade( value = { CascadeType.ALL } )
+ @AnyMetaDef( idType = "integer", metaType = "string", metaValues = {
+ @MetaValue( value = "S", targetEntity = StringProperty.class ),
+ @MetaValue( value = "I", targetEntity = IntegerProperty.class )
+ } )
+ @JoinColumn( name = "property_id" )
+ public Property getSomeProperty() {
+ return someProperty;
+ }
+
+ public void setSomeProperty(Property someProperty) {
+ this.someProperty = someProperty;
+ }
+
+ public void addGeneratedProperty(Property property) {
+ this.generalProperties.add( property );
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/StringProperty.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/StringProperty.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/StringProperty.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,54 @@
+package org.hibernate.test.annotations.any;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+@Entity
+@Table(name="string_property")
+public class StringProperty implements Property {
+ private Integer id;
+ private String name;
+ private String value;
+
+ public StringProperty() {
+ super();
+ }
+
+ public StringProperty(String name, String value) {
+ super();
+ this.name = name;
+ this.value = value;
+ }
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String asString() {
+ return value;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ public void setValue(String value) {
+ this.value = value;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/package-info.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/package-info.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/any/package-info.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,16 @@
+//$Id:
+@AnyMetaDefs(
+ @AnyMetaDef( name= "Property", metaType = "string", idType = "integer",
+ metaValues = {
+ @MetaValue(value = "C", targetEntity = CharProperty.class),
+ @MetaValue(value = "I", targetEntity = IntegerProperty.class),
+ @MetaValue(value = "S", targetEntity = StringProperty.class),
+ @MetaValue(value = "L", targetEntity = LongProperty.class)
+ })
+)
+
+package org.hibernate.test.annotations.any;
+
+import org.hibernate.annotations.AnyMetaDefs;
+import org.hibernate.annotations.AnyMetaDef;
+import org.hibernate.annotations.MetaValue;
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/array/ArrayTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/array/ArrayTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/array/ArrayTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,54 @@
+//$Id: ArrayTest.java 14956 2008-07-18 12:08:43Z hardy.ferentschik $
+package org.hibernate.test.annotations.array;
+
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.annotations.TestCase;
+import org.hibernate.test.annotations.array.Contest.Month;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class ArrayTest extends TestCase {
+
+ public void testOneToMany() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Competitor c1 = new Competitor();
+ c1.setName( "Renault" );
+ Competitor c2 = new Competitor();
+ c2.setName( "Ferrari" );
+ Contest contest = new Contest();
+ contest.setResults( new Competitor[]{c1, c2} );
+ contest.setHeldIn(new Month[]{Month.January, Month.December});
+ s.persist( contest );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ contest = (Contest) s.get( Contest.class, contest.getId() );
+ assertNotNull( contest );
+ assertNotNull( contest.getResults() );
+ assertEquals( 2, contest.getResults().length );
+ assertEquals( c2.getName(), contest.getResults()[1].getName() );
+ assertEquals( 2, contest.getHeldIn().length );
+ assertEquals( Month.January, contest.getHeldIn()[0] );
+ tx.commit();
+ s.close();
+ }
+
+ public ArrayTest(String x) {
+ super( x );
+ }
+
+ @SuppressWarnings("unchecked")
+ protected Class[] getMappings() {
+ return new Class[]{
+ Competitor.class,
+ Contest.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/array/Competitor.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/array/Competitor.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/array/Competitor.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,33 @@
+//$Id: Competitor.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.array;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Competitor {
+ private int id;
+ private String name;
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @Id
+ @GeneratedValue
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/array/Contest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/array/Contest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/array/Contest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,56 @@
+//$Id: Contest.java 14956 2008-07-18 12:08:43Z hardy.ferentschik $
+package org.hibernate.test.annotations.array;
+
+
+import javax.persistence.CascadeType;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.OneToMany;
+
+import org.hibernate.annotations.CollectionOfElements;
+import org.hibernate.annotations.IndexColumn;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Contest {
+ private int id;
+ private Competitor[] results;
+ private Month[] heldIn;
+
+ @Id
+ @GeneratedValue
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ @OneToMany(cascade = CascadeType.ALL)
+ @IndexColumn(name = "pos")
+ public Competitor[] getResults() {
+ return results;
+ }
+
+ public void setResults(Competitor[] results) {
+ this.results = results;
+ }
+
+ @CollectionOfElements
+ @IndexColumn(name = "pos", base=1)
+ public Month[] getHeldIn() {
+ return heldIn;
+ }
+
+ public void setHeldIn(Month[] heldIn) {
+ this.heldIn = heldIn;
+ }
+
+ public enum Month {
+ January, February, March, April, May, June, July, August, September, October, November, December;
+ };
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/backquotes/BackquoteTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/backquotes/BackquoteTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/backquotes/BackquoteTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,37 @@
+//$Id: BackquoteTest.java 14747 2008-06-06 08:16:25Z hardy.ferentschik $
+package org.hibernate.test.annotations.backquotes;
+
+import java.io.PrintWriter;
+import java.io.StringWriter;
+
+import junit.framework.TestCase;
+
+import org.hibernate.cfg.AnnotationConfiguration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Testcase for ANN-718 - @JoinTable / @JoinColumn fail when using backquotes in PK field name.
+ *
+ * @author Hardy Ferentschik
+ *
+ */
+public class BackquoteTest extends TestCase {
+
+ private Logger log = LoggerFactory.getLogger(BackquoteTest.class);
+
+ public void testBackquotes() {
+ try {
+ AnnotationConfiguration config = new AnnotationConfiguration();
+ config.addAnnotatedClass(Bug.class);
+ config.addAnnotatedClass(Category.class);
+ config.buildSessionFactory();
+ }
+ catch( Exception e ) {
+ StringWriter writer = new StringWriter();
+ e.printStackTrace(new PrintWriter(writer));
+ log.debug(writer.toString());
+ fail(e.getMessage());
+ }
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/backquotes/Bug.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/backquotes/Bug.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/backquotes/Bug.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,52 @@
+//$Id: Bug.java 14747 2008-06-06 08:16:25Z hardy.ferentschik $
+package org.hibernate.test.annotations.backquotes;
+
+import java.util.List;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.JoinTable;
+import javax.persistence.ManyToMany;
+
+import org.hibernate.annotations.Index;
+
+@Entity
+public class Bug
+{
+ @Id
+ @Column(name="`bug_id`")
+ private int id;
+
+ @Column(name="`title`")
+ @Index(name="`titleindex`")
+ private String title;
+
+ @ManyToMany
+ @JoinTable(name="`bug_category`")
+ private List<Category> categories;
+
+ public List<Category> getCategories() {
+ return categories;
+ }
+
+ public void setCategories(List<Category> categories) {
+ this.categories = categories;
+ }
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/backquotes/Category.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/backquotes/Category.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/backquotes/Category.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,33 @@
+//$Id: Category.java 14735 2008-06-04 14:05:50Z hardy.ferentschik $
+package org.hibernate.test.annotations.backquotes;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+@Entity
+public class Category
+{
+ @Id
+ @Column(name="`cat_id`")
+ private int id;
+
+ @Column(name="`title`")
+ private String title;
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/bytecode/Hammer.hbm.xml
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/bytecode/Hammer.hbm.xml (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/bytecode/Hammer.hbm.xml 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,12 @@
+<?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.annotations.bytecode">
+ <class name="Hammer">
+ <id name="id" type="java.lang.Long">
+ <generator class="increment"/>
+ </id>
+ </class>
+</hibernate-mapping>
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/bytecode/Hammer.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/bytecode/Hammer.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/bytecode/Hammer.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,21 @@
+//$Id: Hammer.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.bytecode;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class Hammer implements Tool {
+ private Long id;
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public Integer usage() {
+ return 0;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/bytecode/ProxyBreakingTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/bytecode/ProxyBreakingTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/bytecode/ProxyBreakingTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,52 @@
+//$Id: ProxyBreakingTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.bytecode;
+
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.Hibernate;
+import org.hibernate.test.annotations.TestCase;
+import org.hibernate.cfg.Configuration;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class ProxyBreakingTest extends TestCase {
+
+ static {
+ System.setProperty( "hibernate.bytecode.provider", "javassist" );
+ }
+
+ public void testProxiedBridgeMethod() throws Exception {
+ //bridge methods should not be proxied
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Hammer h = new Hammer();
+ s.save(h);
+ s.flush();
+ s.clear();
+ assertNotNull( "The proxy creation failure is breaking things", h.getId() );
+ h = (Hammer) s.load( Hammer.class, h.getId() );
+ assertFalse( Hibernate.isInitialized( h ) );
+ tx.rollback();
+ s.close();
+ }
+
+ public ProxyBreakingTest(String name) {
+ super( name );
+ }
+
+ protected Class[] getMappings() {
+ return new Class[0];
+ }
+
+ protected String[] getXmlFiles() {
+ return new String[] {
+ "org/hibernate/test/annotations/bytecode/Hammer.hbm.xml"
+ };
+ }
+
+ @Override
+ protected void configure(Configuration cfg) {
+ super.configure( cfg.setProperty( "hibernate.bytecode.provider", "javassist" ) );
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/bytecode/Tool.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/bytecode/Tool.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/bytecode/Tool.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,13 @@
+//$Id: Tool.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.bytecode;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public interface Tool {
+ public Long getId();
+
+ public void setId(Long id);
+
+ public Number usage();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cascade/CascadeTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cascade/CascadeTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cascade/CascadeTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,115 @@
+//$Id: CascadeTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.cascade;
+
+import java.util.ArrayList;
+
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * Check some of the individual cascade styles
+ *
+ * @author Emmanuel Bernard
+ */
+//FIXME do somthing for refresh
+public class CascadeTest extends TestCase {
+ public void testPersist() {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ Tooth tooth = new Tooth();
+ Tooth leftTooth = new Tooth();
+ tooth.leftNeighbour = leftTooth;
+ s.persist( tooth );
+ tx = s.beginTransaction();
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ leftTooth = (Tooth) s.get( Tooth.class, leftTooth.id );
+ assertNotNull( leftTooth );
+ tx.commit();
+ s.close();
+ }
+
+ public void testMerge() {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ Tooth tooth = new Tooth();
+ Tooth rightTooth = new Tooth();
+ tooth.type = "canine";
+ tooth.rightNeighbour = rightTooth;
+ rightTooth.type = "incisive";
+ s.persist( rightTooth );
+ s.persist( tooth );
+ tx = s.beginTransaction();
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ tooth = (Tooth) s.get( Tooth.class, tooth.id );
+ assertEquals( "incisive", tooth.rightNeighbour.type );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ tooth.rightNeighbour.type = "premolars";
+ s.merge( tooth );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ rightTooth = (Tooth) s.get( Tooth.class, rightTooth.id );
+ assertEquals( "premolars", rightTooth.type );
+ tx.commit();
+ s.close();
+ }
+
+ public void testRemove() {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Tooth tooth = new Tooth();
+ Mouth mouth = new Mouth();
+ s.persist( mouth );
+ s.persist( tooth );
+ tooth.mouth = mouth;
+ mouth.teeth = new ArrayList<Tooth>();
+ mouth.teeth.add( tooth );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ tooth = (Tooth) s.get( Tooth.class, tooth.id );
+ assertNotNull( tooth );
+ s.delete( tooth.mouth );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ tooth = (Tooth) s.get( Tooth.class, tooth.id );
+ assertNull( tooth );
+ tx.commit();
+ s.close();
+ }
+
+ public CascadeTest(String x) {
+ super( x );
+ }
+
+ protected Class[] getMappings() {
+ return new Class[]{
+ Mouth.class,
+ Tooth.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cascade/Mouth.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cascade/Mouth.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cascade/Mouth.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,24 @@
+//$Id: Mouth.java 15056 2008-08-13 18:15:05Z epbernard $
+package org.hibernate.test.annotations.cascade;
+
+import java.util.Collection;
+import javax.persistence.CascadeType;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.OneToMany;
+import javax.persistence.Column;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Mouth {
+ @Id
+ @GeneratedValue
+ public Integer id;
+ @Column(name="mouth_size")
+ public int size;
+ @OneToMany(mappedBy = "mouth", cascade = CascadeType.REMOVE)
+ public Collection<Tooth> teeth;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cascade/Tooth.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cascade/Tooth.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cascade/Tooth.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,25 @@
+//$Id: Tooth.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.cascade;
+
+import javax.persistence.CascadeType;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.ManyToOne;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Tooth {
+ @Id
+ @GeneratedValue
+ public Integer id;
+ public String type;
+ @ManyToOne(cascade = CascadeType.PERSIST)
+ public Tooth leftNeighbour;
+ @ManyToOne(cascade = CascadeType.MERGE)
+ public Tooth rightNeighbour;
+ @ManyToOne
+ public Mouth mouth;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/A.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/A.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/A.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,27 @@
+//$Id: A.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.cid;
+
+import java.io.Serializable;
+
+import javax.persistence.EmbeddedId;
+import javax.persistence.Entity;
+
+
+/**
+ * @author Artur Legan
+ *
+ */
+@Entity
+public class A implements Serializable{
+
+ @EmbeddedId
+ private AId aId;
+
+ public AId getAId() {
+ return aId;
+ }
+
+ public void setAId(AId aId) {
+ this.aId = aId;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/AId.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/AId.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/AId.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,40 @@
+//$Id: AId.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.cid;
+
+import java.io.Serializable;
+import javax.persistence.Embeddable;
+import javax.persistence.JoinColumn;
+import javax.persistence.OneToOne;
+
+
+/**
+ * @author Artur Legan
+ */
+@Embeddable
+public class AId implements Serializable {
+
+ @OneToOne
+ @JoinColumn( name = "bid" )
+ private B b;
+
+ @OneToOne
+ @JoinColumn( name = "cid" )
+ private C c;
+
+
+ public B getB() {
+ return b;
+ }
+
+ public void setB(B b) {
+ this.b = b;
+ }
+
+ public C getC() {
+ return c;
+ }
+
+ public void setC(C c) {
+ this.c = c;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/B.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/B.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/B.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,27 @@
+//$Id: B.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.cid;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+
+/**
+ * @author Artur Legan
+ */
+@Entity
+public class B {
+
+ @Id
+ @GeneratedValue
+ private Long id;
+
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/C.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/C.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/C.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,27 @@
+//$Id: C.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.cid;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+
+/**
+ * @author Artur Legan
+ */
+@Entity
+public class C {
+
+ @Id
+ @GeneratedValue
+ private Long id;
+
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/Channel.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/Channel.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/Channel.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,16 @@
+//$Id: Channel.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.cid;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Channel {
+ @Id
+ @GeneratedValue
+ public Integer id;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/Child.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/Child.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/Child.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,22 @@
+//$Id: Child.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.cid;
+
+import javax.persistence.AttributeOverride;
+import javax.persistence.Column;
+import javax.persistence.EmbeddedId;
+import javax.persistence.Entity;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+
+/**
+ * Entity having a many to one in its pk
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Inheritance(strategy = InheritanceType.JOINED)
+public class Child {
+ @EmbeddedId
+ @AttributeOverride(name = "nthChild", column = @Column(name = "nth"))
+ public ChildPk id;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/ChildPk.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/ChildPk.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/ChildPk.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,43 @@
+//$Id: ChildPk.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.cid;
+
+import java.io.Serializable;
+import javax.persistence.Embeddable;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinColumns;
+import javax.persistence.ManyToOne;
+
+/**
+ * Child Pk with many to one inside
+ *
+ * @author Emmanuel Bernard
+ */
+@Embeddable
+public class ChildPk implements Serializable {
+ public int nthChild;
+ @ManyToOne()
+ @JoinColumns({
+ @JoinColumn(name = "parentLastName", referencedColumnName = "p_lname"),
+ @JoinColumn(name = "parentFirstName", referencedColumnName = "firstName")
+ })
+ public Parent parent;
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( !( o instanceof ChildPk ) ) return false;
+
+ final ChildPk childPk = (ChildPk) o;
+
+ if ( nthChild != childPk.nthChild ) return false;
+ if ( !parent.equals( childPk.parent ) ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ int result;
+ result = nthChild;
+ result = 29 * result + parent.hashCode();
+ return result;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/CompositeIdTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/CompositeIdTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/CompositeIdTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,280 @@
+//$Id: CompositeIdTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.cid;
+
+import java.util.Date;
+import java.util.List;
+
+import org.hibernate.Query;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * test some composite id functionalities
+ *
+ * @author Emmanuel Bernard
+ */
+public class CompositeIdTest extends TestCase {
+ public CompositeIdTest(String x) {
+ super( x );
+ }
+
+ public void testOneToOneInCompositePk() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ B b = new B();
+ C c = new C();
+ s.persist( b );
+ s.persist( c );
+ A a = new A();
+ a.setAId( new AId() );
+ a.getAId().setB( b );
+ a.getAId().setC( c );
+ s.persist( a );
+ s.flush();
+ s.clear();
+
+ a = (A) s.get(A.class, a.getAId() );
+ assertEquals( b.getId(), a.getAId().getB().getId() );
+
+ tx.rollback();
+ s.close();
+ }
+
+
+ /**
+ * This feature is not supported by the EJB3
+ * this is an hibernate extension
+ */
+ public void testManyToOneInCompositePk() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ ParentPk ppk = new ParentPk();
+ ppk.setFirstName( "Emmanuel" );
+ ppk.setLastName( "Bernard" );
+ Parent p = new Parent();
+ p.id = ppk;
+ s.persist( p );
+ ChildPk cpk = new ChildPk();
+ cpk.parent = p;
+ cpk.nthChild = 1;
+ Child c = new Child();
+ c.id = cpk;
+ s.persist( c );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ Query q = s.createQuery( "select c from Child c where c.id.nthChild = :nth" );
+ q.setInteger( "nth", 1 );
+ List results = q.list();
+ assertEquals( 1, results.size() );
+ c = (Child) results.get( 0 );
+ assertNotNull( c );
+ assertNotNull( c.id.parent );
+ //FIXME mke it work in unambigious cases
+ // assertNotNull(c.id.parent.id);
+ // assertEquals(p.id.getFirstName(), c.id.parent.id.getFirstName());
+ s.delete( c );
+ s.delete( c.id.parent );
+ tx.commit();
+ s.close();
+ }
+
+ /**
+ * This feature is not supported by the EJB3
+ * this is an hibernate extension
+ */
+ public void testManyToOneInCompositePkAndSubclass() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ ParentPk ppk = new ParentPk();
+ ppk.setFirstName( "Emmanuel" );
+ ppk.setLastName( "Bernard" );
+ Parent p = new Parent();
+ p.id = ppk;
+ s.persist( p );
+ ChildPk cpk = new ChildPk();
+ cpk.parent = p;
+ cpk.nthChild = 1;
+ LittleGenius c = new LittleGenius();
+ c.particularSkill = "Human Annotation parser";
+ c.id = cpk;
+ s.persist( c );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ Query q = s.createQuery( "select c from Child c where c.id.nthChild = :nth" );
+ q.setInteger( "nth", 1 );
+ List results = q.list();
+ assertEquals( 1, results.size() );
+ c = (LittleGenius) results.get( 0 );
+ assertNotNull( c );
+ assertNotNull( c.id.parent );
+ //FIXME mke it work in unambigious cases
+// assertNotNull(c.id.parent.id);
+// assertEquals(p.id.getFirstName(), c.id.parent.id.getFirstName());
+ s.delete( c );
+ s.delete( c.id.parent );
+ tx.commit();
+ s.close();
+ }
+
+ public void testManyToOneInCompositeId() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Channel channel = new Channel();
+ s.persist( channel );
+ Presenter pres = new Presenter();
+ pres.name = "Casimir";
+ s.persist( pres );
+ TvMagazinPk pk = new TvMagazinPk();
+ TvMagazin mag = new TvMagazin();
+ mag.time = new Date();
+ mag.id = pk;
+ //pk.name = "Trax";
+ pk.channel = channel;
+ pk.presenter = pres;
+ s.persist( mag );
+ tx.commit();
+ s.clear();
+ tx = s.beginTransaction();
+ mag = (TvMagazin) s.createQuery( "from TvMagazin mag" ) // where mag.id.name = :name")
+ //.setParameter( "name", "Trax" )
+ .uniqueResult();
+ assertNotNull( mag.id );
+ assertNotNull( mag.id.channel );
+ assertEquals( channel.id, mag.id.channel.id );
+ assertNotNull( mag.id.presenter );
+ assertEquals( pres.name, mag.id.presenter.name );
+ s.delete( mag );
+ s.delete( mag.id.channel );
+ s.delete( mag.id.presenter );
+ tx.commit();
+ s.close();
+ }
+
+ public void testManyToOneInCompositeIdClass() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Order order = new Order();
+ s.persist( order );
+ Product product = new Product();
+ product.name = "small car";
+ s.persist( product );
+ OrderLinePk pk = new OrderLinePk();
+ OrderLine orderLine = new OrderLine();
+ orderLine.order = order;
+ orderLine.product = product;
+ s.persist( orderLine );
+ s.flush();
+ s.clear();
+
+ orderLine = (OrderLine) s.createQuery( "select ol from OrderLine ol" ).uniqueResult();
+ assertNotNull( orderLine.order );
+ assertEquals( order.id, orderLine.order.id );
+ assertNotNull( orderLine.product );
+ assertEquals( product.name, orderLine.product.name );
+
+ tx.rollback();
+ s.close();
+ }
+
+ public void testSecondaryTableWithCompositeId() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Channel channel = new Channel();
+ s.persist( channel );
+ Presenter pres = new Presenter();
+ pres.name = "Tim Russet";
+ s.persist( pres );
+ TvMagazinPk pk = new TvMagazinPk();
+ TvProgram program = new TvProgram();
+ program.time = new Date();
+ program.id = pk;
+ program.text = "Award Winning Programming";
+ //pk.name = "Trax";
+ pk.channel = channel;
+ pk.presenter = pres;
+ s.persist( program );
+ tx.commit();
+ s.clear();
+ tx = s.beginTransaction();
+ program = (TvProgram) s.createQuery( "from TvProgram pr" ) // where mag.id.name = :name")
+ //.setParameter( "name", "Trax" )
+ .uniqueResult();
+ assertNotNull( program.id );
+ assertNotNull( program.id.channel );
+ assertEquals( channel.id, program.id.channel.id );
+ assertNotNull( program.id.presenter );
+ assertNotNull( program.text );
+ assertEquals( pres.name, program.id.presenter.name );
+ s.delete( program );
+ s.delete( program.id.channel );
+ s.delete( program.id.presenter );
+ tx.commit();
+ s.close();
+ }
+
+ public void testSecondaryTableWithIdClass() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Channel channel = new Channel();
+ s.persist( channel );
+ Presenter pres = new Presenter();
+ pres.name = "Bob";
+ s.persist( pres );
+ TvProgramIdClass program = new TvProgramIdClass();
+ program.time = new Date();
+ program.channel = channel;
+ program.presenter = pres;
+ program.text = "Jump the shark programming";
+ //pk.name = "Trax";
+ s.persist( program );
+ tx.commit();
+ s.clear();
+ tx = s.beginTransaction();
+ program = (TvProgramIdClass) s.createQuery( "from TvProgramIdClass pr" ) // where mag.id.name = :name")
+ //.setParameter( "name", "Trax" )
+ .uniqueResult();
+ assertNotNull( program.channel );
+ assertEquals( channel.id, program.channel.id );
+ assertNotNull( program.presenter );
+ assertNotNull( program.text );
+ assertEquals( pres.name, program.presenter.name );
+ s.delete( program );
+ s.delete( program.channel );
+ s.delete( program.presenter );
+ tx.commit();
+ s.close();
+ }
+
+ protected Class[] getMappings() {
+ return new Class[] {
+ Parent.class,
+ Child.class,
+ Channel.class,
+ TvMagazin.class,
+ TvProgramIdClass.class,
+ TvProgram.class,
+ Presenter.class,
+ Order.class,
+ Product.class,
+ OrderLine.class,
+ OrderLinePk.class,
+ LittleGenius.class,
+ A.class,
+ B.class,
+ C.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/LittleGenius.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/LittleGenius.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/LittleGenius.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,19 @@
+package org.hibernate.test.annotations.cid;
+
+import javax.persistence.Entity;
+import javax.persistence.PrimaryKeyJoinColumn;
+import javax.persistence.PrimaryKeyJoinColumns;
+
+/**
+ * Hierarchy with cid + many to one
+ * @author Anthony
+ *
+ */
+@Entity
+@PrimaryKeyJoinColumns({
+@PrimaryKeyJoinColumn(name = "nthChild"),
+@PrimaryKeyJoinColumn(name = "parentLastName"),
+@PrimaryKeyJoinColumn(name = "parentFirstName")})
+public class LittleGenius extends Child {
+ public String particularSkill;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/Order.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/Order.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/Order.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,17 @@
+package org.hibernate.test.annotations.cid;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Table;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Table(name = "OrderTableFoobar")
+public class Order {
+ @Id
+ @GeneratedValue
+ public Integer id;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/OrderLine.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/OrderLine.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/OrderLine.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,17 @@
+package org.hibernate.test.annotations.cid;
+
+import javax.persistence.Entity;
+import javax.persistence.IdClass;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+(a)IdClass(OrderLinePk.class)
+public class OrderLine {
+ @Id
+ public Order order;
+ @Id
+ public Product product;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/OrderLinePk.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/OrderLinePk.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/OrderLinePk.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,18 @@
+package org.hibernate.test.annotations.cid;
+
+
+import javax.persistence.ManyToOne;
+import javax.persistence.JoinColumn;
+import java.io.Serializable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class OrderLinePk implements Serializable {
+ @ManyToOne
+ @JoinColumn(name = "foo", nullable = false)
+ public Order order;
+ @ManyToOne
+ @JoinColumn(name = "bar", nullable = false)
+ public Product product;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/Parent.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/Parent.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/Parent.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,31 @@
+//$Id: Parent.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.cid;
+
+import javax.persistence.EmbeddedId;
+import javax.persistence.Entity;
+
+/**
+ * Entity with composite id
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Parent {
+ @EmbeddedId
+ public ParentPk id;
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( !( o instanceof Parent ) ) return false;
+
+ final Parent parent = (Parent) o;
+
+ if ( !id.equals( parent.id ) ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ return id.hashCode();
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/ParentPk.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/ParentPk.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/ParentPk.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,52 @@
+//$Id: ParentPk.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.cid;
+
+import java.io.Serializable;
+import javax.persistence.Column;
+
+/**
+ * @author Emmanuel Bernard
+ */
+
+public class ParentPk implements Serializable {
+ public String getFirstName() {
+ return firstName;
+ }
+
+ public void setFirstName(String firstName) {
+ this.firstName = firstName;
+ }
+
+
+ public String getLastName() {
+ return lastName;
+ }
+
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+
+
+ private String firstName;
+ @Column(name = "p_lname")
+ private String lastName;
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( !( o instanceof ParentPk ) ) return false;
+
+ final ParentPk parentPk = (ParentPk) o;
+
+ if ( !firstName.equals( parentPk.firstName ) ) return false;
+ if ( !lastName.equals( parentPk.lastName ) ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ int result;
+ result = firstName.hashCode();
+ result = 29 * result + lastName.hashCode();
+ return result;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/Presenter.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/Presenter.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/Presenter.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,14 @@
+//$Id: Presenter.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.cid;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Presenter {
+ @Id
+ public String name;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/Product.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/Product.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/Product.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,13 @@
+package org.hibernate.test.annotations.cid;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Product {
+ @Id
+ public String name;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/TvMagazin.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/TvMagazin.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/TvMagazin.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,22 @@
+//$Id: TvMagazin.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.cid;
+
+import java.util.Date;
+import javax.persistence.AssociationOverride;
+import javax.persistence.EmbeddedId;
+import javax.persistence.Entity;
+import javax.persistence.JoinColumn;
+import javax.persistence.Temporal;
+import javax.persistence.TemporalType;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@AssociationOverride(name = "id.channel", joinColumns = @JoinColumn(name = "chan_id"))
+public class TvMagazin {
+ @EmbeddedId
+ public TvMagazinPk id;
+ @Temporal(TemporalType.TIME)
+ Date time;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/TvMagazinPk.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/TvMagazinPk.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/TvMagazinPk.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,18 @@
+//$Id: TvMagazinPk.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.cid;
+
+import java.io.Serializable;
+import javax.persistence.Embeddable;
+import javax.persistence.ManyToOne;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Embeddable
+public class TvMagazinPk implements Serializable {
+ @ManyToOne
+ public Channel channel;
+ //public String name;
+ @ManyToOne
+ public Presenter presenter;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/TvProgram.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/TvProgram.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/TvProgram.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,31 @@
+//$Id: TvProgram.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.cid;
+
+import java.util.Date;
+import javax.persistence.Column;
+import javax.persistence.EmbeddedId;
+import javax.persistence.Entity;
+import javax.persistence.PrimaryKeyJoinColumn;
+import javax.persistence.SecondaryTable;
+import javax.persistence.Temporal;
+import javax.persistence.TemporalType;
+
+/**
+ * @author Chandra Patni
+ */
+@Entity
+@SecondaryTable( name = "TV_PROGRAM_EXT", pkJoinColumns = {
+@PrimaryKeyJoinColumn( name = "CHANNEL_ID" ),
+@PrimaryKeyJoinColumn( name = "PRESENTER_NAME" )
+ } )
+public class TvProgram {
+ @EmbeddedId
+ public TvMagazinPk id;
+
+ @Temporal( TemporalType.TIME )
+ Date time;
+
+ @Column( name = "TXT", table = "TV_PROGRAM_EXT" )
+ public String text;
+
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/TvProgramIdClass.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/TvProgramIdClass.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/cid/TvProgramIdClass.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,34 @@
+//$Id: TvProgramIdClass.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.cid;
+
+import java.util.Date;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.IdClass;
+import javax.persistence.PrimaryKeyJoinColumn;
+import javax.persistence.SecondaryTable;
+import javax.persistence.Temporal;
+import javax.persistence.TemporalType;
+
+@Entity
+@SecondaryTable( name = "TV_PROGRAM_IDCLASS", pkJoinColumns =
+ {
+ @PrimaryKeyJoinColumn( name = "CHANNEL_ID" ),
+ @PrimaryKeyJoinColumn( name = "PRESENTER_NAME" )
+ } )
+@IdClass( TvMagazinPk.class )
+public class TvProgramIdClass {
+ @Id
+ public Channel channel;
+ @Id
+ public Presenter presenter;
+
+ @Temporal( TemporalType.TIME )
+ Date time;
+
+ @Column( name = "TXT", table = "TV_PROGRAM_IDCLASS" )
+ public String text;
+}
+
+
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/Boy.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/Boy.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/Boy.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,134 @@
+//$Id: Boy.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.collectionelement;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import javax.persistence.AttributeOverride;
+import javax.persistence.AttributeOverrides;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.EnumType;
+import javax.persistence.Enumerated;
+import javax.persistence.FetchType;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinTable;
+
+import org.hibernate.annotations.CollectionOfElements;
+import org.hibernate.annotations.IndexColumn;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@AttributeOverrides({
+ @AttributeOverride( name="characters.element", column = @Column(name="fld_character") ),
+ @AttributeOverride( name="scorePerNickName.element", column = @Column(name="fld_score") ),
+ @AttributeOverride( name="favoriteToys.element.brand.surname", column = @Column(name = "fld_surname"))}
+)
+public class Boy {
+ private Integer id;
+ private String firstName;
+ private String lastName;
+ private Set<String> nickNames = new HashSet<String>();
+ private Map<String, Integer> scorePerNickName = new HashMap<String, Integer>();
+ private int[] favoriteNumbers;
+ private Set<Toy> favoriteToys = new HashSet<Toy>();
+ private Set<Character> characters = new HashSet<Character>();
+ private Set<CountryAttitude> countryAttitudes = new HashSet<CountryAttitude>();
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getFirstName() {
+ return firstName;
+ }
+
+ public void setFirstName(String firstName) {
+ this.firstName = firstName;
+ }
+
+ public String getLastName() {
+ return lastName;
+ }
+
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+
+ @CollectionOfElements
+ public Set<String> getNickNames() {
+ return nickNames;
+ }
+
+ public void setNickNames(Set<String> nickName) {
+ this.nickNames = nickName;
+ }
+
+ @CollectionOfElements
+ @JoinTable(name = "ScorePerNickName", joinColumns = @JoinColumn(name = "BoyId"))
+ @Column(name = "score", nullable = false)
+ public Map<String, Integer> getScorePerNickName() {
+ return scorePerNickName;
+ }
+
+ public void setScorePerNickName(Map<String, Integer> scorePerNickName) {
+ this.scorePerNickName = scorePerNickName;
+ }
+
+ @CollectionOfElements
+ @JoinTable(
+ name = "BoyFavoriteNumbers",
+ joinColumns = @JoinColumn(name = "BoyId")
+ )
+ @Column(name = "favoriteNumber", nullable = false)
+ @IndexColumn(name = "nbr_index")
+ public int[] getFavoriteNumbers() {
+ return favoriteNumbers;
+ }
+
+ public void setFavoriteNumbers(int[] favoriteNumbers) {
+ this.favoriteNumbers = favoriteNumbers;
+ }
+
+ @CollectionOfElements
+ @AttributeOverride(name = "element.serial", column = @Column(name = "serial_nbr"))
+ public Set<Toy> getFavoriteToys() {
+ return favoriteToys;
+ }
+
+ public void setFavoriteToys(Set<Toy> favoriteToys) {
+ this.favoriteToys = favoriteToys;
+ }
+
+ @CollectionOfElements
+ @Enumerated(EnumType.STRING)
+ public Set<Character> getCharacters() {
+ return characters;
+ }
+
+ public void setCharacters(Set<Character> characters) {
+ this.characters = characters;
+ }
+
+ @CollectionOfElements(fetch = FetchType.EAGER)
+ //@Where(clause = "b_likes=false")
+ public Set<CountryAttitude> getCountryAttitudes() {
+ return countryAttitudes;
+ }
+
+ public void setCountryAttitudes(Set<CountryAttitude> countryAttitudes) {
+ this.countryAttitudes = countryAttitudes;
+ }
+}
+
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/Brand.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/Brand.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/Brand.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,44 @@
+//$Id: Brand.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.collectionelement;
+
+import javax.persistence.Embeddable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Embeddable
+public class Brand {
+ private String name;
+ private String surname;
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getSurname() {
+ return surname;
+ }
+
+ public void setSurname(String surname) {
+ this.surname = surname;
+ }
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( o == null || getClass() != o.getClass() ) return false;
+
+ final Brand brand = (Brand) o;
+
+ if ( !name.equals( brand.name ) ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ return name.hashCode();
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/Character.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/Character.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/Character.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,13 @@
+package org.hibernate.test.annotations.collectionelement;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public enum Character {
+ GENTLE,
+ NORMAL,
+ AGGRESSIVE,
+ ATTENTIVE,
+ VIOLENT,
+ CRAFTY
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/CollectionElementTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/CollectionElementTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/CollectionElementTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,213 @@
+//$Id: CollectionElementTest.java 14754 2008-06-09 15:57:07Z hardy.ferentschik $
+package org.hibernate.test.annotations.collectionelement;
+
+import java.util.List;
+import java.util.Locale;
+
+import org.hibernate.Filter;
+import org.hibernate.Query;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.annotations.Country;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * @author Emmanuel Bernard
+ * @author Hardy Ferentschik
+ */
+@SuppressWarnings("unchecked")
+public class CollectionElementTest extends TestCase {
+
+ public void testSimpleElement() throws Exception {
+ assertEquals(
+ "BoyFavoriteNumbers",
+ getCfg().getCollectionMapping( Boy.class.getName() + '.' + "favoriteNumbers" )
+ .getCollectionTable().getName()
+ );
+ Session s = openSession();
+ s.getTransaction().begin();
+ Boy boy = new Boy();
+ boy.setFirstName( "John" );
+ boy.setLastName( "Doe" );
+ boy.getNickNames().add( "Johnny" );
+ boy.getNickNames().add( "Thing" );
+ boy.getScorePerNickName().put( "Johnny", new Integer( 3 ) );
+ boy.getScorePerNickName().put( "Thing", new Integer( 5 ) );
+ int[] favNbrs = new int[4];
+ for (int index = 0; index < favNbrs.length - 1; index++) {
+ favNbrs[index] = index * 3;
+ }
+ boy.setFavoriteNumbers( favNbrs );
+ boy.getCharacters().add( Character.GENTLE );
+ boy.getCharacters().add( Character.CRAFTY );
+ s.persist( boy );
+ s.getTransaction().commit();
+ s.clear();
+ Transaction tx = s.beginTransaction();
+ boy = (Boy) s.get( Boy.class, boy.getId() );
+ assertNotNull( boy.getNickNames() );
+ assertTrue( boy.getNickNames().contains( "Thing" ) );
+ assertNotNull( boy.getScorePerNickName() );
+ assertTrue( boy.getScorePerNickName().containsKey( "Thing" ) );
+ assertEquals( new Integer( 5 ), boy.getScorePerNickName().get( "Thing" ) );
+ assertNotNull( boy.getFavoriteNumbers() );
+ assertEquals( 3, boy.getFavoriteNumbers()[1] );
+ assertTrue( boy.getCharacters().contains( Character.CRAFTY ) );
+ List result = s.createQuery( "select boy from Boy boy join boy.nickNames names where names = :name" )
+ .setParameter( "name", "Thing" ).list();
+ assertEquals( 1, result.size() );
+ s.delete( boy );
+ tx.commit();
+ s.close();
+ }
+
+ public void testCompositeElement() throws Exception {
+ Session s = openSession();
+ s.getTransaction().begin();
+ Boy boy = new Boy();
+ boy.setFirstName( "John" );
+ boy.setLastName( "Doe" );
+ Toy toy = new Toy();
+ toy.setName( "Balloon" );
+ toy.setSerial( "serial001" );
+ toy.setBrand( new Brand() );
+ toy.getBrand().setName( "Bandai" );
+ boy.getFavoriteToys().add( toy );
+ s.persist( boy );
+ s.getTransaction().commit();
+ s.clear();
+ Transaction tx = s.beginTransaction();
+ boy = (Boy) s.get( Boy.class, boy.getId() );
+ assertNotNull( boy.getFavoriteToys() );
+ assertTrue( boy.getFavoriteToys().contains( toy ) );
+ assertEquals( "@Parent is failing", boy, boy.getFavoriteToys().iterator().next().getOwner() );
+ s.delete( boy );
+ tx.commit();
+ s.close();
+ }
+
+ public void testAttributedJoin() throws Exception {
+ Session s = openSession();
+ s.getTransaction().begin();
+ Country country = new Country();
+ country.setName( "Australia" );
+ s.persist( country );
+
+ Boy boy = new Boy();
+ boy.setFirstName( "John" );
+ boy.setLastName( "Doe" );
+ CountryAttitude attitude = new CountryAttitude();
+ // TODO: doesn't work
+ attitude.setBoy( boy );
+ attitude.setCountry( country );
+ attitude.setLikes( true );
+ boy.getCountryAttitudes().add( attitude );
+ s.persist( boy );
+ s.getTransaction().commit();
+ s.clear();
+
+ Transaction tx = s.beginTransaction();
+ boy = (Boy) s.get( Boy.class, boy.getId() );
+ assertTrue( boy.getCountryAttitudes().contains( attitude ) );
+ s.delete( boy );
+ s.delete( s.get( Country.class, country.getId() ) );
+ tx.commit();
+ s.close();
+
+ }
+
+ public void testLazyCollectionofElements() throws Exception {
+ assertEquals(
+ "BoyFavoriteNumbers",
+ getCfg().getCollectionMapping( Boy.class.getName() + '.' + "favoriteNumbers" )
+ .getCollectionTable().getName()
+ );
+ Session s = openSession();
+ s.getTransaction().begin();
+ Boy boy = new Boy();
+ boy.setFirstName( "John" );
+ boy.setLastName( "Doe" );
+ boy.getNickNames().add( "Johnny" );
+ boy.getNickNames().add( "Thing" );
+ boy.getScorePerNickName().put( "Johnny", new Integer( 3 ) );
+ boy.getScorePerNickName().put( "Thing", new Integer( 5 ) );
+ int[] favNbrs = new int[4];
+ for (int index = 0; index < favNbrs.length - 1; index++) {
+ favNbrs[index] = index * 3;
+ }
+ boy.setFavoriteNumbers( favNbrs );
+ boy.getCharacters().add( Character.GENTLE );
+ boy.getCharacters().add( Character.CRAFTY );
+ s.persist( boy );
+ s.getTransaction().commit();
+ s.clear();
+ Transaction tx = s.beginTransaction();
+ boy = (Boy) s.get( Boy.class, boy.getId() );
+ assertNotNull( boy.getNickNames() );
+ assertTrue( boy.getNickNames().contains( "Thing" ) );
+ assertNotNull( boy.getScorePerNickName() );
+ assertTrue( boy.getScorePerNickName().containsKey( "Thing" ) );
+ assertEquals( new Integer( 5 ), boy.getScorePerNickName().get( "Thing" ) );
+ assertNotNull( boy.getFavoriteNumbers() );
+ assertEquals( 3, boy.getFavoriteNumbers()[1] );
+ assertTrue( boy.getCharacters().contains( Character.CRAFTY ) );
+ List result = s.createQuery( "select boy from Boy boy join boy.nickNames names where names = :name" )
+ .setParameter( "name", "Thing" ).list();
+ assertEquals( 1, result.size() );
+ s.delete( boy );
+ tx.commit();
+ s.close();
+ }
+
+ public void testFetchEagerAndFilter() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+
+ TestCourse test = new TestCourse();
+
+ LocalizedString title = new LocalizedString( "title in english" );
+ title.getVariations().put( Locale.FRENCH.getLanguage(), "title en francais" );
+ test.setTitle( title );
+ s.save( test );
+
+ s.flush();
+ s.clear();
+
+ Filter filter = s.enableFilter( "selectedLocale" );
+ filter.setParameter( "param", "fr" );
+
+ Query q = s.createQuery( "from TestCourse t" );
+ List l = q.list();
+ assertEquals( 1, l.size() );
+
+ TestCourse t = (TestCourse) s.get( TestCourse.class, test.getTestCourseId() );
+ assertEquals( 1, t.getTitle().getVariations().size() );
+
+ tx.rollback();
+
+ s.close();
+ }
+
+ public void testMapKeyType() throws Exception {
+ Matrix m = new Matrix();
+ m.getValues().put( 1, 1.1f );
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ s.persist( m );
+ s.flush();
+ s.clear();
+ m = (Matrix) s.get( Matrix.class, m.getId() );
+ assertEquals( 1.1f, m.getValues().get( 1 ) );
+ tx.rollback();
+ s.close();
+ }
+
+ protected Class[] getMappings() {
+ return new Class[] {
+ Boy.class,
+ Country.class,
+ TestCourse.class,
+ Matrix.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/CountryAttitude.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/CountryAttitude.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/CountryAttitude.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,59 @@
+//$Id: CountryAttitude.java 14754 2008-06-09 15:57:07Z hardy.ferentschik $
+package org.hibernate.test.annotations.collectionelement;
+
+import javax.persistence.Column;
+import javax.persistence.Embeddable;
+import javax.persistence.ManyToOne;
+
+import org.hibernate.test.annotations.Country;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Embeddable
+public class CountryAttitude {
+ private Boy boy;
+ private Country country;
+ private boolean likes;
+
+ // TODO: This currently does not work
+// @ManyToOne(optional = false)
+// public Boy getBoy() {
+// return boy;
+// }
+
+ public void setBoy(Boy boy) {
+ this.boy = boy;
+ }
+
+ @ManyToOne(optional = false)
+ public Country getCountry() {
+ return country;
+ }
+
+ public void setCountry(Country country) {
+ this.country = country;
+ }
+
+ @Column(name = "b_likes")
+ public boolean isLikes() {
+ return likes;
+ }
+
+ public void setLikes(boolean likes) {
+ this.likes = likes;
+ }
+
+ @Override
+ public int hashCode() {
+ return country.hashCode();
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if ( !( obj instanceof CountryAttitude ) ) {
+ return false;
+ }
+ return country.equals( ( (CountryAttitude) obj ).country );
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/LocalizedString.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/LocalizedString.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/LocalizedString.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,47 @@
+//$Id: LocalizedString.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.collectionelement;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Locale;
+import java.io.Serializable;
+import javax.persistence.Column;
+import javax.persistence.Embeddable;
+
+import org.hibernate.annotations.CollectionOfElements;
+import org.hibernate.annotations.Fetch;
+import org.hibernate.annotations.MapKey;
+import org.hibernate.annotations.FetchMode;
+import org.hibernate.annotations.Filter;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Embeddable
+public class LocalizedString implements Serializable {
+
+ private static final Locale DEFAULT_LOCALE = Locale.ENGLISH;
+
+ public LocalizedString() {
+ }
+
+ public LocalizedString(String string) {
+ this.getVariations().put( DEFAULT_LOCALE.getLanguage(), string );
+ }
+
+ private Map<String, String> variations =
+ new HashMap<String, String>( 1 );
+
+ @CollectionOfElements
+ @MapKey( columns = @Column( name = "language_code" ) )
+ @Fetch( FetchMode.JOIN )
+ @Filter( name = "selectedLocale",
+ condition = " language_code = :param " )
+ public Map<String, String> getVariations() {
+ return variations;
+ }
+
+ public void setVariations(Map<String, String> variations) {
+ this.variations = variations;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/Matrix.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/Matrix.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/Matrix.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,48 @@
+//$
+package org.hibernate.test.annotations.collectionelement;
+
+import java.util.Map;
+import java.util.SortedMap;
+import java.util.TreeMap;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+import org.hibernate.annotations.CollectionOfElements;
+import org.hibernate.annotations.MapKey;
+import org.hibernate.annotations.Sort;
+import org.hibernate.annotations.SortType;
+import org.hibernate.annotations.Type;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Matrix {
+ @Id
+ @GeneratedValue
+ private Integer id;
+
+ @MapKey(type = @Type(type="integer") )
+ @CollectionOfElements
+ @Sort(type = SortType.NATURAL)
+ @Type(type = "float")
+ private SortedMap<Integer, Float> values = new TreeMap<Integer, Float>();
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public Map<Integer, Float> getValues() {
+ return values;
+ }
+
+ public void setValues(SortedMap<Integer, Float> values) {
+ this.values = values;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/TestCourse.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/TestCourse.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/TestCourse.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,42 @@
+//$Id: TestCourse.java 14754 2008-06-09 15:57:07Z hardy.ferentschik $
+package org.hibernate.test.annotations.collectionelement;
+
+import javax.persistence.Embedded;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+
+import org.hibernate.annotations.FilterDef;
+import org.hibernate.annotations.ParamDef;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@FilterDef(name="selectedLocale", parameters={ @ParamDef( name="param", type="string" ) } )
+public class TestCourse {
+
+ private Long testCourseId;
+
+ private LocalizedString title;
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ public Long getTestCourseId() {
+ return testCourseId;
+ }
+
+ public void setTestCourseId(Long testCourseId) {
+ this.testCourseId = testCourseId;
+ }
+
+ @Embedded
+ public LocalizedString getTitle() {
+ return title;
+ }
+
+ public void setTitle(LocalizedString title) {
+ this.title = title;
+ }
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/Toy.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/Toy.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/Toy.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,73 @@
+//$Id: Toy.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.collectionelement;
+
+import javax.persistence.AttributeOverride;
+import javax.persistence.Column;
+import javax.persistence.Embeddable;
+
+import org.hibernate.annotations.Parent;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Embeddable
+public class Toy {
+ private String name;
+ private Brand brand;
+ private String serial;
+ private Boy owner;
+
+ @AttributeOverride(name = "name", column = @Column(name = "brand_name"))
+ public Brand getBrand() {
+ return brand;
+ }
+
+ public void setBrand(Brand brand) {
+ this.brand = brand;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getSerial() {
+ return serial;
+ }
+
+ public void setSerial(String serial) {
+ this.serial = serial;
+ }
+
+ @Parent
+ public Boy getOwner() {
+ return owner;
+ }
+
+ public void setOwner(Boy owner) {
+ this.owner = owner;
+ }
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( o == null || getClass() != o.getClass() ) return false;
+
+ final Toy toy = (Toy) o;
+
+ if ( !brand.equals( toy.brand ) ) return false;
+ if ( !name.equals( toy.name ) ) return false;
+ if ( !serial.equals( toy.serial ) ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ int result;
+ result = name.hashCode();
+ result = 29 * result + brand.hashCode();
+ return result;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/A.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/A.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/A.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,45 @@
+//$
+package org.hibernate.test.annotations.collectionelement.deepcollectionelements;
+
+/**
+ * @author Emmanuel Bernard
+ */
+
+import java.util.List;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.SequenceGenerator;
+import javax.persistence.Table;
+
+import org.hibernate.annotations.CollectionOfElements;
+import org.hibernate.annotations.IndexColumn;
+
+@Entity
+@Table( name = "A" )
+public class A {
+ @Id
+ @GeneratedValue( strategy = GenerationType.SEQUENCE, generator = "aSequence" )
+ @SequenceGenerator( name = "aSequence", sequenceName = "seq_A" )
+ private int id;
+ @CollectionOfElements
+ @IndexColumn( name = "ndx" )
+ private List<B> listOfB;
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ public List<B> getListOfB() {
+ return listOfB;
+ }
+
+ public void setListOfB(List<B> listOfB) {
+ this.listOfB = listOfB;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/B.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/B.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/B.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,36 @@
+//$
+package org.hibernate.test.annotations.collectionelement.deepcollectionelements;
+
+import java.util.List;
+import javax.persistence.Embeddable;
+import javax.persistence.Transient;
+import javax.persistence.OneToMany;
+
+import org.hibernate.annotations.CollectionOfElements;
+import org.hibernate.annotations.IndexColumn;
+
+@Embeddable
+public class B {
+ private String name;
+
+ //@CollectionOfElements
+ @OneToMany
+ @IndexColumn( name = "ndx" )
+ private List<C> listOfC;
+
+ public List<C> getListOfC() {
+ return listOfC;
+ }
+
+ public void setListOfC(List<C> listOfC) {
+ this.listOfC = listOfC;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/C.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/C.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/C.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,27 @@
+//$
+package org.hibernate.test.annotations.collectionelement.deepcollectionelements;
+
+import javax.persistence.Column;
+import javax.persistence.Embeddable;
+import javax.persistence.Id;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Entity;
+
+
+@Entity
+public class C {
+ @Id
+ @GeneratedValue
+ private int id;
+
+ @Column( length = 500 )
+ private String comment;
+
+ public String getComment() {
+ return comment;
+ }
+
+ public void setComment(String comment) {
+ this.comment = comment;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/DeepCollectionElementTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/DeepCollectionElementTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/deepcollectionelements/DeepCollectionElementTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,25 @@
+//$
+package org.hibernate.test.annotations.collectionelement.deepcollectionelements;
+
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * @author Emmanuel Bernard
+ */
+
+//TEST not used: wait for ANN-591 and HHH-3157
+public class DeepCollectionElementTest extends TestCase {
+
+ public void testInitialization() throws Exception {
+ //test only the SF creation
+
+ }
+
+ protected Class[] getMappings() {
+ return new Class[] {
+ //A.class,
+ //B.class,
+ //C.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/indexedCollection/Contact.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/indexedCollection/Contact.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/indexedCollection/Contact.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,20 @@
+//$
+package org.hibernate.test.annotations.collectionelement.indexedCollection;
+
+import javax.persistence.Embeddable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Embeddable
+public class Contact {
+ private String name;
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/indexedCollection/IndexedCollectionOfElementsTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/indexedCollection/IndexedCollectionOfElementsTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/indexedCollection/IndexedCollectionOfElementsTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,32 @@
+//$
+package org.hibernate.test.annotations.collectionelement.indexedCollection;
+
+import org.hibernate.test.annotations.TestCase;
+import org.hibernate.Session;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class IndexedCollectionOfElementsTest extends TestCase {
+
+ public void testIndexedCollectionOfElements() throws Exception {
+ Sale sale = new Sale();
+ Contact contact = new Contact();
+ contact.setName( "Emmanuel" );
+ sale.getContacts().add(contact);
+ Session s = openSession( );
+ s.getTransaction().begin();
+ s.save( sale );
+ s.flush();
+ s.get( Sale.class, sale.getId() );
+ assertEquals( 1, sale.getContacts().size() );
+ s.getTransaction().rollback();
+ s.close();
+ }
+
+ protected Class[] getMappings() {
+ return new Class[] {
+ Sale.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/indexedCollection/Sale.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/indexedCollection/Sale.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/collectionelement/indexedCollection/Sale.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,51 @@
+//$
+package org.hibernate.test.annotations.collectionelement.indexedCollection;
+
+import java.util.List;
+import java.util.ArrayList;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.GeneratedValue;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinTable;
+import javax.persistence.Column;
+
+import org.hibernate.annotations.Type;
+import org.hibernate.annotations.CollectionOfElements;
+import org.hibernate.annotations.CollectionId;
+import org.hibernate.annotations.GenericGenerator;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@GenericGenerator(name="increment", strategy = "increment")
+public class Sale {
+ @Id @GeneratedValue private Integer id;
+
+ @CollectionOfElements
+ @JoinTable(
+ name = "contact",
+ joinColumns = @JoinColumn(name = "n_key_person"))
+ @CollectionId(
+ columns = @Column(name = "n_key_contact"),
+ type = @Type(type = "long"),
+ generator = "increment" )
+ private List<Contact> contacts = new ArrayList<Contact>();
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public List<Contact> getContacts() {
+ return contacts;
+ }
+
+ public void setContacts(List<Contact> contacts) {
+ this.contacts = contacts;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/configuration/ConfigurationTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/configuration/ConfigurationTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/configuration/ConfigurationTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,21 @@
+//$Id: ConfigurationTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.configuration;
+
+import junit.framework.TestCase;
+import org.hibernate.cfg.AnnotationConfiguration;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class ConfigurationTest extends TestCase {
+ public void testMixPackageAndResourceOrdering() throws Exception {
+ try {
+ AnnotationConfiguration config = new AnnotationConfiguration();
+ config.addResource( "org/hibernate/test/annotations/configuration/orm.xml" );
+ config.addPackage( "org.hibernate.test.annotations.configuration" );
+ }
+ catch( Exception e ) {
+ fail("Processing package first when ORM.xml is used should not fail");
+ }
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/configuration/orm.xml
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/configuration/orm.xml (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/configuration/orm.xml 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<entity-mappings
+ xmlns="http://java.sun.com/xml/ns/persistence/orm"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_1_0.xsd"
+ version="1.0">
+</entity-mappings>
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/configuration/package-info.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/configuration/package-info.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/configuration/package-info.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,4 @@
+@GenericGenerator(name = "myGenerator", strategy = "sequence")
+package org.hibernate.test.annotations.configuration;
+
+import org.hibernate.annotations.GenericGenerator;
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/duplicatedgenerator/DuplicateTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/duplicatedgenerator/DuplicateTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/duplicatedgenerator/DuplicateTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,28 @@
+//$Id: DuplicateTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.duplicatedgenerator;
+
+import junit.framework.TestCase;
+import org.hibernate.AnnotationException;
+import org.hibernate.cfg.AnnotationConfiguration;
+import org.hibernate.cfg.Environment;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class DuplicateTest extends TestCase {
+ public void testDuplicateEntityName() throws Exception {
+ AnnotationConfiguration cfg = new AnnotationConfiguration();
+ cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
+ try {
+ cfg.addAnnotatedClass( Flight.class );
+ cfg.addAnnotatedClass( org.hibernate.test.annotations.Flight.class );
+ cfg.addResource( "org/hibernate/test/annotations/orm.xml");
+ cfg.addResource( "org/hibernate/test/annotations/duplicatedgenerator/orm.xml");
+ cfg.buildSessionFactory();
+ fail( "Should not be able to map the same entity name twice" );
+ }
+ catch (AnnotationException ae) {
+ //success
+ }
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/duplicatedgenerator/Flight.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/duplicatedgenerator/Flight.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/duplicatedgenerator/Flight.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,18 @@
+//$Id: Flight.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.duplicatedgenerator;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+/**
+ * Here to test duplicate import
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Table(name = "tbl_flight")
+public class Flight {
+ @Id
+ public String id;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/duplicatedgenerator/orm.xml
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/duplicatedgenerator/orm.xml (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/duplicatedgenerator/orm.xml 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ version="1.0"
+ >
+ <table-generator name="EMP_GEN" table="GENERATOR_TABLE"
+ pk-column-name="pkey" pk-column-value="EMP"
+ value-column-name="hi" allocation-size="20"/>
+</entity-mappings>
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Address.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Address.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Address.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,20 @@
+//$Id: Address.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.embedded;
+
+import java.io.Serializable;
+import javax.persistence.Column;
+import javax.persistence.Embeddable;
+import javax.persistence.ManyToOne;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Embeddable
+public class Address implements Serializable {
+ String address1;
+ @Column(name = "fld_city")
+ String city;
+ Country country;
+ @ManyToOne
+ AddressType type;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/AddressType.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/AddressType.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/AddressType.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,35 @@
+//$Id: AddressType.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.embedded;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * Kind of address (home, professional etc)
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity()
+public class AddressType {
+ private Integer id;
+ private String name;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Book.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Book.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Book.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,49 @@
+//$Id: Book.java 15073 2008-08-14 17:32:44Z epbernard $
+package org.hibernate.test.annotations.embedded;
+
+import javax.persistence.AttributeOverride;
+import javax.persistence.AttributeOverrides;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.SecondaryTable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@SecondaryTable(name = "BookSummary")
+public class Book {
+ private String isbn;
+ private String name;
+ private Summary summary;
+
+ @Id
+ public String getIsbn() {
+ return isbn;
+ }
+
+ public void setIsbn(String isbn) {
+ this.isbn = isbn;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @AttributeOverrides({
+ @AttributeOverride(name = "size", column = @Column(name="summ_size", table = "BookSummary")),
+ @AttributeOverride(name = "text", column = @Column(table = "BookSummary"))
+ })
+ public Summary getSummary() {
+ return summary;
+ }
+
+ public void setSummary(Summary summary) {
+ this.summary = summary;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/CorpType.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/CorpType.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/CorpType.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,33 @@
+//$Id: CorpType.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.embedded;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class CorpType {
+ private Integer id;
+ private String type;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Country.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Country.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Country.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,39 @@
+//$Id: Country.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.embedded;
+
+import java.io.Serializable;
+import javax.persistence.Column;
+import javax.persistence.Embeddable;
+
+import org.hibernate.annotations.AccessType;
+
+/**
+ * Non realistic embedded dependent object
+ *
+ * @author Emmanuel Bernard
+ */
+@Embeddable
+//access = AccessType.PROPERTY)
+@AccessType("property")
+public class Country implements Serializable {
+ private String iso2;
+ private String name;
+
+ public String getIso2() {
+ return iso2;
+ }
+
+ public void setIso2(String iso2) {
+ this.iso2 = iso2;
+ }
+
+ @Column(name = "countryName")
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Deal.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Deal.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Deal.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,40 @@
+//$Id: Deal.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.embedded;
+
+import javax.persistence.Embedded;
+import javax.persistence.Id;
+import javax.persistence.MappedSuperclass;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@MappedSuperclass
+public class Deal {
+ /**
+ * Deal ID.
+ */
+ private String id;
+
+ @Id
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ /**
+ * Swap with the tenor.
+ */
+ private Swap swap;
+
+ @Embedded
+ public Swap getSwap() {
+ return swap;
+ }
+
+ public void setSwap(Swap swap) {
+ this.swap = swap;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/EmbeddedTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/EmbeddedTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/EmbeddedTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,386 @@
+//$Id: EmbeddedTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.embedded;
+
+import java.io.Serializable;
+import java.util.List;
+import java.util.Set;
+
+import org.hibernate.Query;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.annotations.TestCase;
+import org.hibernate.test.annotations.embedded.FloatLeg.RateIndex;
+import org.hibernate.test.annotations.embedded.Leg.Frequency;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class EmbeddedTest extends TestCase {
+
+ public void testSimple() throws Exception {
+ Session s;
+ Transaction tx;
+ Person p = new Person();
+ Address a = new Address();
+ Country c = new Country();
+ Country bornCountry = new Country();
+ c.setIso2( "DM" );
+ c.setName( "Matt Damon Land" );
+ bornCountry.setIso2( "US" );
+ bornCountry.setName( "United States of America" );
+
+ a.address1 = "colorado street";
+ a.city = "Springfield";
+ a.country = c;
+ p.address = a;
+ p.bornIn = bornCountry;
+ p.name = "Homer";
+ s = openSession();
+ tx = s.beginTransaction();
+ s.persist( p );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ p = (Person) s.get( Person.class, p.id );
+ assertNotNull( p );
+ assertNotNull( p.address );
+ assertEquals( "Springfield", p.address.city );
+ assertNotNull( p.address.country );
+ assertEquals( "DM", p.address.country.getIso2() );
+ assertNotNull( p.bornIn );
+ assertEquals( "US", p.bornIn.getIso2() );
+ tx.commit();
+ s.close();
+ }
+
+ public void testCompositeId() throws Exception {
+ Session s;
+ Transaction tx;
+ RegionalArticlePk pk = new RegionalArticlePk();
+ pk.iso2 = "FR";
+ pk.localUniqueKey = "1234567890123";
+ RegionalArticle reg = new RegionalArticle();
+ reg.setName( "Je ne veux pes rester sage - Dolly" );
+ reg.setPk( pk );
+ s = openSession();
+ tx = s.beginTransaction();
+ s.persist( reg );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ reg = (RegionalArticle) s.get( RegionalArticle.class, (Serializable) reg.getPk() );
+ assertNotNull( reg );
+ assertNotNull( reg.getPk() );
+ assertEquals( "Je ne veux pes rester sage - Dolly", reg.getName() );
+ assertEquals( "FR", reg.getPk().iso2 );
+ tx.commit();
+ s.close();
+ }
+
+ public void testManyToOneInsideComponent() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Person p = new Person();
+ Country bornIn = new Country();
+ bornIn.setIso2( "FR" );
+ bornIn.setName( "France" );
+ p.bornIn = bornIn;
+ p.name = "Emmanuel";
+ AddressType type = new AddressType();
+ type.setName( "Primary Home" );
+ s.persist( type );
+ Country currentCountry = new Country();
+ currentCountry.setIso2( "US" );
+ currentCountry.setName( "USA" );
+ Address add = new Address();
+ add.address1 = "4 square street";
+ add.city = "San diego";
+ add.country = currentCountry;
+ add.type = type;
+ p.address = add;
+ s.persist( p );
+ tx.commit();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ Query q = s.createQuery( "select p from Person p where p.address.city = :city" );
+ q.setString( "city", add.city );
+ List result = q.list();
+ Person samePerson = (Person) result.get( 0 );
+ assertNotNull( samePerson.address.type );
+ assertEquals( type.getName(), samePerson.address.type.getName() );
+ tx.commit();
+ s.close();
+ }
+
+ public void testEmbeddedSuperclass() {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ VanillaSwap swap = new VanillaSwap();
+ swap.setInstrumentId( "US345421" );
+ swap.setCurrency( VanillaSwap.Currency.EUR );
+ FixedLeg fixed = new FixedLeg();
+ fixed.setPaymentFrequency( Leg.Frequency.SEMIANNUALLY );
+ fixed.setRate( 5.6 );
+ FloatLeg floating = new FloatLeg();
+ floating.setPaymentFrequency( Leg.Frequency.QUARTERLY );
+ floating.setRateIndex( FloatLeg.RateIndex.LIBOR );
+ floating.setRateSpread( 1.1 );
+ swap.setFixedLeg( fixed );
+ swap.setFloatLeg( floating );
+ s.persist( swap );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ swap = (VanillaSwap) s.get( VanillaSwap.class, swap.getInstrumentId() );
+ // All fields must be filled with non-default values
+ fixed = swap.getFixedLeg();
+ assertNotNull( "Fixed leg retrieved as null", fixed );
+ floating = swap.getFloatLeg();
+ assertNotNull( "Floating leg retrieved as null", floating );
+ assertEquals( Leg.Frequency.SEMIANNUALLY, fixed.getPaymentFrequency() );
+ assertEquals( Leg.Frequency.QUARTERLY, floating.getPaymentFrequency() );
+ s.delete( swap );
+ tx.commit();
+ s.close();
+ }
+
+ public void testDottedProperty() {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ // Create short swap
+ Swap shortSwap = new Swap();
+ shortSwap.setTenor( 2 );
+ FixedLeg shortFixed = new FixedLeg();
+ shortFixed.setPaymentFrequency( Frequency.SEMIANNUALLY );
+ shortFixed.setRate( 5.6 );
+ FloatLeg shortFloating = new FloatLeg();
+ shortFloating.setPaymentFrequency( Frequency.QUARTERLY );
+ shortFloating.setRateIndex( RateIndex.LIBOR );
+ shortFloating.setRateSpread( 1.1 );
+ shortSwap.setFixedLeg( shortFixed );
+ shortSwap.setFloatLeg( shortFloating );
+ // Create medium swap
+ Swap swap = new Swap();
+ swap.setTenor( 7 );
+ FixedLeg fixed = new FixedLeg();
+ fixed.setPaymentFrequency( Frequency.MONTHLY );
+ fixed.setRate( 7.6 );
+ FloatLeg floating = new FloatLeg();
+ floating.setPaymentFrequency( Frequency.MONTHLY );
+ floating.setRateIndex( RateIndex.TIBOR );
+ floating.setRateSpread( 0.8 );
+ swap.setFixedLeg( fixed );
+ swap.setFloatLeg( floating );
+ // Create long swap
+ Swap longSwap = new Swap();
+ longSwap.setTenor( 7 );
+ FixedLeg longFixed = new FixedLeg();
+ longFixed.setPaymentFrequency( Frequency.MONTHLY );
+ longFixed.setRate( 7.6 );
+ FloatLeg longFloating = new FloatLeg();
+ longFloating.setPaymentFrequency( Frequency.MONTHLY );
+ longFloating.setRateIndex( RateIndex.TIBOR );
+ longFloating.setRateSpread( 0.8 );
+ longSwap.setFixedLeg( longFixed );
+ longSwap.setFloatLeg( longFloating );
+ // Compose a curve spread deal
+ SpreadDeal deal = new SpreadDeal();
+ deal.setId( "FX45632" );
+ deal.setNotional( 450000.0 );
+ deal.setShortSwap( shortSwap );
+ deal.setSwap( swap );
+ deal.setLongSwap( longSwap );
+ s.persist( deal );
+
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ deal = (SpreadDeal) s.get( SpreadDeal.class, deal.getId() );
+ // All fields must be filled with non-default values
+ assertNotNull( "Short swap is null.", deal.getShortSwap() );
+ assertNotNull( "Swap is null.", deal.getSwap() );
+ assertNotNull( "Long swap is null.", deal.getLongSwap() );
+ assertEquals( 2, deal.getShortSwap().getTenor() );
+ assertEquals( 7, deal.getSwap().getTenor() );
+ assertEquals( 7, deal.getLongSwap().getTenor() );
+ assertNotNull( "Short fixed leg is null.", deal.getShortSwap().getFixedLeg() );
+ assertNotNull( "Short floating leg is null.", deal.getShortSwap().getFloatLeg() );
+ assertNotNull( "Fixed leg is null.", deal.getSwap().getFixedLeg() );
+ assertNotNull( "Floating leg is null.", deal.getSwap().getFloatLeg() );
+ assertNotNull( "Long fixed leg is null.", deal.getLongSwap().getFixedLeg() );
+ assertNotNull( "Long floating leg is null.", deal.getLongSwap().getFloatLeg() );
+ assertEquals( Frequency.SEMIANNUALLY, deal.getShortSwap().getFixedLeg().getPaymentFrequency() );
+ assertEquals( Frequency.QUARTERLY, deal.getShortSwap().getFloatLeg().getPaymentFrequency() );
+ assertEquals( Frequency.MONTHLY, deal.getSwap().getFixedLeg().getPaymentFrequency() );
+ assertEquals( Frequency.MONTHLY, deal.getSwap().getFloatLeg().getPaymentFrequency() );
+ assertEquals( Frequency.MONTHLY, deal.getLongSwap().getFixedLeg().getPaymentFrequency() );
+ assertEquals( Frequency.MONTHLY, deal.getLongSwap().getFloatLeg().getPaymentFrequency() );
+ assertEquals( 5.6, deal.getShortSwap().getFixedLeg().getRate() );
+ assertEquals( 7.6, deal.getSwap().getFixedLeg().getRate() );
+ assertEquals( 7.6, deal.getLongSwap().getFixedLeg().getRate() );
+ assertEquals( RateIndex.LIBOR, deal.getShortSwap().getFloatLeg().getRateIndex() );
+ assertEquals( RateIndex.TIBOR, deal.getSwap().getFloatLeg().getRateIndex() );
+ assertEquals( RateIndex.TIBOR, deal.getLongSwap().getFloatLeg().getRateIndex() );
+ assertEquals( 1.1, deal.getShortSwap().getFloatLeg().getRateSpread() );
+ assertEquals( 0.8, deal.getSwap().getFloatLeg().getRateSpread() );
+ assertEquals( 0.8, deal.getLongSwap().getFloatLeg().getRateSpread() );
+ s.delete( deal );
+ tx.commit();
+ s.close();
+ }
+
+ public void testEmbeddedInSecdondaryTable() throws Exception {
+ Session s;
+ s = openSession();
+ s.getTransaction().begin();
+ Book book = new Book();
+ book.setIsbn( "1234" );
+ book.setName( "HiA Second Edition" );
+ Summary summary = new Summary();
+ summary.setText( "This is a HiA SE summary" );
+ summary.setSize( summary.getText().length() );
+ book.setSummary( summary );
+ s.persist( book );
+ s.getTransaction().commit();
+
+ s.clear();
+
+ Transaction tx = s.beginTransaction();
+ Book loadedBook = (Book) s.get( Book.class, book.getIsbn() );
+ assertNotNull( loadedBook.getSummary() );
+ assertEquals( book.getSummary().getText(), loadedBook.getSummary().getText() );
+ s.delete( loadedBook );
+ tx.commit();
+ s.close();
+ }
+
+ public void testParent() throws Exception {
+ Session s;
+ s = openSession();
+ s.getTransaction().begin();
+ Book book = new Book();
+ book.setIsbn( "1234" );
+ book.setName( "HiA Second Edition" );
+ Summary summary = new Summary();
+ summary.setText( "This is a HiA SE summary" );
+ summary.setSize( summary.getText().length() );
+ book.setSummary( summary );
+ s.persist( book );
+ s.getTransaction().commit();
+
+ s.clear();
+
+ Transaction tx = s.beginTransaction();
+ Book loadedBook = (Book) s.get( Book.class, book.getIsbn() );
+ assertNotNull( loadedBook.getSummary() );
+ assertEquals( loadedBook, loadedBook.getSummary().getSummarizedBook() );
+ s.delete( loadedBook );
+ tx.commit();
+ s.close();
+ }
+
+ public void testEmbeddedAndMultipleManyToOne() throws Exception {
+ Session s;
+ s = openSession();
+ Transaction tx = s.beginTransaction();
+ CorpType type = new CorpType();
+ type.setType( "National" );
+ s.persist( type );
+ Nationality nat = new Nationality();
+ nat.setName( "Canadian" );
+ s.persist( nat );
+ InternetProvider provider = new InternetProvider();
+ provider.setBrandName( "Fido" );
+ LegalStructure structure = new LegalStructure();
+ structure.setCorporationType( type );
+ structure.setCountry( "Canada" );
+ structure.setName( "Rogers" );
+ provider.setOwner( structure );
+ structure.setOrigin( nat );
+ s.persist( provider );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ provider = (InternetProvider) s.get( InternetProvider.class, provider.getId() );
+ assertNotNull( provider.getOwner() );
+ assertNotNull( "Many to one not set", provider.getOwner().getCorporationType() );
+ assertEquals( "Wrong link", type.getType(), provider.getOwner().getCorporationType().getType() );
+ assertNotNull( "2nd Many to one not set", provider.getOwner().getOrigin() );
+ assertEquals( "Wrong 2nd link", nat.getName(), provider.getOwner().getOrigin().getName() );
+ s.delete( provider );
+ s.delete( provider.getOwner().getCorporationType() );
+ s.delete( provider.getOwner().getOrigin() );
+ tx.commit();
+ s.close();
+ }
+
+ public void testEmbeddedAndOneToMany() throws Exception {
+ Session s;
+ s = openSession();
+ Transaction tx = s.beginTransaction();
+ InternetProvider provider = new InternetProvider();
+ provider.setBrandName( "Fido" );
+ LegalStructure structure = new LegalStructure();
+ structure.setCountry( "Canada" );
+ structure.setName( "Rogers" );
+ provider.setOwner( structure );
+ s.persist( provider );
+ Manager manager = new Manager();
+ manager.setName( "Bill" );
+ manager.setEmployer( provider );
+ structure.getTopManagement().add( manager );
+ s.persist( manager );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ provider = (InternetProvider) s.get( InternetProvider.class, provider.getId() );
+ assertNotNull( provider.getOwner() );
+ Set<Manager> topManagement = provider.getOwner().getTopManagement();
+ assertNotNull( "OneToMany not set", topManagement );
+ assertEquals( "Wrong number of elements", 1, topManagement.size() );
+ manager = (Manager) topManagement.iterator().next();
+ assertEquals( "Wrong element", "Bill", manager.getName() );
+ s.delete( manager );
+ s.delete( provider );
+ tx.commit();
+ s.close();
+ }
+
+ public EmbeddedTest(String x) {
+ super( x );
+ }
+
+ protected Class[] getMappings() {
+ return new Class[]{
+ Person.class,
+ RegionalArticle.class,
+ AddressType.class,
+ VanillaSwap.class,
+ SpreadDeal.class,
+ Book.class,
+ InternetProvider.class,
+ CorpType.class,
+ Nationality.class,
+ Manager.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/FixedLeg.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/FixedLeg.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/FixedLeg.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,31 @@
+package org.hibernate.test.annotations.embedded;
+
+import java.text.NumberFormat;
+import javax.persistence.Embeddable;
+
+/**
+ * Represents fixed part of Interest Rate Swap cash flows.
+ */
+@Embeddable
+public class FixedLeg extends Leg {
+
+ /**
+ * Fixed rate.
+ */
+ private double rate;
+
+ public double getRate() {
+ return rate;
+ }
+
+ public void setRate(double rate) {
+ this.rate = rate;
+ }
+
+ public String toString() {
+ NumberFormat format = NumberFormat.getNumberInstance();
+ format.setMinimumFractionDigits( 4 );
+ format.setMaximumFractionDigits( 4 );
+ return format.format( getRate() ) + "%";
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/FloatLeg.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/FloatLeg.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/FloatLeg.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,49 @@
+package org.hibernate.test.annotations.embedded;
+
+import java.text.NumberFormat;
+import javax.persistence.Embeddable;
+
+/**
+ * Represents floating part of Interest Rate Swap cash flows.
+ */
+@Embeddable
+public class FloatLeg extends Leg {
+
+ /**
+ * Possible values for the rate index.
+ */
+ public enum RateIndex {
+ LIBOR, EURIBOR, TIBOR}
+
+ ;
+
+ private RateIndex rateIndex;
+
+ /**
+ * Spread over the selected rate index (in basis points).
+ */
+ private double rateSpread;
+
+ public RateIndex getRateIndex() {
+ return rateIndex;
+ }
+
+ public void setRateIndex(RateIndex rateIndex) {
+ this.rateIndex = rateIndex;
+ }
+
+ public double getRateSpread() {
+ return rateSpread;
+ }
+
+ public void setRateSpread(double rateSpread) {
+ this.rateSpread = rateSpread;
+ }
+
+ public String toString() {
+ NumberFormat format = NumberFormat.getNumberInstance();
+ format.setMinimumFractionDigits( 1 );
+ format.setMaximumFractionDigits( 1 );
+ return "[" + getRateIndex().toString() + "+" + format.format( getRateSpread() ) + "]";
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/InternetProvider.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/InternetProvider.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/InternetProvider.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,42 @@
+//$Id: InternetProvider.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.embedded;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class InternetProvider {
+ private Integer id;
+ private String brandName;
+ private LegalStructure owner;
+
+ public String getBrandName() {
+ return brandName;
+ }
+
+ public void setBrandName(String brandName) {
+ this.brandName = brandName;
+ }
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public LegalStructure getOwner() {
+ return owner;
+ }
+
+ public void setOwner(LegalStructure owner) {
+ this.owner = owner;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Leg.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Leg.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Leg.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,31 @@
+package org.hibernate.test.annotations.embedded;
+
+import javax.persistence.MappedSuperclass;
+
+/**
+ * Represents a leg of a vanilla interest rate swap.
+ */
+@MappedSuperclass
+public class Leg {
+ /**
+ * Possible values of the payment frequency field.
+ */
+ public enum Frequency {
+ ANNUALY, SEMIANNUALLY, QUARTERLY, MONTHLY }
+
+ ;
+
+ /**
+ * Shows how frequent payments according to this leg should be made.
+ */
+ private Frequency paymentFrequency;
+
+ public Frequency getPaymentFrequency() {
+ return paymentFrequency;
+ }
+
+ public void setPaymentFrequency(Frequency paymentFrequency) {
+ this.paymentFrequency = paymentFrequency;
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/LegalStructure.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/LegalStructure.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/LegalStructure.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,66 @@
+//$Id: LegalStructure.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.embedded;
+
+import java.util.HashSet;
+import java.util.Set;
+import javax.persistence.Embeddable;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+import javax.persistence.OneToMany;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Embeddable
+public class LegalStructure {
+ private String name;
+ private String country;
+ private CorpType corporationType;
+ private Nationality origin;
+ private Set<Manager> topManagement = new HashSet<Manager>();
+
+ @ManyToOne
+ @JoinColumn(name = "CORP_ID")
+ public CorpType getCorporationType() {
+ return corporationType;
+ }
+
+ public void setCorporationType(CorpType corporationType) {
+ this.corporationType = corporationType;
+ }
+
+ public String getCountry() {
+ return country;
+ }
+
+ public void setCountry(String country) {
+ this.country = country;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @ManyToOne
+ @JoinColumn(name = "origin_fk")
+ public Nationality getOrigin() {
+ return origin;
+ }
+
+ public void setOrigin(Nationality origin) {
+ this.origin = origin;
+ }
+
+ @OneToMany(mappedBy = "employer")
+ public Set<Manager> getTopManagement() {
+ return topManagement;
+ }
+
+ public void setTopManagement(Set<Manager> topManagement) {
+ this.topManagement = topManagement;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Manager.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Manager.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Manager.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,44 @@
+//$Id: Manager.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.embedded;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.ManyToOne;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Manager {
+ private Integer id;
+ private String name;
+ private InternetProvider employer;
+
+ @ManyToOne
+ public InternetProvider getEmployer() {
+ return employer;
+ }
+
+ public void setEmployer(InternetProvider employer) {
+ this.employer = employer;
+ }
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Nationality.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Nationality.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Nationality.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,33 @@
+//$Id: Nationality.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.embedded;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Nationality {
+ private Integer id;
+ private String name;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/NotonialDeal.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/NotonialDeal.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/NotonialDeal.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,30 @@
+//$Id: NotonialDeal.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.embedded;
+
+import javax.persistence.AttributeOverride;
+import javax.persistence.AttributeOverrides;
+import javax.persistence.Column;
+import javax.persistence.MappedSuperclass;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@AttributeOverrides(value = {
+@AttributeOverride(name = "swap.tenor", column = @Column(name = "TENOR")), //should be ovvriden by deal
+@AttributeOverride(name = "id", column = @Column(name = "NOTONIALDEAL_ID"))
+ })
+@MappedSuperclass
+public class NotonialDeal extends Deal {
+ /**
+ * Notional amount of both IRSs.
+ */
+ private double notional;
+
+ public double getNotional() {
+ return notional;
+ }
+
+ public void setNotional(double notional) {
+ this.notional = notional;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Person.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Person.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Person.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,35 @@
+//$Id: Person.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.embedded;
+
+import java.io.Serializable;
+import javax.persistence.AttributeOverride;
+import javax.persistence.AttributeOverrides;
+import javax.persistence.Column;
+import javax.persistence.Embedded;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Table(name = "PersonEmbed")
+public class Person implements Serializable {
+ @Id
+ @GeneratedValue
+ Integer id;
+
+ String name;
+
+ @Embedded
+ Address address;
+
+ @Embedded
+ @AttributeOverrides({
+ @AttributeOverride(name = "iso2", column = @Column(name = "bornIso2")),
+ @AttributeOverride(name = "name", column = @Column(name = "bornCountryName"))
+ })
+ Country bornIn;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/RegionalArticle.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/RegionalArticle.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/RegionalArticle.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,50 @@
+//$Id: RegionalArticle.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.embedded;
+
+import java.io.Serializable;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+/**
+ * A regional article is typically a bad design, it keep the country iso2 and a business key as
+ * (composite) primary key
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class RegionalArticle implements Serializable {
+ private RegionalArticlePk pk;
+ private String name;
+
+ @Id
+ public RegionalArticlePk getPk() {
+ return pk;
+ }
+
+ public void setPk(RegionalArticlePk pk) {
+ this.pk = pk;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public int hashCode() {
+ //a NPE can occurs, but I don't expect hashcode to be used before pk is set
+ return getPk().hashCode();
+ }
+
+ public boolean equals(Object obj) {
+ //a NPE can occurs, but I don't expect equals to be used before pk is set
+ if ( obj != null && obj instanceof RegionalArticle ) {
+ return getPk().equals( ( (RegionalArticle) obj ).getPk() );
+ }
+ else {
+ return false;
+ }
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/RegionalArticlePk.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/RegionalArticlePk.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/RegionalArticlePk.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,38 @@
+//$Id: RegionalArticlePk.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.embedded;
+
+import java.io.Serializable;
+import javax.persistence.Embeddable;
+
+import org.hibernate.annotations.AccessType;
+
+/**
+ * Regional article pk
+ *
+ * @author Emmanuel Bernard
+ */
+@Embeddable
+@AccessType("field")
+public class RegionalArticlePk implements Serializable {
+ /**
+ * country iso2 code
+ */
+ public String iso2;
+ public String localUniqueKey;
+
+ public int hashCode() {
+ //this implem sucks
+ return ( iso2 + localUniqueKey ).hashCode();
+ }
+
+ public boolean equals(Object obj) {
+ //iso2 and localUniqueKey are expected to be set in this implem
+ if ( obj != null && obj instanceof RegionalArticlePk ) {
+ RegionalArticlePk other = (RegionalArticlePk) obj;
+ return iso2.equals( other.iso2 ) && localUniqueKey.equals( other.localUniqueKey );
+ }
+ else {
+ return false;
+ }
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/SpreadDeal.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/SpreadDeal.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/SpreadDeal.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,62 @@
+package org.hibernate.test.annotations.embedded;
+
+import javax.persistence.AttributeOverride;
+import javax.persistence.AttributeOverrides;
+import javax.persistence.Column;
+import javax.persistence.Embedded;
+import javax.persistence.Entity;
+
+/**
+ * Represents a "curve spread" deal that consists of
+ * two Interest Rate Swaps with different tenors (short and long).
+ * For simplicity, tenors are not considered here.
+ */
+@Entity
+@AttributeOverrides(value = {
+@AttributeOverride(name = "swap.tenor", column = @Column(name = "MEDIUM_TENOR")),
+@AttributeOverride(name = "swap.fixedLeg.paymentFrequency", column = @Column(name = "MEDIUM_FIXED_FREQUENCY")),
+@AttributeOverride(name = "swap.fixedLeg.rate", column = @Column(name = "MEDIUM_FIXED_RATE")),
+@AttributeOverride(name = "swap.floatLeg.paymentFrequency", column = @Column(name = "MEDIUM_FLOAT_FREQUENCY")),
+@AttributeOverride(name = "swap.floatLeg.rateIndex", column = @Column(name = "MEDIUM_FLOAT_RATEINDEX")),
+@AttributeOverride(name = "swap.floatLeg.rateSpread", column = @Column(name = "MEDIUM_FLOAT_RATESPREAD"))
+ })
+public class SpreadDeal extends NotonialDeal {
+
+ /**
+ * Swap with the tenor.
+ */
+ private Swap longSwap;
+
+ @Embedded
+ public Swap getLongSwap() {
+ return longSwap;
+ }
+
+ public void setLongSwap(Swap swap) {
+ this.longSwap = swap;
+ }
+
+
+ /**
+ * Swap with the longer tenor.
+ */
+ private Swap shortSwap;
+
+
+ @Embedded
+ @AttributeOverrides(value = {
+ @AttributeOverride(name = "tenor", column = @Column(name = "SHORT_TENOR")),
+ @AttributeOverride(name = "fixedLeg.paymentFrequency", column = @Column(name = "SHORT_FIXED_FREQUENCY")),
+ @AttributeOverride(name = "fixedLeg.rate", column = @Column(name = "SHORT_FIXED_RATE")),
+ @AttributeOverride(name = "floatLeg.paymentFrequency", column = @Column(name = "SHORT_FLOAT_FREQUENCY")),
+ @AttributeOverride(name = "floatLeg.rateIndex", column = @Column(name = "SHORT_FLOAT_RATEINDEX")),
+ @AttributeOverride(name = "floatLeg.rateSpread", column = @Column(name = "SHORT_FLOAT_RATESPREAD"))
+ })
+ public Swap getShortSwap() {
+ return shortSwap;
+ }
+
+ public void setShortSwap(Swap shortSwap) {
+ this.shortSwap = shortSwap;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Summary.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Summary.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Summary.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,43 @@
+//$Id: Summary.java 15056 2008-08-13 18:15:05Z epbernard $
+package org.hibernate.test.annotations.embedded;
+
+import javax.persistence.Embeddable;
+import javax.persistence.Column;
+
+import org.hibernate.annotations.Parent;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Embeddable
+public class Summary {
+ private int size;
+ private String text;
+ private Book summarizedBook;
+
+ @Column(name="summary_size")
+ public int getSize() {
+ return size;
+ }
+
+ public void setSize(int size) {
+ this.size = size;
+ }
+
+ public String getText() {
+ return text;
+ }
+
+ public void setText(String text) {
+ this.text = text;
+ }
+
+ @Parent
+ public Book getSummarizedBook() {
+ return summarizedBook;
+ }
+
+ public void setSummarizedBook(Book summarizedBook) {
+ this.summarizedBook = summarizedBook;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Swap.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Swap.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/Swap.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,58 @@
+package org.hibernate.test.annotations.embedded;
+
+import javax.persistence.AttributeOverride;
+import javax.persistence.Column;
+import javax.persistence.Embeddable;
+import javax.persistence.Embedded;
+
+/**
+ * Interest Rate Swap with Tenor. Used here to compose
+ * a swap spread deal.
+ */
+@Embeddable
+public class Swap {
+
+ /**
+ * Tenor (duration) of the swap (in years).
+ */
+ private int tenor;
+
+ public int getTenor() {
+ return tenor;
+ }
+
+ public void setTenor(int tenor) {
+ this.tenor = tenor;
+ }
+
+ /**
+ * Fixed leg (cash flows with the fixed rate).
+ */
+ private FixedLeg fixedLeg;
+
+ /**
+ * Floating leg (cash flows bound to a financial index).
+ */
+ private FloatLeg floatLeg;
+
+ @Embedded
+ // We retain this annotation to test the precedence of @AttributeOverride
+ // Outermost override annotation should win
+ @AttributeOverride(name = "paymentFrequency", column = @Column(name = "FIXED_FREQENCY"))
+ public FixedLeg getFixedLeg() {
+ return fixedLeg;
+ }
+
+ public void setFixedLeg(FixedLeg fixedLeg) {
+ this.fixedLeg = fixedLeg;
+ }
+
+ @Embedded
+ public FloatLeg getFloatLeg() {
+ return floatLeg;
+ }
+
+ public void setFloatLeg(FloatLeg floatLeg) {
+ this.floatLeg = floatLeg;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/VanillaSwap.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/VanillaSwap.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/embedded/VanillaSwap.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,77 @@
+package org.hibernate.test.annotations.embedded;
+
+import javax.persistence.AttributeOverride;
+import javax.persistence.Column;
+import javax.persistence.Embedded;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+/**
+ * Represents an Interest Rate Swap.
+ */
+@Entity
+public class VanillaSwap {
+
+ /**
+ * Possible values for the currency field.
+ */
+ public enum Currency {
+ USD, GBP, EUR, JPY }
+
+ /**
+ * Identifier of the Interest Rate Swap
+ */
+ private String instrumentId;
+
+ /**
+ * Currency of the swap (and of both legs).
+ */
+ private Currency currency;
+
+ /**
+ * Fixed leg (cash flows with the fixed rate).
+ */
+ private FixedLeg fixedLeg;
+
+ /**
+ * Floating leg (cash flows bound to a financial index).
+ */
+ private FloatLeg floatLeg;
+
+ @Embedded
+ @AttributeOverride(name = "paymentFrequency", column = @Column(name = "FIXED_FREQENCY"))
+ public FixedLeg getFixedLeg() {
+ return fixedLeg;
+ }
+
+ public void setFixedLeg(FixedLeg fixedLeg) {
+ this.fixedLeg = fixedLeg;
+ }
+
+ @Embedded
+ @AttributeOverride(name = "paymentFrequency", column = @Column(name = "FLOAT_FREQUENCY"))
+ public FloatLeg getFloatLeg() {
+ return floatLeg;
+ }
+
+ public void setFloatLeg(FloatLeg floatLeg) {
+ this.floatLeg = floatLeg;
+ }
+
+ public Currency getCurrency() {
+ return currency;
+ }
+
+ public void setCurrency(Currency currency) {
+ this.currency = currency;
+ }
+
+ @Id
+ public String getInstrumentId() {
+ return instrumentId;
+ }
+
+ public void setInstrumentId(String instrumentId) {
+ this.instrumentId = instrumentId;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Address.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Address.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Address.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,47 @@
+//$Id: Address.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.entity;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+/**
+ * Has a serializable class as a property
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Table(name = "serial_address")
+public class Address {
+ private Integer id;
+ private String city;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getCity() {
+ return city;
+ }
+
+ public void setCity(String city) {
+ this.city = city;
+ }
+
+ public Country getCountry() {
+ return country;
+ }
+
+ public void setCountry(Country country) {
+ this.country = country;
+ }
+
+ private Country country;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/BasicHibernateAnnotationsTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/BasicHibernateAnnotationsTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/BasicHibernateAnnotationsTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,357 @@
+//$Id: BasicHibernateAnnotationsTest.java 17798 2009-10-19 15:48:57Z stliu $
+package org.hibernate.test.annotations.entity;
+
+import java.math.BigDecimal;
+import java.util.Currency;
+import java.util.Date;
+
+import org.hibernate.Hibernate;
+import org.hibernate.HibernateException;
+import org.hibernate.Query;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class BasicHibernateAnnotationsTest extends TestCase {
+
+ public void testEntity() throws Exception {
+ if( !getDialect().supportsExpectedLobUsagePattern() ){
+ return;
+ }
+ Forest forest = new Forest();
+ forest.setName( "Fontainebleau" );
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ s.persist( forest );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ forest = (Forest) s.get( Forest.class, forest.getId() );
+ assertNotNull( forest );
+ forest.setName( "Fontainebleau" );
+ //should not execute SQL update
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ forest = (Forest) s.get( Forest.class, forest.getId() );
+ assertNotNull( forest );
+ forest.setLength( 23 );
+ //should execute dynamic SQL update
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ s.delete( s.get( Forest.class, forest.getId() ) );
+ tx.commit();
+ s.close();
+ }
+
+ public void testVersioning() throws Exception {
+ if( !getDialect().supportsExpectedLobUsagePattern() ){
+ return;
+ }
+ Forest forest = new Forest();
+ forest.setName( "Fontainebleau" );
+ forest.setLength( 33 );
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ s.persist( forest );
+ tx.commit();
+ s.close();
+
+ Session parallelSession = openSession();
+ Transaction parallelTx = parallelSession.beginTransaction();
+ s = openSession();
+ tx = s.beginTransaction();
+
+ forest = (Forest) parallelSession.get( Forest.class, forest.getId() );
+ Forest reloadedForest = (Forest) s.get( Forest.class, forest.getId() );
+ reloadedForest.setLength( 11 );
+ assertNotSame( forest, reloadedForest );
+ tx.commit();
+ s.close();
+
+ forest.setLength( 22 );
+ try {
+ parallelTx.commit();
+ fail( "All optimistic locking should have make it fail" );
+ }
+ catch (HibernateException e) {
+ if ( parallelTx != null ) parallelTx.rollback();
+ }
+ finally {
+ parallelSession.close();
+ }
+
+ s = openSession();
+ tx = s.beginTransaction();
+ s.delete( s.get( Forest.class, forest.getId() ) );
+ tx.commit();
+ s.close();
+
+ }
+
+ public void testPolymorphism() throws Exception {
+ if( !getDialect().supportsExpectedLobUsagePattern() ){
+ return;
+ }
+ Forest forest = new Forest();
+ forest.setName( "Fontainebleau" );
+ forest.setLength( 33 );
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ s.persist( forest );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ Query query = s.createQuery( "from java.lang.Object" );
+ assertEquals( 0, query.list().size() );
+ query = s.createQuery( "from Forest" );
+ assertTrue( 0 < query.list().size() );
+ tx.commit();
+ s.close();
+ }
+
+ public void testType() throws Exception {
+ if( !getDialect().supportsExpectedLobUsagePattern() ){
+ return;
+ }
+ Forest f = new Forest();
+ f.setName( "Broceliande" );
+ String description = "C'est une enorme foret enchantee ou vivais Merlin et toute la clique";
+ f.setLongDescription( description );
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ s.persist( f );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ f = (Forest) s.get( Forest.class, f.getId() );
+ assertNotNull( f );
+ assertEquals( description, f.getLongDescription() );
+ s.delete( f );
+ tx.commit();
+ s.close();
+
+ }
+
+ public void testNonLazy() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Forest f = new Forest();
+ Tree t = new Tree();
+ t.setName( "Basic one" );
+ s.persist( f );
+ s.persist( t );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ f = (Forest) s.load( Forest.class, f.getId() );
+ t = (Tree) s.load( Tree.class, t.getId() );
+ assertFalse( "Default should be lazy", Hibernate.isInitialized( f ) );
+ assertTrue( "Tree is not lazy", Hibernate.isInitialized( t ) );
+ tx.commit();
+ s.close();
+ }
+
+ public void testCache() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ ZipCode zc = new ZipCode();
+ zc.code = "92400";
+ s.persist( zc );
+ tx.commit();
+ s.close();
+ getSessions().getStatistics().clear();
+ getSessions().getStatistics().setStatisticsEnabled( true );
+ getSessions().evict( ZipCode.class );
+ s = openSession();
+ tx = s.beginTransaction();
+ s.get( ZipCode.class, zc.code );
+ assertEquals( 1, getSessions().getStatistics().getSecondLevelCachePutCount() );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ s.get( ZipCode.class, zc.code );
+ assertEquals( 1, getSessions().getStatistics().getSecondLevelCacheHitCount() );
+ tx.commit();
+ s.close();
+ }
+
+ public void testFilter() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ s.createQuery( "delete Forest" ).executeUpdate();
+ Forest f1 = new Forest();
+ f1.setLength( 2 );
+ s.persist( f1 );
+ Forest f2 = new Forest();
+ f2.setLength( 20 );
+ s.persist( f2 );
+ Forest f3 = new Forest();
+ f3.setLength( 200 );
+ s.persist( f3 );
+ tx.commit();
+ s.close();
+ s = openSession();
+ tx = s.beginTransaction();
+ s.enableFilter( "betweenLength" ).setParameter( "minLength", 5 ).setParameter( "maxLength", 50 );
+ long count = ( (Long) s.createQuery( "select count(*) from Forest" ).iterate().next() ).intValue();
+ assertEquals( 1, count );
+ s.disableFilter( "betweenLength" );
+ s.enableFilter( "minLength" ).setParameter( "minLength", 5 );
+ count = ( (Long) s.createQuery( "select count(*) from Forest" ).iterate().next() ).longValue();
+ assertEquals( 2l, count );
+ s.disableFilter( "minLength" );
+ tx.rollback();
+ s.close();
+ }
+
+ public void testParameterizedType() throws Exception {
+ if( !getDialect().supportsExpectedLobUsagePattern() ){
+ return;
+ }
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Forest f = new Forest();
+ f.setSmallText( "ThisIsASmallText" );
+ f.setBigText( "ThisIsABigText" );
+ s.persist( f );
+ tx.commit();
+ s.close();
+ s = openSession();
+ tx = s.beginTransaction();
+ Forest f2 = (Forest) s.get( Forest.class, f.getId() );
+ assertEquals( f.getSmallText().toLowerCase(), f2.getSmallText() );
+ assertEquals( f.getBigText().toUpperCase(), f2.getBigText() );
+ tx.commit();
+ s.close();
+ }
+
+ public void testSerialized() throws Exception {
+ if( !getDialect().supportsExpectedLobUsagePattern() ){
+ return;
+ }
+ Forest forest = new Forest();
+ forest.setName( "Shire" );
+ Country country = new Country();
+ country.setName( "Middle Earth" );
+ forest.setCountry( country );
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ s.persist( forest );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ forest = (Forest) s.get( Forest.class, forest.getId() );
+ assertNotNull( forest );
+ assertNotNull( forest.getCountry() );
+ assertEquals( country.getName(), forest.getCountry().getName() );
+ tx.commit();
+ s.close();
+ }
+
+ public void testCompositeType() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Ransom r = new Ransom();
+ r.setKidnapperName( "Se7en" );
+ r.setDate( new Date() );
+ MonetaryAmount amount = new MonetaryAmount(
+ new BigDecimal( 100000 ),
+ Currency.getInstance( "EUR" )
+ );
+ r.setAmount( amount );
+ s.persist( r );
+ tx.commit();
+ s.clear();
+ tx = s.beginTransaction();
+ r = (Ransom) s.get( Ransom.class, r.getId() );
+ assertNotNull( r );
+ assertNotNull( r.getAmount() );
+ assertTrue( 0 == new BigDecimal( 100000 ).compareTo( r.getAmount().getAmount() ) );
+ assertEquals( Currency.getInstance( "EUR" ), r.getAmount().getCurrency() );
+ tx.commit();
+ s.close();
+ }
+
+ public void testFormula() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ org.hibernate.test.annotations.entity.Flight airFrance = new Flight();
+ airFrance.setId( new Long( 747 ) );
+ airFrance.setMaxAltitude( 10000 );
+ s.persist( airFrance );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ airFrance = (Flight) s.get( Flight.class, airFrance.getId() );
+ assertNotNull( airFrance );
+ assertEquals( 10000000, airFrance.getMaxAltitudeInMilimeter() );
+ s.delete( airFrance );
+ tx.commit();
+ s.close();
+ }
+
+ public BasicHibernateAnnotationsTest(String x) {
+ super( x );
+ }
+
+ protected Class[] getMappings() {
+ return new Class[]{
+ Forest.class,
+ Tree.class,
+ Ransom.class,
+ ZipCode.class,
+ Flight.class
+ };
+ }
+
+ protected String[] getAnnotatedPackages() {
+ return new String[]{
+ "org.hibernate.test.annotations.entity"
+ };
+ }
+
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Bid.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Bid.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Bid.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,63 @@
+//$Id: Bid.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.entity;
+
+import javax.persistence.Entity;
+import javax.persistence.EnumType;
+import javax.persistence.Enumerated;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Bid {
+ private Integer id;
+ private String description;
+ private Starred note;
+ private Starred editorsNote;
+ private Boolean approved;
+
+ @Enumerated(EnumType.STRING)
+ //@Column(columnDefinition = "VARCHAR(10)")
+ public Starred getEditorsNote() {
+ return editorsNote;
+ }
+
+ public void setEditorsNote(Starred editorsNote) {
+ this.editorsNote = editorsNote;
+ }
+
+ @Id
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public Starred getNote() {
+ return note;
+ }
+
+ public void setNote(Starred note) {
+ this.note = note;
+ }
+
+ public Boolean getApproved() {
+ return approved;
+ }
+
+ public void setApproved(Boolean approved) {
+ this.approved = approved;
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/CasterStringType.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/CasterStringType.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/CasterStringType.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,90 @@
+//$Id: CasterStringType.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.entity;
+
+import java.io.Serializable;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Types;
+import java.util.Properties;
+
+import org.hibernate.HibernateException;
+import org.hibernate.usertype.ParameterizedType;
+import org.hibernate.usertype.UserType;
+
+/**
+ * Sample of parameter type
+ *
+ * @author Emmanuel Bernard
+ */
+public class CasterStringType implements UserType, ParameterizedType {
+ private static final String CAST = "cast";
+ private Properties parameters;
+
+ public int[] sqlTypes() {
+ return new int[]{Types.VARCHAR};
+ }
+
+ public Class returnedClass() {
+ return String.class;
+ }
+
+ public boolean equals(Object x, Object y) throws HibernateException {
+ return ( x == y ) || ( x != null && x.equals( y ) );
+ }
+
+ public int hashCode(Object x) throws HibernateException {
+ return x.hashCode();
+ }
+
+ public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
+ String result = rs.getString( names[0] );
+ if ( rs.wasNull() ) return null;
+ if ( parameters.getProperty( CAST ).equals( "lower" ) ) {
+ return result.toLowerCase();
+ }
+ else {
+ return result.toUpperCase();
+ }
+ }
+
+ public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
+ if ( value == null ) {
+ st.setNull( index, sqlTypes()[0] );
+ }
+ else {
+ String string = (String) value;
+ if ( parameters.getProperty( CAST ).equals( "lower" ) ) {
+ string = string.toLowerCase();
+ }
+ else {
+ string = string.toUpperCase();
+ }
+ st.setString( index, string );
+ }
+ }
+
+ public Object deepCopy(Object value) throws HibernateException {
+ return value;
+ }
+
+ public boolean isMutable() {
+ return false;
+ }
+
+ public Serializable disassemble(Object value) throws HibernateException {
+ return (Serializable) value;
+ }
+
+ public Object assemble(Serializable cached, Object owner) throws HibernateException {
+ return cached;
+ }
+
+ public Object replace(Object original, Object target, Object owner) throws HibernateException {
+ return original;
+ }
+
+ public void setParameterValues(Properties parameters) {
+ this.parameters = parameters;
+ }
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/CommunityBid.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/CommunityBid.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/CommunityBid.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,21 @@
+//$Id: CommunityBid.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.entity;
+
+import javax.persistence.Entity;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class CommunityBid extends Bid {
+ private Starred communityNote;
+
+ public Starred getCommunityNote() {
+ return communityNote;
+ }
+
+ public void setCommunityNote(Starred communityNote) {
+ this.communityNote = communityNote;
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Country.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Country.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Country.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,21 @@
+//$Id: Country.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.entity;
+
+import java.io.Serializable;
+
+/**
+ * Serializable object to be serialized in DB as is
+ *
+ * @author Emmanuel Bernard
+ */
+public class Country implements Serializable {
+ private String name;
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Flight.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Flight.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Flight.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,49 @@
+//$Id: Flight.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.entity;
+
+import java.io.Serializable;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+import javax.persistence.Table;
+
+import org.hibernate.annotations.Formula;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity()
+@Table(name = "Formula_flight")
+@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
+public class Flight implements Serializable {
+ Long id;
+ long maxAltitudeInMilimeter;
+ long maxAltitude;
+
+ @Id
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long long1) {
+ id = long1;
+ }
+
+ public long getMaxAltitude() {
+ return maxAltitude;
+ }
+
+ public void setMaxAltitude(long maxAltitude) {
+ this.maxAltitude = maxAltitude;
+ }
+
+ @Formula("maxAltitude * 1000")
+ public long getMaxAltitudeInMilimeter() {
+ return maxAltitudeInMilimeter;
+ }
+
+ public void setMaxAltitudeInMilimeter(long maxAltitudeInMilimeter) {
+ this.maxAltitudeInMilimeter = maxAltitudeInMilimeter;
+ }
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Forest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Forest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Forest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,113 @@
+//$Id: Forest.java 17791 2009-10-19 13:16:08Z stliu $
+package org.hibernate.test.annotations.entity;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.Lob;
+
+import org.hibernate.annotations.BatchSize;
+import org.hibernate.annotations.Filter;
+import org.hibernate.annotations.FilterDef;
+import org.hibernate.annotations.Filters;
+import org.hibernate.annotations.Index;
+import org.hibernate.annotations.OptimisticLock;
+import org.hibernate.annotations.OptimisticLockType;
+import org.hibernate.annotations.ParamDef;
+import org.hibernate.annotations.Parameter;
+import org.hibernate.annotations.PolymorphismType;
+import org.hibernate.annotations.Type;
+import org.hibernate.annotations.Where;
+
+/**
+ * Use hibernate specific annotations
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity
+@BatchSize(size = 5)
+(a)org.hibernate.annotations.Entity(
+ selectBeforeUpdate = true,
+ dynamicInsert = true, dynamicUpdate = true,
+ optimisticLock = OptimisticLockType.ALL,
+ polymorphism = PolymorphismType.EXPLICIT)
+@Where(clause = "1=1")
+@FilterDef(name = "minLength", parameters = {@ParamDef(name = "minLength", type = "integer")})
+@Filters({
+@Filter(name = "betweenLength"),
+@Filter(name = "minLength", condition = ":minLength <= length")
+ })
+(a)org.hibernate.annotations.Table(appliesTo = "Forest",
+ indexes = {@Index(name = "idx", columnNames = {"name", "length"})})
+public class Forest {
+ private Integer id;
+ private String name;
+ private long length;
+ private String longDescription;
+ private String smallText;
+ private String bigText;
+ private Country country;
+
+ @OptimisticLock(excluded=true)
+ @Type(type = "text")
+ public String getLongDescription() {
+ return longDescription;
+ }
+
+ public void setLongDescription(String longDescription) {
+ this.longDescription = longDescription;
+ }
+
+ public long getLength() {
+ return length;
+ }
+
+ public void setLength(long length) {
+ this.length = length;
+ }
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @Type(type = "caster")
+ public String getSmallText() {
+ return smallText;
+ }
+
+ @Type(type = "caster", parameters = {@Parameter(name = "cast", value = "upper")})
+ public String getBigText() {
+ return bigText;
+ }
+
+ public void setSmallText(String smallText) {
+ this.smallText = smallText;
+ }
+
+ public void setBigText(String bigText) {
+ this.bigText = bigText;
+ }
+
+ @Lob
+ public Country getCountry() {
+ return country;
+ }
+
+ public void setCountry(Country country) {
+ this.country = country;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Java5FeaturesTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Java5FeaturesTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Java5FeaturesTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,125 @@
+//$Id: Java5FeaturesTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.entity;
+
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class Java5FeaturesTest extends TestCase {
+ public void testInterface() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Race r = new Race();
+ r.setId( new Integer( 1 ) );
+ r.setLength( new Long( 3 ) );
+ s.persist( r );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ r = (Race) s.get( Race.class, r.getId() );
+ assertEquals( new Long( 3 ), r.getLength() );
+ tx.commit();
+ s.close();
+
+ }
+
+ public void testEnums() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ CommunityBid communityBid = new CommunityBid();
+ communityBid.setId( new Integer( 2 ) );
+ communityBid.setCommunityNote( Starred.OK );
+ Bid bid = new Bid();
+ bid.setId( new Integer( 1 ) );
+ bid.setDescription( "My best one" );
+ bid.setNote( Starred.OK );
+ bid.setEditorsNote( Starred.GOOD );
+ s.persist( bid );
+ s.persist( communityBid );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ //bid = (Bid) s.get( Bid.class, bid.getId() );
+ bid = (Bid)s.createQuery( "select b from Bid b where b.note = " +
+ Starred.class.getName() + ".OK and b.editorsNote = " +
+ Starred.class.getName() + ".GOOD and b.id = :id")
+ .setParameter( "id", bid.getId() ).uniqueResult();
+ //testing constant value
+ assertEquals( Starred.OK, bid.getNote() );
+ assertEquals( Starred.GOOD, bid.getEditorsNote() );
+ bid = (Bid)s.createQuery( "select b from Bid b where b.note = :note" +
+ " and b.editorsNote = :editorNote " +
+ " and b.id = :id")
+ .setParameter( "id", bid.getId() )
+ .setParameter( "note", Starred.OK )
+ .setParameter( "editorNote", Starred.GOOD )
+ .uniqueResult();
+ //testing constant value
+ assertEquals( Starred.OK, bid.getNote() );
+ assertEquals( Starred.GOOD, bid.getEditorsNote() );
+ bid.setNote( null );
+ tx.commit();
+ s.clear();
+ tx = s.beginTransaction();
+ bid = (Bid) s.get( Bid.class, bid.getId() );
+ communityBid = (CommunityBid) s.get( CommunityBid.class, communityBid.getId() );
+ assertNull( bid.getNote() );
+ assertEquals( Starred.OK, communityBid.getCommunityNote() );
+ s.delete( bid );
+ s.clear();
+ communityBid = (CommunityBid) s.createSQLQuery( "select {b.*} from Bid b where b.id = ?" )
+ .addEntity( "b", CommunityBid.class )
+ .setInteger( 0, communityBid.getId() ).uniqueResult();
+ assertEquals( Starred.OK, communityBid.getCommunityNote() );
+ s.delete( communityBid );
+ tx.commit();
+ s.close();
+ }
+
+ public void testAutoboxing() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Bid bid = new Bid();
+ bid.setId( new Integer( 2 ) );
+ bid.setDescription( "My best one" );
+ bid.setNote( Starred.OK );
+ bid.setEditorsNote( Starred.GOOD );
+ bid.setApproved( null );
+ s.persist( bid );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ bid = (Bid) s.get( Bid.class, bid.getId() );
+ assertEquals( null, bid.getApproved() );
+ s.delete( bid );
+ tx.commit();
+ s.close();
+ }
+
+ public Java5FeaturesTest(String x) {
+ super( x );
+ }
+
+ protected Class[] getMappings() {
+ return new Class[]{
+ Race.class,
+ Bid.class,
+ CommunityBid.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Length.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Length.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Length.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,9 @@
+//$Id: Length.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.entity;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public interface Length<Type> {
+ Type getLength();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/MonetaryAmount.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/MonetaryAmount.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/MonetaryAmount.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,36 @@
+//$Id: MonetaryAmount.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.entity;
+
+import java.io.Serializable;
+import java.math.BigDecimal;
+import java.util.Currency;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class MonetaryAmount implements Serializable {
+
+ private BigDecimal amount;
+ private Currency currency;
+
+ public MonetaryAmount(BigDecimal amount, Currency currency) {
+ this.amount = amount;
+ this.currency = currency;
+ }
+
+ public BigDecimal getAmount() {
+ return amount;
+ }
+
+ public void setAmount(BigDecimal amount) {
+ this.amount = amount;
+ }
+
+ public Currency getCurrency() {
+ return currency;
+ }
+
+ public void setCurrency(Currency currency) {
+ this.currency = currency;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/MonetaryAmountUserType.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/MonetaryAmountUserType.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/MonetaryAmountUserType.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,106 @@
+//$Id: MonetaryAmountUserType.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.entity;
+
+import java.io.Serializable;
+import java.math.BigDecimal;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.Currency;
+
+import org.hibernate.Hibernate;
+import org.hibernate.HibernateException;
+import org.hibernate.engine.SessionImplementor;
+import org.hibernate.type.Type;
+import org.hibernate.usertype.CompositeUserType;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class MonetaryAmountUserType implements CompositeUserType {
+
+ public String[] getPropertyNames() {
+ return new String[]{"amount", "currency"};
+ }
+
+ public Type[] getPropertyTypes() {
+ return new Type[]{Hibernate.BIG_DECIMAL, Hibernate.CURRENCY};
+ }
+
+ public Object getPropertyValue(Object component, int property) throws HibernateException {
+ MonetaryAmount ma = (MonetaryAmount) component;
+ return property == 0 ? (Object) ma.getAmount() : (Object) ma.getCurrency();
+ }
+
+ public void setPropertyValue(Object component, int property, Object value)
+ throws HibernateException {
+ MonetaryAmount ma = (MonetaryAmount) component;
+ if ( property == 0 ) {
+ ma.setAmount( (BigDecimal) value );
+ }
+ else {
+ ma.setCurrency( (Currency) value );
+ }
+ }
+
+ public Class returnedClass() {
+ return MonetaryAmount.class;
+ }
+
+ public boolean equals(Object x, Object y) throws HibernateException {
+ if ( x == y ) return true;
+ if ( x == null || y == null ) return false;
+ MonetaryAmount mx = (MonetaryAmount) x;
+ MonetaryAmount my = (MonetaryAmount) y;
+ return mx.getAmount().equals( my.getAmount() ) &&
+ mx.getCurrency().equals( my.getCurrency() );
+ }
+
+ public int hashCode(Object x) throws HibernateException {
+ return ( (MonetaryAmount) x ).getAmount().hashCode();
+ }
+
+ public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner)
+ throws HibernateException, SQLException {
+ BigDecimal amt = (BigDecimal) Hibernate.BIG_DECIMAL.nullSafeGet( rs, names[0] );
+ Currency cur = (Currency) Hibernate.CURRENCY.nullSafeGet( rs, names[1] );
+ if ( amt == null ) return null;
+ return new MonetaryAmount( amt, cur );
+ }
+
+ public void nullSafeSet(
+ PreparedStatement st, Object value, int index,
+ SessionImplementor session
+ ) throws HibernateException, SQLException {
+ MonetaryAmount ma = (MonetaryAmount) value;
+ BigDecimal amt = ma == null ? null : ma.getAmount();
+ Currency cur = ma == null ? null : ma.getCurrency();
+ Hibernate.BIG_DECIMAL.nullSafeSet( st, amt, index );
+ Hibernate.CURRENCY.nullSafeSet( st, cur, index + 1 );
+ }
+
+ public Object deepCopy(Object value) throws HibernateException {
+ MonetaryAmount ma = (MonetaryAmount) value;
+ return new MonetaryAmount( ma.getAmount(), ma.getCurrency() );
+ }
+
+ public boolean isMutable() {
+ return true;
+ }
+
+ public Serializable disassemble(Object value, SessionImplementor session)
+ throws HibernateException {
+ return (Serializable) deepCopy( value );
+ }
+
+ public Object assemble(Serializable cached, SessionImplementor session, Object owner)
+ throws HibernateException {
+ return deepCopy( cached );
+ }
+
+ public Object replace(Object original, Object target, SessionImplementor session, Object owner)
+ throws HibernateException {
+ return deepCopy( original ); //TODO: improve
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/PropertyDefaultMappingsTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/PropertyDefaultMappingsTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/PropertyDefaultMappingsTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,62 @@
+//$Id: PropertyDefaultMappingsTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.entity;
+
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class PropertyDefaultMappingsTest extends TestCase {
+ public PropertyDefaultMappingsTest(String x) {
+ super( x );
+ }
+
+ public void testSerializableObject() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Country c = new Country();
+ c.setName( "France" );
+ Address a = new Address();
+ a.setCity( "Paris" );
+ a.setCountry( c );
+ s.persist( a );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ Address reloadedAddress = (Address) s.get( Address.class, a.getId() );
+ assertNotNull( reloadedAddress );
+ assertNotNull( reloadedAddress.getCountry() );
+ assertEquals( a.getCountry().getName(), reloadedAddress.getCountry().getName() );
+ tx.rollback();
+ s.close();
+ }
+
+ public void testTransientField() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ WashingMachine wm = new WashingMachine();
+ wm.setActive( true );
+ s.persist( wm );
+ tx.commit();
+ s.clear();
+ tx = s.beginTransaction();
+ wm = (WashingMachine) s.get( WashingMachine.class, wm.getId() );
+ assertFalse( "transient should not be persistent", wm.isActive() );
+ s.delete( wm );
+ tx.commit();
+ s.close();
+ }
+
+ protected Class[] getMappings() {
+ return new Class[]{
+ Address.class,
+ WashingMachine.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Race.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Race.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Race.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,31 @@
+//$Id: Race.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.entity;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Race implements Length<Long> {
+ private Long length;
+ private Integer id;
+
+ @Id
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public Long getLength() {
+ return length;
+ }
+
+ public void setLength(Long length) {
+ this.length = length;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Ransom.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Ransom.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Ransom.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,61 @@
+//$Id: Ransom.java 15049 2008-08-13 15:32:32Z epbernard $
+package org.hibernate.test.annotations.entity;
+
+import java.util.Date;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+import org.hibernate.annotations.Columns;
+import org.hibernate.annotations.Type;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Ransom {
+ private Integer id;
+ private String kidnapperName;
+ private MonetaryAmount amount;
+ private Date date;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getKidnapperName() {
+ return kidnapperName;
+ }
+
+ public void setKidnapperName(String kidnapperName) {
+ this.kidnapperName = kidnapperName;
+ }
+
+ @Type(type = "org.hibernate.test.annotations.entity.MonetaryAmountUserType")
+ @Columns(columns = {
+ @Column(name = "r_amount"),
+ @Column(name = "r_currency")
+ })
+ public MonetaryAmount getAmount() {
+ return amount;
+ }
+
+ public void setAmount(MonetaryAmount amount) {
+ this.amount = amount;
+ }
+ @Column(name="ransom_date")
+ public Date getDate() {
+ return date;
+ }
+
+ public void setDate(Date date) {
+ this.date = date;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Starred.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Starred.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Starred.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,10 @@
+package org.hibernate.test.annotations.entity;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public enum Starred {
+ BAD,
+ OK,
+ GOOD
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Tree.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Tree.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/Tree.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,38 @@
+//$Id: Tree.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.entity;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+import org.hibernate.annotations.Proxy;
+
+/**
+ * Non lazy entity
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Proxy(lazy = false)
+public class Tree {
+ private Integer id;
+ private String name;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/WashingMachine.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/WashingMachine.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/WashingMachine.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,33 @@
+//$Id: WashingMachine.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.entity;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class WashingMachine {
+ @Id
+ @GeneratedValue
+ private Integer id;
+ private transient boolean isActive;
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public boolean isActive() {
+ return isActive;
+ }
+
+ public void setActive(boolean active) {
+ isActive = active;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/ZipCode.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/ZipCode.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/ZipCode.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,19 @@
+//$Id: ZipCode.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.entity;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+import org.hibernate.annotations.Cache;
+import org.hibernate.annotations.CacheConcurrencyStrategy;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
+@Entity
+(a)org.hibernate.annotations.Entity(mutable = false)
+public class ZipCode {
+ @Id
+ public String code;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/package-info.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/package-info.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/package-info.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,34 @@
+/**
+ * Test package for metatata facilities
+ * It contains an example of filter metadata
+ */
+@FilterDefs(
+ {
+ @FilterDef(
+ name = "betweenLength",
+ defaultCondition = ":minLength <= length and :maxLength >= length",
+ parameters = {
+ @ParamDef(name = "minLength", type = "integer"),
+ @ParamDef(name = "maxLength", type = "integer")
+ }
+ )
+ }
+)
+@TypeDefs(
+ {
+ @TypeDef(
+ name = "caster",
+ typeClass = CasterStringType.class,
+ parameters = {
+ @Parameter(name = "cast", value = "lower")
+ }
+ )
+ }
+) package org.hibernate.test.annotations.entity;
+
+import org.hibernate.annotations.FilterDef;
+import org.hibernate.annotations.FilterDefs;
+import org.hibernate.annotations.ParamDef;
+import org.hibernate.annotations.Parameter;
+import org.hibernate.annotations.TypeDef;
+import org.hibernate.annotations.TypeDefs;
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entitynonentity/Cellular.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entitynonentity/Cellular.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entitynonentity/Cellular.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,9 @@
+//$Id: Cellular.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.entitynonentity;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class Cellular extends Phone {
+ String brand;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entitynonentity/Communication.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entitynonentity/Communication.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entitynonentity/Communication.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,9 @@
+//$Id: Communication.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.entitynonentity;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class Communication extends Interaction {
+ String species;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entitynonentity/EntityNonEntityTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entitynonentity/EntityNonEntityTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entitynonentity/EntityNonEntityTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,43 @@
+//$Id: EntityNonEntityTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.entitynonentity;
+
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class EntityNonEntityTest extends TestCase {
+ public void testMix() throws Exception {
+ GSM gsm = new GSM();
+ gsm.brand = "Sony";
+ gsm.frequency = 900;
+ gsm.isNumeric = true;
+ gsm.number = 2;
+ gsm.species = "human";
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ s.persist( gsm );
+ tx.commit();
+ s.clear();
+ tx = s.beginTransaction();
+ gsm = (GSM) s.get( GSM.class, gsm.id );
+ assertEquals( "top mapped superclass", 2, gsm.number );
+ assertNull( "non entity between mapped superclass and entity", gsm.species );
+ assertTrue( "mapped superclass under entity", gsm.isNumeric );
+ assertNull( "non entity under entity", gsm.brand );
+ assertEquals( "leaf entity", 900, gsm.frequency );
+ s.delete( gsm );
+ tx.commit();
+ s.close();
+ }
+
+ protected Class[] getMappings() {
+ return new Class[]{
+ Phone.class,
+ Voice.class,
+ GSM.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entitynonentity/GSM.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entitynonentity/GSM.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entitynonentity/GSM.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,12 @@
+//$Id: GSM.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.entitynonentity;
+
+import javax.persistence.Entity;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class GSM extends Cellular {
+ int frequency;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entitynonentity/Interaction.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entitynonentity/Interaction.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entitynonentity/Interaction.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,14 @@
+//$Id: Interaction.java 15049 2008-08-13 15:32:32Z epbernard $
+package org.hibernate.test.annotations.entitynonentity;
+
+import javax.persistence.MappedSuperclass;
+import javax.persistence.Column;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@MappedSuperclass
+public class Interaction {
+ @Column(name="int_nbr")
+ public int number;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entitynonentity/Phone.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entitynonentity/Phone.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entitynonentity/Phone.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,12 @@
+//$Id: Phone.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.entitynonentity;
+
+import javax.persistence.MappedSuperclass;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@MappedSuperclass
+public class Phone extends Voice {
+ boolean isNumeric;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entitynonentity/Voice.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entitynonentity/Voice.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entitynonentity/Voice.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,19 @@
+//$Id: Voice.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.entitynonentity;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Inheritance(strategy = InheritanceType.JOINED)
+public class Voice extends Communication {
+ @Id
+ @GeneratedValue
+ public Integer id;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fetch/Branch.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fetch/Branch.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fetch/Branch.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,40 @@
+//$Id: Branch.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.fetch;
+
+import java.util.Set;
+import java.util.HashSet;
+import javax.persistence.Id;
+import javax.persistence.GeneratedValue;
+import javax.persistence.OneToMany;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Branch {
+ @Id
+ @GeneratedValue
+ private Integer id;
+
+ @OneToMany(mappedBy = "branch", fetch = FetchType.EAGER )
+ private Set<Leaf> leaves = new HashSet<Leaf>();
+
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public Set<Leaf> getLeaves() {
+ return leaves;
+ }
+
+ public void setLeaves(Set<Leaf> leaves) {
+ this.leaves = leaves;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fetch/FetchingTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fetch/FetchingTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fetch/FetchingTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,125 @@
+//$Id: FetchingTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.fetch;
+
+import java.util.Date;
+
+import org.hibernate.Hibernate;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class FetchingTest extends TestCase {
+ public void testLazy() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Person p = new Person( "Gavin", "King", "JBoss Inc" );
+ Stay stay = new Stay( p, new Date(), new Date(), "A380", "Blah", "Blah" );
+ p.addStay( stay );
+ s.persist( p );
+ tx.commit();
+ s.clear();
+ tx = s.beginTransaction();
+ p = (Person) s.createQuery( "from Person p where p.firstName = :name" )
+ .setParameter( "name", "Gavin" ).uniqueResult();
+ assertFalse( Hibernate.isInitialized( p.getStays() ) );
+ s.delete( p );
+ tx.commit();
+ s.close();
+ }
+
+ public void testExtraLazy() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Person p = new Person( "Gavin", "King", "JBoss Inc" );
+ Stay stay = new Stay( p, new Date(), new Date(), "A380", "Blah", "Blah" );
+ p.getOrderedStay().add( stay );
+ s.persist( p );
+ tx.commit();
+ s.clear();
+ tx = s.beginTransaction();
+ p = (Person) s.createQuery( "from Person p where p.firstName = :name" )
+ .setParameter( "name", "Gavin" ).uniqueResult();
+ assertFalse( Hibernate.isInitialized( p.getOrderedStay() ) );
+ assertEquals( 1, p.getOrderedStay().size() );
+ assertFalse( Hibernate.isInitialized( p.getOrderedStay() ) );
+ assertEquals( "A380", p.getOrderedStay().get(0).getVessel() );
+ assertFalse( Hibernate.isInitialized( p.getOrderedStay() ) );
+ s.delete( p );
+ tx.commit();
+ s.close();
+ }
+
+ public void testHibernateFetchingLazy() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Person p = new Person( "Gavin", "King", "JBoss Inc" );
+ Stay stay = new Stay( null, new Date(), new Date(), "A380", "Blah", "Blah" );
+ Stay stay2 = new Stay( null, new Date(), new Date(), "A320", "Blah", "Blah" );
+ Stay stay3 = new Stay( null, new Date(), new Date(), "A340", "Blah", "Blah" );
+ stay.setOldPerson( p );
+ stay2.setVeryOldPerson( p );
+ stay3.setVeryOldPerson( p );
+ p.addOldStay( stay );
+ p.addVeryOldStay( stay2 );
+ p.addVeryOldStay( stay3 );
+ s.persist( p );
+ tx.commit();
+ s.clear();
+ tx = s.beginTransaction();
+ p = (Person) s.createQuery( "from Person p where p.firstName = :name" )
+ .setParameter( "name", "Gavin" ).uniqueResult();
+ assertFalse( Hibernate.isInitialized( p.getOldStays() ) );
+ assertEquals( 1, p.getOldStays().size() );
+ assertFalse( "lazy extra is failing", Hibernate.isInitialized( p.getOldStays() ) );
+ s.clear();
+ stay = (Stay) s.get( Stay.class, stay.getId() );
+ assertTrue( ! Hibernate.isInitialized( stay.getOldPerson() ) );
+ s.clear();
+ stay3 = (Stay) s.get( Stay.class, stay3.getId() );
+ assertTrue( "FetchMode.JOIN should overrides lazy options", Hibernate.isInitialized( stay3.getVeryOldPerson() ) );
+ s.delete( stay3.getVeryOldPerson() );
+ tx.commit();
+ s.close();
+ }
+
+ public void testOneToManyFetchEager() throws Exception {
+ Branch b = new Branch();
+ Session s = openSession( );
+ s.getTransaction().begin();
+ s.persist( b );
+ s.flush();
+ Leaf l = new Leaf();
+ l.setBranch( b );
+ s.persist( l );
+ s.flush();
+
+ s.clear();
+
+ s.createCriteria( Branch.class ).list();
+
+ s.getTransaction().rollback();
+ s.close();
+ }
+
+ public FetchingTest(String x) {
+ super( x );
+ }
+
+ protected Class[] getMappings() {
+ return new Class[]{
+ Person.class,
+ Stay.class,
+ Branch.class,
+ Leaf.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fetch/Leaf.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fetch/Leaf.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fetch/Leaf.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,37 @@
+//$Id: Leaf.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.fetch;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.ManyToOne;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Leaf {
+ @Id
+ @GeneratedValue
+ private Integer id;
+
+ @ManyToOne
+ private Branch branch;
+
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public Branch getBranch() {
+ return branch;
+ }
+
+ public void setBranch(Branch branch) {
+ this.branch = branch;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fetch/Person.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fetch/Person.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fetch/Person.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,176 @@
+//$Id: Person.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.fetch;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Date;
+import java.util.List;
+import javax.persistence.CascadeType;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.OneToMany;
+import javax.persistence.Table;
+
+import org.hibernate.annotations.Fetch;
+import org.hibernate.annotations.FetchMode;
+import org.hibernate.annotations.LazyCollection;
+import org.hibernate.annotations.LazyCollectionOption;
+import org.hibernate.annotations.IndexColumn;
+
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Table(name = "Person")
+public class Person implements Serializable {
+
+ // member declaration
+ private int id;
+ private String firstName;
+ private String lastName;
+ private String companyName;
+ private Collection<Stay> stays;
+ private Collection<Stay> oldStays;
+ private Collection<Stay> veryOldStays;
+ private List<Stay> orderedStay = new ArrayList<Stay>();
+
+ // constructors
+ public Person() {
+ }
+
+ public Person(String firstName, String lastName, String companyName) {
+ this.firstName = firstName;
+ this.lastName = lastName;
+ this.companyName = companyName;
+ }
+
+ // properties
+ public String getCompanyName() {
+ return companyName;
+ }
+
+ public void setCompanyName(String companyName) {
+ this.companyName = companyName;
+ }
+
+ public String getFirstName() {
+ return firstName;
+ }
+
+ public void setFirstName(String firstName) {
+ this.firstName = firstName;
+ }
+
+ @Id
+ @GeneratedValue
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ public String getLastName() {
+ return lastName;
+ }
+
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+
+ // relationships
+
+ @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "person")
+ public Collection<Stay> getStays() {
+ return this.stays;
+ }
+
+ public void setStays(List<Stay> stays) {
+ this.stays = stays;
+ }
+
+ @OneToMany(cascade=CascadeType.ALL, mappedBy = "oldPerson")
+ @LazyCollection(LazyCollectionOption.EXTRA)
+ @Fetch(FetchMode.SUBSELECT)
+ public Collection<Stay> getOldStays() {
+ return oldStays;
+ }
+
+ public void setOldStays(Collection<Stay> oldStays) {
+ this.oldStays = oldStays;
+ }
+
+ @OneToMany(cascade=CascadeType.ALL, mappedBy = "veryOldPerson")
+ @Fetch(FetchMode.SELECT)
+ public Collection<Stay> getVeryOldStays() {
+ return veryOldStays;
+ }
+
+ public void setVeryOldStays(Collection<Stay> veryOldStays) {
+ this.veryOldStays = veryOldStays;
+ }
+
+ @OneToMany(cascade=CascadeType.ALL)
+ @LazyCollection(LazyCollectionOption.EXTRA)
+ @Fetch(FetchMode.SUBSELECT)
+ @IndexColumn(name="orderedStayIndex")
+ public List<Stay> getOrderedStay() {
+ return orderedStay;
+ }
+
+ public void setOrderedStay(List<Stay> orderedStay) {
+ this.orderedStay = orderedStay;
+ }
+
+
+ // business logic
+ public void addStay(Date startDate, Date endDate, String vessel, String authoriser, String comments) {
+ Stay stay = new Stay( this, startDate, endDate, vessel, authoriser, comments );
+ addStay( stay );
+ }
+
+ public void addStay(Stay stay) {
+ Collection<Stay> stays = getStays();
+ if ( stays == null ) {
+ stays = new ArrayList<Stay>();
+ }
+ stays.add( stay );
+
+ this.stays = stays;
+ }
+
+ public void addOldStay(Date startDate, Date endDate, String vessel, String authoriser, String comments) {
+ Stay stay = new Stay( this, startDate, endDate, vessel, authoriser, comments );
+ addOldStay( stay );
+ }
+
+ public void addOldStay(Stay stay) {
+ Collection<Stay> stays = getOldStays();
+ if ( stays == null ) {
+ stays = new ArrayList<Stay>();
+ }
+ stays.add( stay );
+
+ this.oldStays = stays;
+ }
+
+ public void addVeryOldStay(Date startDate, Date endDate, String vessel, String authoriser, String comments) {
+ Stay stay = new Stay( this, startDate, endDate, vessel, authoriser, comments );
+ addVeryOldStay( stay );
+ }
+
+ public void addVeryOldStay(Stay stay) {
+ Collection<Stay> stays = getVeryOldStays();
+ if ( stays == null ) {
+ stays = new ArrayList<Stay>();
+ }
+ stays.add( stay );
+
+ this.veryOldStays = stays;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fetch/Stay.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fetch/Stay.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fetch/Stay.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,143 @@
+//$Id: Stay.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.fetch;
+
+import java.io.Serializable;
+import java.util.Date;
+import javax.persistence.CascadeType;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+import javax.persistence.Table;
+
+import org.hibernate.annotations.LazyToOne;
+import org.hibernate.annotations.LazyToOneOption;
+import org.hibernate.annotations.Fetch;
+import org.hibernate.annotations.FetchMode;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Table(name = "Stay")
+public class Stay implements Serializable {
+
+ // member declaration
+ private int id;
+ private Person person;
+ private Person oldPerson;
+ private Person veryOldPerson;
+ private Date startDate;
+ private Date endDate;
+ private String vessel;
+ private String authoriser;
+ private String comments;
+
+
+ // constructors
+ public Stay() {
+ }
+
+ public Stay(int id) {
+ this.id = id;
+ }
+
+ public Stay(Person person, Date startDate, Date endDate, String vessel, String authoriser, String comments) {
+ this.authoriser = authoriser;
+ this.endDate = endDate;
+ this.person = person;
+ this.startDate = startDate;
+ this.vessel = vessel;
+ this.comments = comments;
+ }
+
+
+ // properties
+ public String getAuthoriser() {
+ return authoriser;
+ }
+
+ public void setAuthoriser(String authoriser) {
+ this.authoriser = authoriser;
+ }
+
+ public String getComments() {
+ return comments;
+ }
+
+ public void setComments(String comments) {
+ this.comments = comments;
+ }
+
+ public Date getEndDate() {
+ return endDate;
+ }
+
+ public void setEndDate(Date endDate) {
+ this.endDate = endDate;
+ }
+
+ @Id
+ @GeneratedValue
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
+ @JoinColumn(name = "person")
+ public Person getPerson() {
+ return person;
+ }
+
+ public void setPerson(Person person) {
+ this.person = person;
+ }
+
+ @ManyToOne(cascade = CascadeType.ALL)
+ @LazyToOne(LazyToOneOption.PROXY)
+ @Fetch(FetchMode.SELECT)
+ @JoinColumn(name = "oldperson")
+ public Person getOldPerson() {
+ return oldPerson;
+ }
+
+ public void setOldPerson(Person oldPerson) {
+ this.oldPerson = oldPerson;
+ }
+
+ @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
+ @LazyToOne(LazyToOneOption.PROXY)
+ @Fetch(FetchMode.JOIN)
+ @JoinColumn(name = "veryoldperson")
+ public Person getVeryOldPerson() {
+ return veryOldPerson;
+ }
+
+ public void setVeryOldPerson(Person veryOldPerson) {
+ this.veryOldPerson = veryOldPerson;
+ }
+
+ public Date getStartDate() {
+ return startDate;
+ }
+
+ public void setStartDate(Date startDate) {
+ this.startDate = startDate;
+ }
+
+ public String getVessel() {
+ return vessel;
+ }
+
+ public void setVessel(String vessel) {
+ this.vessel = vessel;
+ }
+
+
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/A.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/A.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/A.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,25 @@
+// $Id: A.java 14777 2008-06-18 17:47:30Z hardy.ferentschik $
+package org.hibernate.test.annotations.fkcircularity;
+
+import javax.persistence.EmbeddedId;
+import javax.persistence.Entity;
+
+/**
+ * Test entities ANN-722.
+ *
+ * @author Hardy Ferentschik
+ *
+ */
+@Entity
+public class A {
+ private A_PK id;
+
+ @EmbeddedId
+ public A_PK getId() {
+ return id;
+ }
+
+ public void setId(A_PK id) {
+ this.id = id;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/A_PK.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/A_PK.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/A_PK.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,26 @@
+// $Id: A_PK.java 14777 2008-06-18 17:47:30Z hardy.ferentschik $
+package org.hibernate.test.annotations.fkcircularity;
+
+import java.io.Serializable;
+
+import javax.persistence.ManyToOne;
+
+/**
+ * Test entities ANN-722.
+ *
+ * @author Hardy Ferentschik
+ *
+ */
+@SuppressWarnings("serial")
+public class A_PK implements Serializable {
+ public D d;
+
+ @ManyToOne
+ public D getD() {
+ return d;
+ }
+
+ public void setD(D d) {
+ this.d = d;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/B.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/B.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/B.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,28 @@
+// $Id: B.java 14777 2008-06-18 17:47:30Z hardy.ferentschik $
+package org.hibernate.test.annotations.fkcircularity;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+
+/**
+ * Test entities ANN-722.
+ *
+ * @author Hardy Ferentschik
+ *
+ */
+@Entity
+@Inheritance(strategy = InheritanceType.JOINED)
+public class B {
+ @Id
+ private int id;
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/C.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/C.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/C.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,14 @@
+// $Id: C.java 14777 2008-06-18 17:47:30Z hardy.ferentschik $
+package org.hibernate.test.annotations.fkcircularity;
+
+import javax.persistence.Entity;
+
+/**
+ * Test entities ANN-722.
+ *
+ * @author Hardy Ferentschik
+ *
+ */
+@Entity
+public class C extends B {
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/ClassA.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/ClassA.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/ClassA.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,33 @@
+// $Id: ClassA.java 14777 2008-06-18 17:47:30Z hardy.ferentschik $
+package org.hibernate.test.annotations.fkcircularity;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+import javax.persistence.Table;
+
+/**
+ * Test entities ANN-730.
+ *
+ * @author Hardy Ferentschik
+ *
+ */
+@Entity
+@Table(name = "class_a")
+@Inheritance(strategy = InheritanceType.JOINED)
+public class ClassA {
+
+ private int id;
+
+ @Id
+ @Column(name = "id")
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/ClassB.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/ClassB.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/ClassB.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,18 @@
+// $Id: ClassB.java 14777 2008-06-18 17:47:30Z hardy.ferentschik $
+package org.hibernate.test.annotations.fkcircularity;
+
+import javax.persistence.Entity;
+import javax.persistence.PrimaryKeyJoinColumn;
+import javax.persistence.Table;
+
+/**
+ * Test entities ANN-730.
+ *
+ * @author Hardy Ferentschik
+ *
+ */
+@Entity
+@Table(name = "class_b")
+@PrimaryKeyJoinColumn(name = "id", referencedColumnName = "id")
+public class ClassB extends ClassA {
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/ClassC.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/ClassC.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/ClassC.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,18 @@
+// $Id: ClassC.java 14777 2008-06-18 17:47:30Z hardy.ferentschik $
+package org.hibernate.test.annotations.fkcircularity;
+
+import javax.persistence.Entity;
+import javax.persistence.PrimaryKeyJoinColumn;
+import javax.persistence.Table;
+
+/**
+ * Test entities ANN-730.
+ *
+ * @author Hardy Ferentschik
+ *
+ */
+@Entity
+@Table(name = "class_c")
+@PrimaryKeyJoinColumn(name = "id", referencedColumnName = "id")
+public class ClassC extends ClassB {
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/ClassD.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/ClassD.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/ClassD.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,18 @@
+// $Id: ClassD.java 14777 2008-06-18 17:47:30Z hardy.ferentschik $
+package org.hibernate.test.annotations.fkcircularity;
+
+import javax.persistence.Entity;
+import javax.persistence.PrimaryKeyJoinColumn;
+import javax.persistence.Table;
+
+/**
+ * Test entities ANN-730.
+ *
+ * @author Hardy Ferentschik
+ *
+ */
+@Entity
+@Table(name = "class_1d")
+@PrimaryKeyJoinColumn(name = "id", referencedColumnName = "id")
+public class ClassD extends ClassC {
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/D.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/D.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/D.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,25 @@
+// $Id: D.java 14777 2008-06-18 17:47:30Z hardy.ferentschik $
+package org.hibernate.test.annotations.fkcircularity;
+
+import javax.persistence.EmbeddedId;
+import javax.persistence.Entity;
+
+/**
+ * Test entities ANN-722.
+ *
+ * @author Hardy Ferentschik
+ *
+ */
+@Entity
+public class D {
+ private D_PK id;
+
+ @EmbeddedId
+ public D_PK getId() {
+ return id;
+ }
+
+ public void setId(D_PK id) {
+ this.id = id;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/D_PK.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/D_PK.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/D_PK.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,26 @@
+// $Id: D_PK.java 14777 2008-06-18 17:47:30Z hardy.ferentschik $
+package org.hibernate.test.annotations.fkcircularity;
+
+import java.io.Serializable;
+
+import javax.persistence.ManyToOne;
+
+/**
+ * Test entities ANN-722.
+ *
+ * @author Hardy Ferentschik
+ *
+ */
+@SuppressWarnings("serial")
+public class D_PK implements Serializable{
+ private C c;
+
+ @ManyToOne
+ public C getC() {
+ return c;
+ }
+
+ public void setC(C c) {
+ this.c = c;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/FkCircularityTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/FkCircularityTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/fkcircularity/FkCircularityTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,67 @@
+// $Id: FkCircularityTest.java 14777 2008-06-18 17:47:30Z hardy.ferentschik $
+package org.hibernate.test.annotations.fkcircularity;
+
+import java.io.PrintWriter;
+import java.io.StringWriter;
+
+import junit.framework.TestCase;
+
+import org.hibernate.cfg.AnnotationConfiguration;
+import org.hibernate.dialect.HSQLDialect;
+import org.hibernate.dialect.SQLServerDialect;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Test case for ANN-722 and ANN-730.
+ *
+ * @author Hardy Ferentschik
+ */
+public class FkCircularityTest extends TestCase {
+
+ private Logger log = LoggerFactory.getLogger(FkCircularityTest.class);
+
+ public void testJoinedSublcassesInPK() {
+ try {
+ AnnotationConfiguration config = new AnnotationConfiguration();
+ config.addAnnotatedClass(A.class);
+ config.addAnnotatedClass(B.class);
+ config.addAnnotatedClass(C.class);
+ config.addAnnotatedClass(D.class);
+ config.buildSessionFactory();
+ String[] schema = config
+ .generateSchemaCreationScript(new SQLServerDialect());
+ for (String s : schema) {
+ log.debug(s);
+ }
+ log.debug("success");
+ } catch (Exception e) {
+ StringWriter writer = new StringWriter();
+ e.printStackTrace(new PrintWriter(writer));
+ log.debug(writer.toString());
+ fail(e.getMessage());
+ }
+ }
+
+ public void testDeepJoinedSuclassesHierachy() {
+ try {
+ AnnotationConfiguration config = new AnnotationConfiguration();
+ config.addAnnotatedClass(ClassA.class);
+ config.addAnnotatedClass(ClassB.class);
+ config.addAnnotatedClass(ClassC.class);
+ config.addAnnotatedClass(ClassD.class);
+ config.buildSessionFactory();
+ String[] schema = config
+ .generateSchemaCreationScript(new HSQLDialect());
+ for (String s : schema) {
+ log.debug(s);
+ }
+ log.debug("success");
+ } catch (Exception e) {
+ StringWriter writer = new StringWriter();
+ e.printStackTrace(new PrintWriter(writer));
+ log.debug(writer.toString());
+ fail(e.getMessage());
+ }
+ }
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/Classes.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/Classes.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/Classes.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,47 @@
+package org.hibernate.test.annotations.generics;
+
+/**
+ * A test case for ANN-494.
+ *
+ * @author Edward Costello
+ * @author Paolo Perrotta
+ */
+import java.util.HashSet;
+import java.util.Set;
+
+import javax.persistence.Embeddable;
+import javax.persistence.Embedded;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+
+import org.hibernate.annotations.CollectionOfElements;
+
+public class Classes {
+
+ @Embeddable
+ public static class Edition<T> {
+ T name;
+ }
+
+ @Entity
+ public static class Book {
+ @Id
+ @GeneratedValue(strategy=GenerationType.AUTO)
+ Long id;
+
+ @Embedded
+ Edition<String> edition;
+ }
+
+ @Entity
+ public static class PopularBook {
+ @Id
+ @GeneratedValue(strategy=GenerationType.AUTO)
+ Long id;
+
+ @CollectionOfElements
+ Set<Edition<String>> editions = new HashSet<Edition<String>>();
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/DNA.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/DNA.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/DNA.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,25 @@
+//$Id: DNA.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.generics;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * @author Paolo Perrotta
+ */
+@Entity
+public class DNA {
+
+ private Integer id;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/Dummy.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/Dummy.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/Dummy.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,36 @@
+//$
+package org.hibernate.test.annotations.generics;
+
+import javax.persistence.Transient;
+import javax.persistence.Id;
+import javax.persistence.Entity;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Dummy<K> {
+
+ @Id
+ private Long id;
+
+ @Transient
+ transient private K dummyField;
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public K getDummyField() {
+ return dummyField;
+ }
+
+ public void setDummyField(K dummyField) {
+ this.dummyField = dummyField;
+ }
+
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/EmbeddedGenericsTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/EmbeddedGenericsTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/EmbeddedGenericsTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,73 @@
+package org.hibernate.test.annotations.generics;
+
+/**
+ * A test case for ANN-494.
+ *
+ * @author Edward Costello
+ * @author Paolo Perrotta
+ */
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.annotations.TestCase;
+
+public class EmbeddedGenericsTest extends TestCase {
+
+ Session session;
+ Classes.Edition<String> edition;
+
+ public void setUp() throws Exception {
+ super.setUp();
+ session = openSession();
+ session.getTransaction().begin();
+ edition = new Classes.Edition<String>();
+ edition.name = "Second";
+ }
+
+ public void testWorksWithGenericEmbedded() {
+ Classes.Book b = new Classes.Book();
+ b.edition = edition;
+ persist( b );
+
+ Classes.Book retrieved = (Classes.Book)find( Classes.Book.class, b.id );
+ assertEquals( "Second", retrieved.edition.name );
+
+ clean( Classes.Book.class, b.id );
+ session.close();
+ }
+
+ public void testWorksWithGenericCollectionOfElements() {
+ Classes.PopularBook b = new Classes.PopularBook();
+ b.editions.add( edition );
+ persist( b );
+
+ Classes.PopularBook retrieved = (Classes.PopularBook)find( Classes.PopularBook.class, b.id );
+ assertEquals( "Second", retrieved.editions.iterator().next().name );
+
+ clean( Classes.PopularBook.class, b.id );
+ session.close();
+ }
+
+ protected Class[] getMappings() {
+ return new Class[]{
+ Classes.Book.class,
+ Classes.PopularBook.class
+ };
+ }
+
+ private void persist(Object data) {
+ session.persist( data );
+ session.getTransaction().commit();
+ session.clear();
+ }
+
+ private Object find(Class clazz, Long id) {
+ return session.get( clazz, id );
+ }
+
+ private void clean(Class<?> clazz, Long id) {
+ Transaction tx = session.beginTransaction();
+ session.delete( find( clazz, id ) );
+ tx.commit();
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/Gene.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/Gene.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/Gene.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,45 @@
+package org.hibernate.test.annotations.generics;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.ManyToOne;
+
+import org.hibernate.annotations.Type;
+
+/**
+ * @author Paolo Perrotta
+ */
+@Entity
+public class Gene<T, STE extends Enum> {
+
+ private Integer id;
+ private STE state;
+
+ @Type(type="org.hibernate.test.annotations.generics.StateType")
+ public STE getState() {
+ return state;
+ }
+
+ public void setState(STE state) {
+ this.state = state;
+ }
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ @ManyToOne(targetEntity = DNA.class)
+ public T getGeneticCode() {
+ return null;
+ }
+
+ public void setGeneticCode(T gene) {
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/GenericsTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/GenericsTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/GenericsTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,63 @@
+//$Id: GenericsTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.generics;
+
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.cfg.Environment;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class GenericsTest extends TestCase {
+ public void testManyToOneGenerics() throws Exception {
+ Paper white = new Paper();
+ white.setName( "WhiteA4" );
+ PaperType type = new PaperType();
+ type.setName( "A4" );
+ SomeGuy me = new SomeGuy();
+ white.setType( type );
+ white.setOwner( me );
+ Price price = new Price();
+ price.setAmount( new Double( 1 ) );
+ price.setCurrency( "Euro" );
+ white.setValue( price );
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ s.persist( type );
+ s.persist( price );
+ s.persist( me );
+ s.persist( white );
+ tx.commit();
+ //s.close();
+ s = openSession();
+ tx = s.beginTransaction();
+ white = (Paper) s.get( Paper.class, white.getId() );
+ s.delete( white.getType() );
+ s.delete( white.getOwner() );
+ s.delete( white.getValue() );
+ s.delete( white );
+ tx.commit();
+ //s.close();
+ }
+
+ @Override
+ protected void configure(Configuration cfg) {
+ cfg.setProperty( Environment.AUTO_CLOSE_SESSION, "true" );
+ super.configure( cfg );
+ }
+
+ protected Class[] getMappings() {
+ return new Class[]{
+ Paper.class,
+ PaperType.class,
+ SomeGuy.class,
+ Price.class,
+ WildEntity.class,
+
+ //test at deployment only test unbound property when default field access is used
+ Dummy.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/Item.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/Item.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/Item.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,54 @@
+//$Id: Item.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.generics;
+
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.ManyToOne;
+import javax.persistence.MappedSuperclass;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@MappedSuperclass
+public class Item<Type, Owner> extends PricedStuff {
+ private Integer id;
+ private String name;
+ private Type type;
+ private Owner owner;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @ManyToOne
+ public Type getType() {
+ return type;
+ }
+
+ public void setType(Type type) {
+ this.type = type;
+ }
+
+ @ManyToOne
+ public Owner getOwner() {
+ return owner;
+ }
+
+ public void setOwner(Owner owner) {
+ this.owner = owner;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/Paper.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/Paper.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/Paper.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,11 @@
+//$Id: Paper.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.generics;
+
+import javax.persistence.Entity;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Paper extends Item<PaperType, SomeGuy> {
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/PaperType.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/PaperType.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/PaperType.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,34 @@
+//$Id: PaperType.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.generics;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class PaperType {
+ private Integer id;
+ private String name;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/Price.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/Price.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/Price.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,42 @@
+//$Id: Price.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.generics;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Price {
+ private Integer id;
+ private Double amount;
+ private String currency;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public Double getAmount() {
+ return amount;
+ }
+
+ public void setAmount(Double amount) {
+ this.amount = amount;
+ }
+
+ public String getCurrency() {
+ return currency;
+ }
+
+ public void setCurrency(String currency) {
+ this.currency = currency;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/PricedStuff.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/PricedStuff.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/PricedStuff.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,11 @@
+//$Id: PricedStuff.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.generics;
+
+import javax.persistence.MappedSuperclass;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@MappedSuperclass
+public class PricedStuff extends Stuff<Price> {
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/SomeGuy.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/SomeGuy.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/SomeGuy.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,24 @@
+//$Id: SomeGuy.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.generics;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class SomeGuy {
+ private Integer id;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/State.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/State.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/State.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,10 @@
+//$Id: State.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.generics;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public enum State {
+ ACTIVE,
+ DORMANT
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/StateType.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/StateType.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/StateType.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,69 @@
+//$Id: StateType.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.generics;
+
+import java.io.Serializable;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.PreparedStatement;
+import java.sql.Types;
+
+import org.hibernate.usertype.UserType;
+import org.hibernate.HibernateException;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class StateType implements UserType {
+ public int[] sqlTypes() {
+ return new int[] {
+ Types.INTEGER
+ };
+ }
+
+ public Class returnedClass() {
+ return State.class;
+ }
+
+ public boolean equals(Object x, Object y) throws HibernateException {
+ return x == y;
+ }
+
+ public int hashCode(Object x) throws HibernateException {
+ return x.hashCode();
+ }
+
+ public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
+ int result = rs.getInt( names[0] );
+ if ( rs.wasNull() ) return null;
+ return State.values()[result];
+ }
+
+ public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
+ if (value == null) {
+ st.setNull( index, Types.INTEGER );
+ }
+ else {
+ st.setInt( index, ( (State) value ).ordinal() );
+ }
+ }
+
+ public Object deepCopy(Object value) throws HibernateException {
+ return value;
+ }
+
+ public boolean isMutable() {
+ return false;
+ }
+
+ public Serializable disassemble(Object value) throws HibernateException {
+ return (Serializable) value;
+ }
+
+ public Object assemble(Serializable cached, Object owner) throws HibernateException {
+ return cached;
+ }
+
+ public Object replace(Object original, Object target, Object owner) throws HibernateException {
+ return original;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/Stuff.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/Stuff.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/Stuff.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,22 @@
+//$Id: Stuff.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.generics;
+
+import javax.persistence.ManyToOne;
+import javax.persistence.MappedSuperclass;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@MappedSuperclass
+public class Stuff<Value> {
+ private Value value;
+
+ @ManyToOne
+ public Value getValue() {
+ return value;
+ }
+
+ public void setValue(Value value) {
+ this.value = value;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/UnresolvedTypeTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/UnresolvedTypeTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/UnresolvedTypeTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,43 @@
+package org.hibernate.test.annotations.generics;
+
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * @author Paolo Perrotta
+ */
+public class UnresolvedTypeTest extends TestCase {
+
+ public void testAcceptsUnresolvedPropertyTypesIfATargetEntityIsExplicitlySet() {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Gene item = new Gene();
+ s.persist( item );
+ s.flush();
+ tx.rollback();
+ s.close();
+ }
+
+ public void testAcceptsUnresolvedPropertyTypesIfATypeExplicitlySet() {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Gene item = new Gene();
+ item.setState( State.DORMANT );
+ s.persist( item );
+ s.flush();
+ s.clear();
+ item = (Gene) s.get( Gene.class, item.getId() );
+ assertEquals( State.DORMANT, item.getState() );
+ tx.rollback();
+ s.close();
+ }
+
+ @Override
+ protected Class[] getMappings() {
+ return new Class[]{
+ Gene.class,
+ DNA.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/WildEntity.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/WildEntity.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/generics/WildEntity.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,44 @@
+//$Id: WildEntity.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.generics;
+
+import java.io.Serializable;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.Transient;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class WildEntity implements Serializable {
+
+ private static final long serialVersionUID = -1171578628576139205L;
+
+ private int id;
+
+ private String property;
+
+ @Id
+ @GeneratedValue
+ public int getId() {
+ return id;
+ }
+
+ @Transient
+ public <T extends Object> T someMethod() {
+ return null;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ public String getProperty() {
+ return property;
+ }
+
+ public void setProperty(String property) {
+ this.property = property;
+ }
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/Child.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/Child.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/Child.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,27 @@
+package org.hibernate.test.annotations.genericsinheritance;
+
+import javax.persistence.MappedSuperclass;
+import javax.persistence.Id;
+import javax.persistence.ManyToOne;
+
+@MappedSuperclass
+public abstract class Child<P extends Parent> {
+
+ @Id Long id;
+ @ManyToOne P parent;
+
+ public Long getId() {
+ return id;
+ }
+ public void setId(Long id) {
+ this.id = id;
+ }
+ public P getParent() {
+ return parent;
+ }
+ public void setParent(P parent) {
+ this.parent = parent;
+ }
+
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/ChildHierarchy1.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/ChildHierarchy1.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/ChildHierarchy1.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,8 @@
+package org.hibernate.test.annotations.genericsinheritance;
+
+import javax.persistence.Entity;
+
+@Entity
+public class ChildHierarchy1 extends Child<ParentHierarchy1> {
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/ChildHierarchy2.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/ChildHierarchy2.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/ChildHierarchy2.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,8 @@
+package org.hibernate.test.annotations.genericsinheritance;
+
+import javax.persistence.MappedSuperclass;
+
+@MappedSuperclass
+public class ChildHierarchy2<P extends ParentHierarchy2> extends Child<P> {
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/ChildHierarchy22.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/ChildHierarchy22.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/ChildHierarchy22.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,8 @@
+package org.hibernate.test.annotations.genericsinheritance;
+
+import javax.persistence.Entity;
+
+@Entity
+public class ChildHierarchy22 extends ChildHierarchy2<ParentHierarchy22> {
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/GenericsInheritanceTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/GenericsInheritanceTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/GenericsInheritanceTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,24 @@
+//$Id: GenericsInheritanceTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.genericsinheritance;
+
+import org.hibernate.test.annotations.TestCase;
+import org.hibernate.Session;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class GenericsInheritanceTest extends TestCase {
+ public void testMapping() throws Exception {
+ Session s = openSession();
+ s.close();
+ //mapping is tested
+ }
+ protected Class[] getMappings() {
+ return new Class[] {
+ ChildHierarchy1.class,
+ ParentHierarchy1.class,
+ ChildHierarchy22.class,
+ ParentHierarchy22.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/Parent.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/Parent.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/Parent.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,35 @@
+package org.hibernate.test.annotations.genericsinheritance;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.MapKey;
+import javax.persistence.MappedSuperclass;
+import javax.persistence.OneToMany;
+
+@MappedSuperclass
+public abstract class Parent<C extends Child> {
+
+ @Id @GeneratedValue Long id;
+ @MapKey @OneToMany(mappedBy="parent") Map<Long,C> children = new HashMap<Long,C>();
+
+
+ public Long getId() {
+ return id;
+ }
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+
+ public Map<Long,C> getChildren() {
+ return children;
+ }
+ public void setChildren(Map<Long,C> children) {
+ this.children = children;
+ }
+
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/ParentHierarchy1.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/ParentHierarchy1.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/ParentHierarchy1.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,8 @@
+package org.hibernate.test.annotations.genericsinheritance;
+
+import javax.persistence.Entity;
+
+@Entity
+public class ParentHierarchy1 extends Parent<ChildHierarchy1> {
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/ParentHierarchy2.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/ParentHierarchy2.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/ParentHierarchy2.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,8 @@
+package org.hibernate.test.annotations.genericsinheritance;
+
+import javax.persistence.MappedSuperclass;
+
+@MappedSuperclass
+public class ParentHierarchy2<C extends ChildHierarchy2> extends Parent<C> {
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/ParentHierarchy22.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/ParentHierarchy22.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/genericsinheritance/ParentHierarchy22.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,8 @@
+package org.hibernate.test.annotations.genericsinheritance;
+
+import javax.persistence.Entity;
+
+@Entity
+public class ParentHierarchy22 extends ParentHierarchy2<ChildHierarchy22> {
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/hibernate.cfg.xml
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/hibernate.cfg.xml (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/hibernate.cfg.xml 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,11 @@
+<!DOCTYPE hibernate-configuration PUBLIC
+ "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
+ "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
+
+<hibernate-configuration>
+ <session-factory>
+ <mapping resource="org/hibernate/test/annotations/Boat.hbm.xml"/>
+ <mapping package="org.hibernate.test.annotations"/>
+ <mapping class="org.hibernate.test.annotations.Plane"/>
+ </session-factory>
+</hibernate-configuration>
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/EnumIdTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/EnumIdTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/EnumIdTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,62 @@
+//$Id: EnumIdTest.java 14785 2008-06-19 10:44:33Z hardy.ferentschik $
+package org.hibernate.test.annotations.id;
+
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.annotations.TestCase;
+import org.hibernate.test.annotations.id.entities.Planet;
+import org.hibernate.test.annotations.id.entities.PlanetCheatSheet;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tests for enum type as id.
+ *
+ * @author Hardy Ferentschik
+ * @see ANN-744
+ */
+@SuppressWarnings("unchecked")
+public class EnumIdTest extends TestCase {
+
+ private Logger log = LoggerFactory.getLogger(EnumIdTest.class);
+
+ public EnumIdTest(String x) {
+ super(x);
+ }
+
+ public void testEnumAsId() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ PlanetCheatSheet mercury = new PlanetCheatSheet();
+ mercury.setPlanet(Planet.MERCURY);
+ mercury.setMass(3.303e+23);
+ mercury.setRadius(2.4397e6);
+ mercury.setNumberOfInhabitants(0);
+ s.persist(mercury);
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ PlanetCheatSheet mercuryFromDb = (PlanetCheatSheet) s.get(PlanetCheatSheet.class, mercury.getPlanet());
+ assertNotNull(mercuryFromDb);
+ log.debug(mercuryFromDb.toString());
+ s.delete(mercuryFromDb);
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ mercury = (PlanetCheatSheet) s.get(PlanetCheatSheet.class, Planet.MERCURY);
+ assertNull(mercury);
+ tx.commit();
+ s.close();
+ }
+
+ /**
+ * @see org.hibernate.test.annotations.TestCase#getMappings()
+ */
+ protected Class[] getMappings() {
+ return new Class[] { PlanetCheatSheet.class };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/IdClassTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/IdClassTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/IdClassTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,38 @@
+//$Id: IdClassTest.java 14784 2008-06-19 10:42:20Z hardy.ferentschik $
+package org.hibernate.test.annotations.id;
+
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.annotations.TestCase;
+import org.hibernate.test.annotations.id.entities.Location;
+import org.hibernate.test.annotations.id.entities.Tower;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@SuppressWarnings("unchecked")
+public class IdClassTest extends TestCase {
+
+ public void testIdClassInSuperclass() throws Exception {
+ Tower tower = new Tower();
+ tower.latitude = 10.3;
+ tower.longitude = 45.4;
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ s.persist( tower );
+ s.flush();
+ s.clear();
+ Location loc = new Location();
+ loc.latitude = tower.latitude;
+ loc.longitude = tower.longitude;
+ assertNotNull( s.get( Tower.class, loc ) );
+ tx.rollback();
+ s.close();
+ }
+
+ protected Class[] getMappings() {
+ return new Class[]{
+ Tower.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/IdTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/IdTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/IdTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,301 @@
+//$Id: IdTest.java 17735 2009-10-14 05:15:33Z stliu $
+package org.hibernate.test.annotations.id;
+
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.mapping.Column;
+import org.hibernate.test.annotations.TestCase;
+import org.hibernate.test.annotations.id.entities.Ball;
+import org.hibernate.test.annotations.id.entities.BreakDance;
+import org.hibernate.test.annotations.id.entities.Computer;
+import org.hibernate.test.annotations.id.entities.Department;
+import org.hibernate.test.annotations.id.entities.Dog;
+import org.hibernate.test.annotations.id.entities.FirTree;
+import org.hibernate.test.annotations.id.entities.Footballer;
+import org.hibernate.test.annotations.id.entities.FootballerPk;
+import org.hibernate.test.annotations.id.entities.Furniture;
+import org.hibernate.test.annotations.id.entities.GoalKeeper;
+import org.hibernate.test.annotations.id.entities.Home;
+import org.hibernate.test.annotations.id.entities.Monkey;
+import org.hibernate.test.annotations.id.entities.Phone;
+import org.hibernate.test.annotations.id.entities.Shoe;
+import org.hibernate.test.annotations.id.entities.SoundSystem;
+import org.hibernate.test.annotations.id.entities.Store;
+import org.hibernate.test.annotations.id.entities.Tree;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@SuppressWarnings("unchecked")
+public class IdTest extends TestCase {
+ public void testGenericGenerator() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ SoundSystem system = new SoundSystem();
+ system.setBrand("Genelec");
+ system.setModel("T234");
+ Furniture fur = new Furniture();
+ s.persist(system);
+ s.persist(fur);
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ system = (SoundSystem) s.get(SoundSystem.class, system.getId());
+ fur = (Furniture) s.get(Furniture.class, fur.getId());
+ assertNotNull(system);
+ assertNotNull(fur);
+ s.delete(system);
+ s.delete(fur);
+ tx.commit();
+ s.close();
+
+ }
+
+ /*
+ * Ensures that GenericGenerator annotations wrapped inside a
+ * GenericGenerators holder are bound correctly
+ */
+ public void testGenericGenerators() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Monkey monkey = new Monkey();
+ s.persist(monkey);
+ s.flush();
+ assertNotNull(monkey.getId());
+ tx.rollback();
+ s.close();
+ }
+
+ public void testTableGenerator() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+
+ Ball b = new Ball();
+ Dog d = new Dog();
+ Computer c = new Computer();
+ s.persist(b);
+ s.persist(d);
+ s.persist(c);
+ tx.commit();
+ s.close();
+ assertEquals("table id not generated", new Integer(1), b.getId());
+ assertEquals("generator should not be shared", new Integer(1), d
+ .getId());
+ assertEquals("default value should work", new Long(1), c.getId());
+
+ s = openSession();
+ tx = s.beginTransaction();
+ s.delete(s.get(Ball.class, new Integer(1)));
+ s.delete(s.get(Dog.class, new Integer(1)));
+ s.delete(s.get(Computer.class, new Long(1)));
+ tx.commit();
+ s.close();
+ }
+
+ public void testSequenceGenerator() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Shoe b = new Shoe();
+ s.persist(b);
+ tx.commit();
+ s.close();
+ assertNotNull(b.getId());
+
+ s = openSession();
+ tx = s.beginTransaction();
+ s.delete(s.get(Shoe.class, b.getId()));
+ tx.commit();
+ s.close();
+ }
+
+ public void testClassLevelGenerator() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Store b = new Store();
+ s.persist(b);
+ tx.commit();
+ s.close();
+ assertNotNull(b.getId());
+
+ s = openSession();
+ tx = s.beginTransaction();
+ s.delete(s.get(Store.class, b.getId()));
+ tx.commit();
+ s.close();
+ }
+
+ public void testMethodLevelGenerator() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Department b = new Department();
+ s.persist(b);
+ tx.commit();
+ s.close();
+ assertNotNull(b.getId());
+
+ s = openSession();
+ tx = s.beginTransaction();
+ s.delete(s.get(Department.class, b.getId()));
+ tx.commit();
+ s.close();
+ }
+
+ public void testDefaultSequence() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Home h = new Home();
+ s.persist(h);
+ tx.commit();
+ s.close();
+ assertNotNull(h.getId());
+
+ s = openSession();
+ tx = s.beginTransaction();
+ Home reloadedHome = (Home) s.get(Home.class, h.getId());
+ assertEquals(h.getId(), reloadedHome.getId());
+ s.delete(reloadedHome);
+ tx.commit();
+ s.close();
+ }
+
+ public void testParameterizedAuto() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Home h = new Home();
+ s.persist(h);
+ tx.commit();
+ s.close();
+ assertNotNull(h.getId());
+
+ s = openSession();
+ tx = s.beginTransaction();
+ Home reloadedHome = (Home) s.get(Home.class, h.getId());
+ assertEquals(h.getId(), reloadedHome.getId());
+ s.delete(reloadedHome);
+ tx.commit();
+ s.close();
+ }
+
+ public void testIdInEmbeddableSuperclass() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ FirTree chrismasTree = new FirTree();
+ s.persist(chrismasTree);
+ tx.commit();
+ s.clear();
+ tx = s.beginTransaction();
+ chrismasTree = (FirTree) s.get(FirTree.class, chrismasTree.getId());
+ assertNotNull(chrismasTree);
+ s.delete(chrismasTree);
+ tx.commit();
+ s.close();
+ }
+
+ public void testIdClass() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Footballer fb = new Footballer("David", "Beckam", "Arsenal");
+ GoalKeeper keeper = new GoalKeeper("Fabien", "Bartez", "OM");
+ s.persist(fb);
+ s.persist(keeper);
+ tx.commit();
+ s.clear();
+
+ // lookup by id
+ tx = s.beginTransaction();
+ FootballerPk fpk = new FootballerPk("David", "Beckam");
+ fb = (Footballer) s.get(Footballer.class, fpk);
+ FootballerPk fpk2 = new FootballerPk("Fabien", "Bartez");
+ keeper = (GoalKeeper) s.get(GoalKeeper.class, fpk2);
+ assertNotNull(fb);
+ assertNotNull(keeper);
+ assertEquals("Beckam", fb.getLastname());
+ assertEquals("Arsenal", fb.getClub());
+ assertEquals(1, s.createQuery(
+ "from Footballer f where f.firstname = 'David'").list().size());
+ tx.commit();
+
+ // reattach by merge
+ tx = s.beginTransaction();
+ fb.setClub("Bimbo FC");
+ s.merge(fb);
+ tx.commit();
+
+ // reattach by saveOrUpdate
+ tx = s.beginTransaction();
+ fb.setClub("Bimbo FC SA");
+ s.saveOrUpdate(fb);
+ tx.commit();
+
+ // clean up
+ s.clear();
+ tx = s.beginTransaction();
+ fpk = new FootballerPk("David", "Beckam");
+ fb = (Footballer) s.get(Footballer.class, fpk);
+ assertEquals("Bimbo FC SA", fb.getClub());
+ s.delete(fb);
+ s.delete(keeper);
+ tx.commit();
+ s.close();
+ }
+
+ public void testColumnDefinition() {
+ Column idCol = (Column) getCfg().getClassMapping(Ball.class.getName())
+ .getIdentifierProperty().getValue().getColumnIterator().next();
+ assertEquals("ball_id", idCol.getName());
+ }
+
+ public void testLowAllocationSize() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ int size = 4;
+ BreakDance[] bds = new BreakDance[size];
+ for (int i = 0; i < size; i++) {
+ bds[i] = new BreakDance();
+ s.persist(bds[i]);
+ }
+ s.flush();
+ for (int i = 0; i < size; i++) {
+ assertEquals(i + 1, bds[i].id.intValue());
+ }
+ tx.rollback();
+ s.close();
+ }
+
+ /**
+ * @see org.hibernate.test.annotations.TestCase#getMappings()
+ */
+ protected Class[] getMappings() {
+ return new Class[] { Ball.class, Shoe.class, Store.class,
+ Department.class, Dog.class, Computer.class, Home.class,
+ Phone.class, Tree.class, FirTree.class, Footballer.class,
+ SoundSystem.class, Furniture.class, GoalKeeper.class,
+ BreakDance.class, Monkey.class};
+ }
+
+ /**
+ * @see org.hibernate.test.annotations.TestCase#getAnnotatedPackages()
+ */
+ protected String[] getAnnotatedPackages() {
+ return new String[] { "org.hibernate.test.annotations",
+ "org.hibernate.test.annotations.id" };
+ }
+
+ @Override
+ protected String[] getXmlFiles() {
+ return new String[] { "org/hibernate/test/annotations/orm.xml" };
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/JoinColumnOverrideTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/JoinColumnOverrideTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/JoinColumnOverrideTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,64 @@
+//$Id: JoinColumnOverrideTest.java 14761 2008-06-11 13:51:06Z hardy.ferentschik $
+package org.hibernate.test.annotations.id;
+
+import java.io.PrintWriter;
+import java.io.StringWriter;
+
+import org.hibernate.cfg.AnnotationConfiguration;
+import org.hibernate.dialect.SQLServerDialect;
+import org.hibernate.test.annotations.TestCase;
+import org.hibernate.test.annotations.id.entities.Bunny;
+import org.hibernate.test.annotations.id.entities.PointyTooth;
+import org.hibernate.test.annotations.id.entities.TwinkleToes;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tests for JIRA issue ANN-748.
+ *
+ * @author Hardy Ferentschik
+ */
+@SuppressWarnings("unchecked")
+public class JoinColumnOverrideTest extends TestCase {
+
+ private Logger log = LoggerFactory.getLogger(JoinColumnOverrideTest.class);
+
+ public JoinColumnOverrideTest(String x) {
+ super(x);
+ }
+
+ public void testBlownPrecision() throws Exception {
+
+ try {
+ AnnotationConfiguration config = new AnnotationConfiguration();
+ config.addAnnotatedClass(Bunny.class);
+ config.addAnnotatedClass(PointyTooth.class);
+ config.addAnnotatedClass(TwinkleToes.class);
+ config.buildSessionFactory();
+ String[] schema = config
+ .generateSchemaCreationScript(new SQLServerDialect());
+ for (String s : schema) {
+ log.debug(s);
+ }
+ String expectedSqlPointyTooth = "create table PointyTooth (id numeric(128,0) not null, " +
+ "bunny_id numeric(128,0) null, primary key (id))";
+ assertEquals("Wrong SQL", expectedSqlPointyTooth, schema[1]);
+
+ String expectedSqlTwinkleToes = "create table TwinkleToes (id numeric(128,0) not null, " +
+ "bunny_id numeric(128,0) null, primary key (id))";
+ assertEquals("Wrong SQL", expectedSqlTwinkleToes, schema[2]);
+ } catch (Exception e) {
+ StringWriter writer = new StringWriter();
+ e.printStackTrace(new PrintWriter(writer));
+ log.debug(writer.toString());
+ fail(e.getMessage());
+ }
+ }
+
+ /**
+ * @see org.hibernate.test.annotations.TestCase#getMappings()
+ */
+ protected Class[] getMappings() {
+ return new Class[] {};
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/UUIDGenerator.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/UUIDGenerator.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/UUIDGenerator.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,34 @@
+package org.hibernate.test.annotations.id;
+
+import java.io.Serializable;
+import java.math.BigInteger;
+import java.util.UUID;
+
+import org.hibernate.HibernateException;
+import org.hibernate.engine.SessionImplementor;
+import org.hibernate.id.IdentifierGenerator;
+
+/**
+ * Unlike Hibernate's UUID generator. This avoids
+ * meaningless synchronization and has less
+ * than a chance of an asteroid hitting you on the head
+ * even after trillions of rows are inserted. I know
+ * this to be true because it says so in Wikipedia(haha).
+ * http://en.wikipedia.org/wiki/UUID#Random_UUID_probability_of_duplicates
+ *
+ */
+public class UUIDGenerator implements IdentifierGenerator {
+
+ public Serializable generate(SessionImplementor arg0, Object arg1) throws HibernateException {
+ UUID uuid = UUID.randomUUID();
+ String sud = uuid.toString();
+ System.out.println("uuid="+uuid);
+ sud = sud.replaceAll("-", "");
+
+ BigInteger integer = new BigInteger(sud,16);
+
+ System.out.println("bi ="+integer.toString() );
+ return integer;
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Ball.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Ball.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Ball.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,35 @@
+//$Id: Ball.java 14760 2008-06-11 07:33:15Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.entities;
+
+import java.io.Serializable;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.TableGenerator;
+
+/**
+ * Sample of table generator
+ *
+ * @author Emmanuel Bernard
+ */
+@TableGenerator(name = "EMP_GEN", table = "GENERATOR_TABLE", pkColumnName = "pkey",
+ valueColumnName = "hi", pkColumnValue = "Ball", allocationSize = 10)
+@Entity
+@SuppressWarnings("serial")
+public class Ball implements Serializable {
+ private Integer id;
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.TABLE, generator = "EMP_GEN")
+ @Column(name = "ball_id")
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/BreakDance.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/BreakDance.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/BreakDance.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,27 @@
+//$Id: BreakDance.java 14760 2008-06-11 07:33:15Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.entities;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.GeneratedValue;
+import javax.persistence.TableGenerator;
+import javax.persistence.GenerationType;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class BreakDance {
+ @Id
+ @GeneratedValue(generator = "memencoIdGen", strategy = GenerationType.TABLE)
+ @TableGenerator(
+ name = "memencoIdGen",
+ table = "hi_id_key",
+ pkColumnName = "id_key",
+ valueColumnName = "next_hi",
+ pkColumnValue = "issue",
+ allocationSize = 1
+ )
+ public Integer id;
+ public String name;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Bunny.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Bunny.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Bunny.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,46 @@
+//$Id: Bunny.java 14761 2008-06-11 13:51:06Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.entities;
+
+import java.io.Serializable;
+import java.math.BigInteger;
+import java.util.Set;
+
+import javax.persistence.Column;
+import javax.persistence.CascadeType;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.OneToMany;
+
+import org.hibernate.annotations.GenericGenerator;
+
+/**
+ * Blown precision on related entity when @JoinColumn is used.
+ *
+ * @see ANN-748
+ * @author Andrew C. Oliver andyspam(a)osintegrators.com
+ */
+@Entity
+@SuppressWarnings("serial")
+public class Bunny implements Serializable {
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "java5_uuid")
+ @GenericGenerator(name = "java5_uuid", strategy = "org.hibernate.test.annotations.id.UUIDGenerator")
+ @Column(name = "id", precision = 128, scale = 0)
+ private BigInteger id;
+
+ @OneToMany(mappedBy = "bunny", cascade = { CascadeType.PERSIST })
+ Set<PointyTooth> teeth;
+
+ @OneToMany(mappedBy = "bunny", cascade = { CascadeType.PERSIST })
+ Set<TwinkleToes> toes;
+
+ public void setTeeth(Set<PointyTooth> teeth) {
+ this.teeth = teeth;
+ }
+
+ public BigInteger getId() {
+ return id;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Computer.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Computer.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Computer.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,34 @@
+//$Id: Computer.java 14760 2008-06-11 07:33:15Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.entities;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity()
+public class Computer {
+ private Long id;
+ private String serialNumber;
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.TABLE)
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getSerialNumber() {
+ return serialNumber;
+ }
+
+ public void setSerialNumber(String serialNumber) {
+ this.serialNumber = serialNumber;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Department.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Department.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Department.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,29 @@
+//$Id: Department.java 17735 2009-10-14 05:15:33Z stliu $
+package org.hibernate.test.annotations.id.entities;
+
+import java.io.Serializable;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * Sample of method generator
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity
+@SuppressWarnings("serial")
+public class Department implements Serializable {
+ private Long id;
+
+ @Id
+ @GeneratedValue
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long long1) {
+ id = long1;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Dog.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Dog.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Dog.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,42 @@
+//$Id: Dog.java 14760 2008-06-11 07:33:15Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.entities;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Table;
+import javax.persistence.TableGenerator;
+
+/**
+ * Share the generator table decribed by the GEN_TABLE GeneratedIdTable
+ * using the Dog key as discriminator
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Table(name = "tbl_dog")
+@TableGenerator(name = "DogGen", table = "GENERATOR_TABLE", pkColumnName = "pkey",
+ valueColumnName = "hi", pkColumnValue = "Dog", allocationSize = 10)
+public class Dog {
+ private Integer id;
+ private String name;
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.TABLE, generator = "DogGen")
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/FirTree.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/FirTree.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/FirTree.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,11 @@
+//$Id: FirTree.java 14760 2008-06-11 07:33:15Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.entities;
+
+import javax.persistence.Entity;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class FirTree extends Tree {
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Footballer.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Footballer.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Footballer.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,73 @@
+//$Id: Footballer.java 14760 2008-06-11 07:33:15Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.entities;
+
+import javax.persistence.DiscriminatorColumn;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.IdClass;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+(a)IdClass(FootballerPk.class)
+@DiscriminatorColumn(name = "bibi")
+public class Footballer {
+ private String firstname;
+ private String lastname;
+ private String club;
+
+ public Footballer() {
+ }
+
+ public Footballer(String firstname, String lastname, String club) {
+ this.firstname = firstname;
+ this.lastname = lastname;
+ this.club = club;
+ }
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( !( o instanceof Footballer ) ) return false;
+
+ final Footballer footballer = (Footballer) o;
+
+ if ( !firstname.equals( footballer.firstname ) ) return false;
+ if ( !lastname.equals( footballer.lastname ) ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ int result;
+ result = firstname.hashCode();
+ result = 29 * result + lastname.hashCode();
+ return result;
+ }
+
+ @Id
+ public String getFirstname() {
+ return firstname;
+ }
+
+ public void setFirstname(String firstname) {
+ this.firstname = firstname;
+ }
+
+ @Id
+ public String getLastname() {
+ return lastname;
+ }
+
+ public void setLastname(String lastname) {
+ this.lastname = lastname;
+ }
+
+ public String getClub() {
+ return club;
+ }
+
+ public void setClub(String club) {
+ this.club = club;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/FootballerPk.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/FootballerPk.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/FootballerPk.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,62 @@
+//$Id: FootballerPk.java 14760 2008-06-11 07:33:15Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.entities;
+
+import java.io.Serializable;
+import javax.persistence.Column;
+import javax.persistence.Embeddable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Embeddable
+@SuppressWarnings("serial")
+public class FootballerPk implements Serializable {
+ private String firstname;
+ private String lastname;
+
+ @Column(name = "fb_fname")
+ public String getFirstname() {
+ return firstname;
+ }
+
+ public String getLastname() {
+ return lastname;
+ }
+
+ public void setFirstname(String firstname) {
+ this.firstname = firstname;
+ }
+
+ public void setLastname(String lastname) {
+ this.lastname = lastname;
+ }
+
+ public FootballerPk() {
+ }
+
+ public FootballerPk(String firstname, String lastname) {
+ this.firstname = firstname;
+ this.lastname = lastname;
+
+ }
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( !( o instanceof FootballerPk ) ) return false;
+
+ final FootballerPk footballerPk = (FootballerPk) o;
+
+ if ( !firstname.equals( footballerPk.firstname ) ) return false;
+ if ( !lastname.equals( footballerPk.lastname ) ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ int result;
+ result = firstname.hashCode();
+ result = 29 * result + lastname.hashCode();
+ return result;
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Furniture.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Furniture.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Furniture.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,33 @@
+//$Id: Furniture.java 14760 2008-06-11 07:33:15Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.entities;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+import org.hibernate.annotations.GenericGenerator;
+import org.hibernate.annotations.Parameter;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Furniture {
+ private Integer id;
+
+ @Id
+ @GeneratedValue(generator = "hibseq")
+ @GenericGenerator(name = "hibseq", strategy = "seqhilo",
+ parameters = {
+ @Parameter(name = "max_lo", value = "5"),
+ @Parameter(name = "sequence", value = "heybabyhey")
+ }
+ )
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/GoalKeeper.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/GoalKeeper.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/GoalKeeper.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,17 @@
+//$Id: GoalKeeper.java 14760 2008-06-11 07:33:15Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.entities;
+
+import javax.persistence.Entity;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class GoalKeeper extends Footballer {
+ public GoalKeeper() {
+ }
+
+ public GoalKeeper(String firstname, String lastname, String club) {
+ super( firstname, lastname, club );
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Home.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Home.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Home.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,26 @@
+//$Id: Home.java 14760 2008-06-11 07:33:15Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.entities;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * Default sequence generation usage
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Home {
+ private Long id;
+
+ @Id
+ @GeneratedValue
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Location.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Location.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Location.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,35 @@
+//$Id: Location.java 14760 2008-06-11 07:33:15Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.entities;
+
+import java.io.Serializable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@SuppressWarnings("serial")
+public class Location implements Serializable {
+ public double longitude;
+ public double latitude;
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( o == null || getClass() != o.getClass() ) return false;
+
+ final Location location = (Location) o;
+
+ if ( Double.compare( location.latitude, latitude ) != 0 ) return false;
+ if ( Double.compare( location.longitude, longitude ) != 0 ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ int result;
+ long temp;
+ temp = longitude != +0.0d ? Double.doubleToLongBits( longitude ) : 0L;
+ result = (int) ( temp ^ ( temp >>> 32 ) );
+ temp = latitude != +0.0d ? Double.doubleToLongBits( latitude ) : 0L;
+ result = 29 * result + (int) ( temp ^ ( temp >>> 32 ) );
+ return result;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/MilitaryBuilding.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/MilitaryBuilding.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/MilitaryBuilding.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,18 @@
+//$Id: MilitaryBuilding.java 14760 2008-06-11 07:33:15Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.entities;
+
+import javax.persistence.Id;
+import javax.persistence.IdClass;
+import javax.persistence.MappedSuperclass;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@MappedSuperclass
+(a)IdClass(Location.class)
+public class MilitaryBuilding {
+ @Id
+ public double longitude;
+ @Id
+ public double latitude;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Monkey.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Monkey.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Monkey.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,24 @@
+//$
+package org.hibernate.test.annotations.id.entities;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * @author Paul Cowan
+ */
+@Entity
+public class Monkey {
+ private String id;
+
+ @Id
+ @GeneratedValue(generator = "system-uuid-2")
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Phone.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Phone.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Phone.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,24 @@
+//$Id: Phone.java 17735 2009-10-14 05:15:33Z stliu $
+package org.hibernate.test.annotations.id.entities;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity()
+public class Phone {
+ private Integer id;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Planet.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Planet.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Planet.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,6 @@
+// $Id: Planet.java 14785 2008-06-19 10:44:33Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.entities;
+
+public enum Planet {
+ MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE, PLUTO;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/PlanetCheatSheet.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/PlanetCheatSheet.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/PlanetCheatSheet.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,85 @@
+package org.hibernate.test.annotations.id.entities;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.EnumType;
+import javax.persistence.Enumerated;
+import javax.persistence.Id;
+
+
+/**
+ * Test entity for enum type as id.
+ *
+ * @author Hardy Ferentschik
+ * @see ANN-744
+ */
+@Entity
+public class PlanetCheatSheet {
+
+ @Id
+ @Enumerated(EnumType.STRING)
+ @Column(name = "planet")
+ private Planet planet;
+
+ private double mass;
+
+ private double radius;
+
+ private long numberOfInhabitants;
+
+ public Planet getPlanet() {
+ return planet;
+ }
+
+ public void setPlanet(Planet planet) {
+ this.planet = planet;
+ }
+
+ public double getMass() {
+ return mass;
+ }
+
+ public void setMass(double mass) {
+ this.mass = mass;
+ }
+
+ public double getRadius() {
+ return radius;
+ }
+
+ public void setRadius(double radius) {
+ this.radius = radius;
+ }
+
+ public long getNumberOfInhabitants() {
+ return numberOfInhabitants;
+ }
+
+ public void setNumberOfInhabitants(long numberOfInhabitants) {
+ this.numberOfInhabitants = numberOfInhabitants;
+ }
+
+ /**
+ * Constructs a <code>String</code> with all attributes
+ * in name = value format.
+ *
+ * @return a <code>String</code> representation
+ * of this object.
+ */
+ public String toString()
+ {
+ final String TAB = " ";
+
+ String retValue = "";
+
+ retValue = "PlanetCheatSheet ( "
+ + super.toString() + TAB
+ + "planet = " + this.planet + TAB
+ + "mass = " + this.mass + TAB
+ + "radius = " + this.radius + TAB
+ + "numberOfInhabitants = " + this.numberOfInhabitants + TAB
+ + " )";
+
+ return retValue;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/PointyTooth.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/PointyTooth.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/PointyTooth.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,44 @@
+//$Id: PointyTooth.java 14761 2008-06-11 13:51:06Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.entities;
+
+import java.io.Serializable;
+import java.math.BigInteger;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+
+import org.hibernate.annotations.GenericGenerator;
+
+/**
+ * Blown precision on related entity when @JoinColumn is used.
+ * Does not cause an issue on HyperSonic, but replicates nicely on PGSQL.
+ *
+ * @see ANN-748
+ * @author Andrew C. Oliver andyspam(a)osintegrators.com
+ */
+@Entity
+@SuppressWarnings("serial")
+public class PointyTooth implements Serializable {
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "java5_uuid")
+ @GenericGenerator(name = "java5_uuid", strategy = "org.hibernate.test.annotations.id.UUIDGenerator")
+ @Column(name = "id", precision = 128, scale = 0)
+ private BigInteger id;
+
+ @ManyToOne
+ @JoinColumn(name = "bunny_id")
+ Bunny bunny;
+
+ public void setBunny(Bunny bunny) {
+ this.bunny = bunny;
+ }
+
+ public BigInteger getId() {
+ return id;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Shoe.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Shoe.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Shoe.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,29 @@
+//$Id: Shoe.java 17735 2009-10-14 05:15:33Z stliu $
+package org.hibernate.test.annotations.id.entities;
+
+import java.io.Serializable;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * sample of Sequance generator
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity
+@SuppressWarnings("serial")
+public class Shoe implements Serializable {
+ private Long id;
+
+ @Id
+ @GeneratedValue
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long long1) {
+ id = long1;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/SoundSystem.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/SoundSystem.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/SoundSystem.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,42 @@
+//$Id: SoundSystem.java 14760 2008-06-11 07:33:15Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.entities;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class SoundSystem {
+ private String id;
+ private String brand;
+ private String model;
+
+ @Id
+ @GeneratedValue(generator = "system-uuid")
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public String getBrand() {
+ return brand;
+ }
+
+ public void setBrand(String brand) {
+ this.brand = brand;
+ }
+
+ public String getModel() {
+ return model;
+ }
+
+ public void setModel(String model) {
+ this.model = model;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Store.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Store.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Store.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,29 @@
+//$Id: Store.java 17735 2009-10-14 05:15:33Z stliu $
+package org.hibernate.test.annotations.id.entities;
+
+import java.io.Serializable;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * Sample of class generator
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity
+@SuppressWarnings("serial")
+public class Store implements Serializable {
+ private Long id;
+
+ @Id
+ @GeneratedValue
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long long1) {
+ id = long1;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Tower.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Tower.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Tower.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,14 @@
+//$Id: Tower.java 14760 2008-06-11 07:33:15Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.entities;
+
+import javax.persistence.AttributeOverride;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@AttributeOverride(name = "longitude", column = @Column(name = "fld_longitude"))
+public class Tower extends MilitaryBuilding {
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Tree.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Tree.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/Tree.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,24 @@
+//$Id: Tree.java 14760 2008-06-11 07:33:15Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.entities;
+
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.MappedSuperclass;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@MappedSuperclass
+public class Tree {
+ private Integer id;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/TwinkleToes.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/TwinkleToes.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/entities/TwinkleToes.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,42 @@
+//$Id: TwinkleToes.java 14761 2008-06-11 13:51:06Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.entities;
+
+import java.io.Serializable;
+import java.math.BigInteger;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.ManyToOne;
+
+import org.hibernate.annotations.GenericGenerator;
+
+/**
+ * Blown precision on related entity when @JoinColumn is used.
+ * Does not cause an issue on HyperSonic, but replicates nicely on PGSQL.
+ *
+ * @see ANN-748
+ * @author Andrew C. Oliver andyspam(a)osintegrators.com
+ */
+@Entity
+@SuppressWarnings("serial")
+public class TwinkleToes implements Serializable {
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "java5_uuid")
+ @GenericGenerator(name = "java5_uuid", strategy = "org.hibernate.test.annotations.id.UUIDGenerator")
+ @Column(name = "id", precision = 128, scale = 0)
+ private BigInteger id;
+
+ @ManyToOne
+ Bunny bunny;
+
+ public void setBunny(Bunny bunny) {
+ this.bunny = bunny;
+ }
+
+ public BigInteger getId() {
+ return id;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/package-info.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/package-info.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/package-info.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,11 @@
+//$Id: package-info.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+/**
+ * Test package for metatata facilities
+ * It contains an example of package level metadata
+ */
+(a)org.hibernate.annotations.GenericGenerator(name = "system-uuid", strategy = "uuid")
+(a)org.hibernate.annotations.GenericGenerators(
+ @org.hibernate.annotations.GenericGenerator(name = "system-uuid-2", strategy = "uuid")
+)
+package org.hibernate.test.annotations.id;
+
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/EnumIdTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/EnumIdTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/EnumIdTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,62 @@
+//$Id: EnumIdTest.java 14785 2008-06-19 10:44:33Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.sequences;
+
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.annotations.TestCase;
+import org.hibernate.test.annotations.id.sequences.entities.Planet;
+import org.hibernate.test.annotations.id.sequences.entities.PlanetCheatSheet;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tests for enum type as id.
+ *
+ * @author Hardy Ferentschik
+ * @see ANN-744
+ */
+@SuppressWarnings("unchecked")
+public class EnumIdTest extends TestCase {
+
+ private Logger log = LoggerFactory.getLogger(EnumIdTest.class);
+
+ public EnumIdTest(String x) {
+ super(x);
+ }
+
+ public void testEnumAsId() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ PlanetCheatSheet mercury = new PlanetCheatSheet();
+ mercury.setPlanet(Planet.MERCURY);
+ mercury.setMass(3.303e+23);
+ mercury.setRadius(2.4397e6);
+ mercury.setNumberOfInhabitants(0);
+ s.persist(mercury);
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ PlanetCheatSheet mercuryFromDb = (PlanetCheatSheet) s.get(PlanetCheatSheet.class, mercury.getPlanet());
+ assertNotNull(mercuryFromDb);
+ log.debug(mercuryFromDb.toString());
+ s.delete(mercuryFromDb);
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ mercury = (PlanetCheatSheet) s.get(PlanetCheatSheet.class, Planet.MERCURY);
+ assertNull(mercury);
+ tx.commit();
+ s.close();
+ }
+
+ /**
+ * @see org.hibernate.test.annotations.TestCase#getMappings()
+ */
+ protected Class[] getMappings() {
+ return new Class[] { PlanetCheatSheet.class };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/IdClassTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/IdClassTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/IdClassTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,39 @@
+//$Id: IdClassTest.java 14784 2008-06-19 10:42:20Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.sequences;
+
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.annotations.TestCase;
+import org.hibernate.test.annotations.id.sequences.entities.Location;
+import org.hibernate.test.annotations.id.sequences.entities.Tower;
+
+
+/**
+ * @author Emmanuel Bernard
+ */
+@SuppressWarnings("unchecked")
+public class IdClassTest extends TestCase {
+
+ public void testIdClassInSuperclass() throws Exception {
+ Tower tower = new Tower();
+ tower.latitude = 10.3;
+ tower.longitude = 45.4;
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ s.persist( tower );
+ s.flush();
+ s.clear();
+ Location loc = new Location();
+ loc.latitude = tower.latitude;
+ loc.longitude = tower.longitude;
+ assertNotNull( s.get( Tower.class, loc ) );
+ tx.rollback();
+ s.close();
+ }
+
+ protected Class[] getMappings() {
+ return new Class[]{
+ Tower.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/IdTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/IdTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/IdTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,308 @@
+//$Id: IdTest.java 15025 2008-08-11 09:14:39Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.sequences;
+
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.mapping.Column;
+import org.hibernate.test.annotations.TestCase;
+import org.hibernate.test.annotations.id.sequences.entities.Ball;
+import org.hibernate.test.annotations.id.sequences.entities.BreakDance;
+import org.hibernate.test.annotations.id.sequences.entities.Computer;
+import org.hibernate.test.annotations.id.sequences.entities.Department;
+import org.hibernate.test.annotations.id.sequences.entities.Dog;
+import org.hibernate.test.annotations.id.sequences.entities.FirTree;
+import org.hibernate.test.annotations.id.sequences.entities.Footballer;
+import org.hibernate.test.annotations.id.sequences.entities.FootballerPk;
+import org.hibernate.test.annotations.id.sequences.entities.Furniture;
+import org.hibernate.test.annotations.id.sequences.entities.GoalKeeper;
+import org.hibernate.test.annotations.id.sequences.entities.Home;
+import org.hibernate.test.annotations.id.sequences.entities.Monkey;
+import org.hibernate.test.annotations.id.sequences.entities.Phone;
+import org.hibernate.test.annotations.id.sequences.entities.Shoe;
+import org.hibernate.test.annotations.id.sequences.entities.SoundSystem;
+import org.hibernate.test.annotations.id.sequences.entities.Store;
+import org.hibernate.test.annotations.id.sequences.entities.Tree;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@SuppressWarnings("unchecked")
+public class IdTest extends TestCase {
+ public void testGenericGenerator() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ SoundSystem system = new SoundSystem();
+ system.setBrand("Genelec");
+ system.setModel("T234");
+ Furniture fur = new Furniture();
+ s.persist(system);
+ s.persist(fur);
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ system = (SoundSystem) s.get(SoundSystem.class, system.getId());
+ fur = (Furniture) s.get(Furniture.class, fur.getId());
+ assertNotNull(system);
+ assertNotNull(fur);
+ s.delete(system);
+ s.delete(fur);
+ tx.commit();
+ s.close();
+
+ }
+
+ /*
+ * Ensures that GenericGenerator annotations wrapped inside a
+ * GenericGenerators holder are bound correctly
+ */
+ public void testGenericGenerators() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Monkey monkey = new Monkey();
+ s.persist(monkey);
+ s.flush();
+ assertNotNull(monkey.getId());
+ tx.rollback();
+ s.close();
+ }
+
+ public void testTableGenerator() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+
+ Ball b = new Ball();
+ Dog d = new Dog();
+ Computer c = new Computer();
+ s.persist(b);
+ s.persist(d);
+ s.persist(c);
+ tx.commit();
+ s.close();
+ assertEquals("table id not generated", new Integer(1), b.getId());
+ assertEquals("generator should not be shared", new Integer(1), d
+ .getId());
+ assertEquals("default value should work", new Long(1), c.getId());
+
+ s = openSession();
+ tx = s.beginTransaction();
+ s.delete(s.get(Ball.class, new Integer(1)));
+ s.delete(s.get(Dog.class, new Integer(1)));
+ s.delete(s.get(Computer.class, new Long(1)));
+ tx.commit();
+ s.close();
+ }
+
+ public void testSequenceGenerator() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Shoe b = new Shoe();
+ s.persist(b);
+ tx.commit();
+ s.close();
+ assertNotNull(b.getId());
+
+ s = openSession();
+ tx = s.beginTransaction();
+ s.delete(s.get(Shoe.class, b.getId()));
+ tx.commit();
+ s.close();
+ }
+
+ public void testClassLevelGenerator() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Store b = new Store();
+ s.persist(b);
+ tx.commit();
+ s.close();
+ assertNotNull(b.getId());
+
+ s = openSession();
+ tx = s.beginTransaction();
+ s.delete(s.get(Store.class, b.getId()));
+ tx.commit();
+ s.close();
+ }
+
+ public void testMethodLevelGenerator() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Department b = new Department();
+ s.persist(b);
+ tx.commit();
+ s.close();
+ assertNotNull(b.getId());
+
+ s = openSession();
+ tx = s.beginTransaction();
+ s.delete(s.get(Department.class, b.getId()));
+ tx.commit();
+ s.close();
+ }
+
+ public void testDefaultSequence() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Home h = new Home();
+ s.persist(h);
+ tx.commit();
+ s.close();
+ assertNotNull(h.getId());
+
+ s = openSession();
+ tx = s.beginTransaction();
+ Home reloadedHome = (Home) s.get(Home.class, h.getId());
+ assertEquals(h.getId(), reloadedHome.getId());
+ s.delete(reloadedHome);
+ tx.commit();
+ s.close();
+ }
+
+ public void testParameterizedAuto() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Home h = new Home();
+ s.persist(h);
+ tx.commit();
+ s.close();
+ assertNotNull(h.getId());
+
+ s = openSession();
+ tx = s.beginTransaction();
+ Home reloadedHome = (Home) s.get(Home.class, h.getId());
+ assertEquals(h.getId(), reloadedHome.getId());
+ s.delete(reloadedHome);
+ tx.commit();
+ s.close();
+ }
+
+ public void testIdInEmbeddableSuperclass() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ FirTree chrismasTree = new FirTree();
+ s.persist(chrismasTree);
+ tx.commit();
+ s.clear();
+ tx = s.beginTransaction();
+ chrismasTree = (FirTree) s.get(FirTree.class, chrismasTree.getId());
+ assertNotNull(chrismasTree);
+ s.delete(chrismasTree);
+ tx.commit();
+ s.close();
+ }
+
+ public void testIdClass() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Footballer fb = new Footballer("David", "Beckam", "Arsenal");
+ GoalKeeper keeper = new GoalKeeper("Fabien", "Bartez", "OM");
+ s.persist(fb);
+ s.persist(keeper);
+ tx.commit();
+ s.clear();
+
+ // lookup by id
+ tx = s.beginTransaction();
+ FootballerPk fpk = new FootballerPk("David", "Beckam");
+ fb = (Footballer) s.get(Footballer.class, fpk);
+ FootballerPk fpk2 = new FootballerPk("Fabien", "Bartez");
+ keeper = (GoalKeeper) s.get(GoalKeeper.class, fpk2);
+ assertNotNull(fb);
+ assertNotNull(keeper);
+ assertEquals("Beckam", fb.getLastname());
+ assertEquals("Arsenal", fb.getClub());
+ assertEquals(1, s.createQuery(
+ "from Footballer f where f.firstname = 'David'").list().size());
+ tx.commit();
+
+ // reattach by merge
+ tx = s.beginTransaction();
+ fb.setClub("Bimbo FC");
+ s.merge(fb);
+ tx.commit();
+
+ // reattach by saveOrUpdate
+ tx = s.beginTransaction();
+ fb.setClub("Bimbo FC SA");
+ s.saveOrUpdate(fb);
+ tx.commit();
+
+ // clean up
+ s.clear();
+ tx = s.beginTransaction();
+ fpk = new FootballerPk("David", "Beckam");
+ fb = (Footballer) s.get(Footballer.class, fpk);
+ assertEquals("Bimbo FC SA", fb.getClub());
+ s.delete(fb);
+ s.delete(keeper);
+ tx.commit();
+ s.close();
+ }
+
+ public void testColumnDefinition() {
+ Column idCol = (Column) getCfg().getClassMapping(Ball.class.getName())
+ .getIdentifierProperty().getValue().getColumnIterator().next();
+ assertEquals("ball_id", idCol.getName());
+ }
+
+ public void testLowAllocationSize() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ int size = 4;
+ BreakDance[] bds = new BreakDance[size];
+ for (int i = 0; i < size; i++) {
+ bds[i] = new BreakDance();
+ s.persist(bds[i]);
+ }
+ s.flush();
+ for (int i = 0; i < size; i++) {
+ assertEquals(i + 1, bds[i].id.intValue());
+ }
+ tx.rollback();
+ s.close();
+ }
+
+
+
+ @Override
+ protected boolean runForCurrentDialect() {
+ return super.runForCurrentDialect() && getDialect().supportsSequences();
+ }
+
+ /**
+ * @see org.hibernate.test.annotations.TestCase#getMappings()
+ */
+ protected Class[] getMappings() {
+ return new Class[] { Ball.class, Shoe.class, Store.class,
+ Department.class, Dog.class, Computer.class, Home.class,
+ Phone.class, Tree.class, FirTree.class, Footballer.class,
+ SoundSystem.class, Furniture.class, GoalKeeper.class,
+ BreakDance.class, Monkey.class};
+ }
+
+ /**
+ * @see org.hibernate.test.annotations.TestCase#getAnnotatedPackages()
+ */
+ protected String[] getAnnotatedPackages() {
+ return new String[] { "org.hibernate.test.annotations",
+ "org.hibernate.test.annotations.id" };
+ }
+
+ @Override
+ protected String[] getXmlFiles() {
+ return new String[] { "org/hibernate/test/annotations/orm.xml" };
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/JoinColumnOverrideTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/JoinColumnOverrideTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/JoinColumnOverrideTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,64 @@
+//$Id: JoinColumnOverrideTest.java 14761 2008-06-11 13:51:06Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.sequences;
+
+import java.io.PrintWriter;
+import java.io.StringWriter;
+
+import org.hibernate.cfg.AnnotationConfiguration;
+import org.hibernate.dialect.SQLServerDialect;
+import org.hibernate.test.annotations.TestCase;
+import org.hibernate.test.annotations.id.sequences.entities.Bunny;
+import org.hibernate.test.annotations.id.sequences.entities.PointyTooth;
+import org.hibernate.test.annotations.id.sequences.entities.TwinkleToes;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tests for JIRA issue ANN-748.
+ *
+ * @author Hardy Ferentschik
+ */
+@SuppressWarnings("unchecked")
+public class JoinColumnOverrideTest extends TestCase {
+
+ private Logger log = LoggerFactory.getLogger(JoinColumnOverrideTest.class);
+
+ public JoinColumnOverrideTest(String x) {
+ super(x);
+ }
+
+ public void testBlownPrecision() throws Exception {
+
+ try {
+ AnnotationConfiguration config = new AnnotationConfiguration();
+ config.addAnnotatedClass(Bunny.class);
+ config.addAnnotatedClass(PointyTooth.class);
+ config.addAnnotatedClass(TwinkleToes.class);
+ config.buildSessionFactory();
+ String[] schema = config
+ .generateSchemaCreationScript(new SQLServerDialect());
+ for (String s : schema) {
+ log.debug(s);
+ }
+ String expectedSqlPointyTooth = "create table PointyTooth (id numeric(128,0) not null, " +
+ "bunny_id numeric(128,0) null, primary key (id))";
+ assertEquals("Wrong SQL", expectedSqlPointyTooth, schema[1]);
+
+ String expectedSqlTwinkleToes = "create table TwinkleToes (id numeric(128,0) not null, " +
+ "bunny_id numeric(128,0) null, primary key (id))";
+ assertEquals("Wrong SQL", expectedSqlTwinkleToes, schema[2]);
+ } catch (Exception e) {
+ StringWriter writer = new StringWriter();
+ e.printStackTrace(new PrintWriter(writer));
+ log.debug(writer.toString());
+ fail(e.getMessage());
+ }
+ }
+
+ /**
+ * @see org.hibernate.test.annotations.TestCase#getMappings()
+ */
+ protected Class[] getMappings() {
+ return new Class[] {};
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/UUIDGenerator.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/UUIDGenerator.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/UUIDGenerator.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,34 @@
+package org.hibernate.test.annotations.id.sequences;
+
+import java.io.Serializable;
+import java.math.BigInteger;
+import java.util.UUID;
+
+import org.hibernate.HibernateException;
+import org.hibernate.engine.SessionImplementor;
+import org.hibernate.id.IdentifierGenerator;
+
+/**
+ * Unlike Hibernate's UUID generator. This avoids
+ * meaningless synchronization and has less
+ * than a chance of an asteroid hitting you on the head
+ * even after trillions of rows are inserted. I know
+ * this to be true because it says so in Wikipedia(haha).
+ * http://en.wikipedia.org/wiki/UUID#Random_UUID_probability_of_duplicates
+ *
+ */
+public class UUIDGenerator implements IdentifierGenerator {
+
+ public Serializable generate(SessionImplementor arg0, Object arg1) throws HibernateException {
+ UUID uuid = UUID.randomUUID();
+ String sud = uuid.toString();
+ System.out.println("uuid="+uuid);
+ sud = sud.replaceAll("-", "");
+
+ BigInteger integer = new BigInteger(sud,16);
+
+ System.out.println("bi ="+integer.toString() );
+ return integer;
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Ball.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Ball.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Ball.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,35 @@
+//$Id: Ball.java 14760 2008-06-11 07:33:15Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.sequences.entities;
+
+import java.io.Serializable;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.TableGenerator;
+
+/**
+ * Sample of table generator
+ *
+ * @author Emmanuel Bernard
+ */
+@TableGenerator(name = "EMP_GEN", table = "GENERATOR_TABLE", pkColumnName = "pkey",
+ valueColumnName = "hi", pkColumnValue = "Ball", allocationSize = 10)
+@Entity
+@SuppressWarnings("serial")
+public class Ball implements Serializable {
+ private Integer id;
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.TABLE, generator = "EMP_GEN")
+ @Column(name = "ball_id")
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/BreakDance.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/BreakDance.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/BreakDance.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,27 @@
+//$Id: BreakDance.java 14760 2008-06-11 07:33:15Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.sequences.entities;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.GeneratedValue;
+import javax.persistence.TableGenerator;
+import javax.persistence.GenerationType;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class BreakDance {
+ @Id
+ @GeneratedValue(generator = "memencoIdGen", strategy = GenerationType.TABLE)
+ @TableGenerator(
+ name = "memencoIdGen",
+ table = "hi_id_key",
+ pkColumnName = "id_key",
+ valueColumnName = "next_hi",
+ pkColumnValue = "issue",
+ allocationSize = 1
+ )
+ public Integer id;
+ public String name;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Bunny.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Bunny.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Bunny.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,46 @@
+//$Id: Bunny.java 14761 2008-06-11 13:51:06Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.sequences.entities;
+
+import java.io.Serializable;
+import java.math.BigInteger;
+import java.util.Set;
+
+import javax.persistence.Column;
+import javax.persistence.CascadeType;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.OneToMany;
+
+import org.hibernate.annotations.GenericGenerator;
+
+/**
+ * Blown precision on related entity when @JoinColumn is used.
+ *
+ * @see ANN-748
+ * @author Andrew C. Oliver andyspam(a)osintegrators.com
+ */
+@Entity
+@SuppressWarnings("serial")
+public class Bunny implements Serializable {
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "java5_uuid")
+ @GenericGenerator(name = "java5_uuid", strategy = "org.hibernate.test.annotations.id.UUIDGenerator")
+ @Column(name = "id", precision = 128, scale = 0)
+ private BigInteger id;
+
+ @OneToMany(mappedBy = "bunny", cascade = { CascadeType.PERSIST })
+ Set<PointyTooth> teeth;
+
+ @OneToMany(mappedBy = "bunny", cascade = { CascadeType.PERSIST })
+ Set<TwinkleToes> toes;
+
+ public void setTeeth(Set<PointyTooth> teeth) {
+ this.teeth = teeth;
+ }
+
+ public BigInteger getId() {
+ return id;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Computer.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Computer.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Computer.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,34 @@
+//$Id: Computer.java 14760 2008-06-11 07:33:15Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.sequences.entities;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity()
+public class Computer {
+ private Long id;
+ private String serialNumber;
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.TABLE)
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getSerialNumber() {
+ return serialNumber;
+ }
+
+ public void setSerialNumber(String serialNumber) {
+ this.serialNumber = serialNumber;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Department.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Department.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Department.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,33 @@
+//$Id: Department.java 14760 2008-06-11 07:33:15Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.sequences.entities;
+
+import java.io.Serializable;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+
+/**
+ * Sample of method generator
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity
+@SuppressWarnings("serial")
+public class Department implements Serializable {
+ private Long id;
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_DEPT")
+ @javax.persistence.SequenceGenerator(
+ name = "SEQ_DEPT",
+ sequenceName = "my_sequence"
+ )
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long long1) {
+ id = long1;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Dog.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Dog.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Dog.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,42 @@
+//$Id: Dog.java 14760 2008-06-11 07:33:15Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.sequences.entities;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Table;
+import javax.persistence.TableGenerator;
+
+/**
+ * Share the generator table decribed by the GEN_TABLE GeneratedIdTable
+ * using the Dog key as discriminator
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Table(name = "tbl_dog")
+@TableGenerator(name = "DogGen", table = "GENERATOR_TABLE", pkColumnName = "pkey",
+ valueColumnName = "hi", pkColumnValue = "Dog", allocationSize = 10)
+public class Dog {
+ private Integer id;
+ private String name;
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.TABLE, generator = "DogGen")
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/FirTree.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/FirTree.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/FirTree.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,11 @@
+//$Id: FirTree.java 14760 2008-06-11 07:33:15Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.sequences.entities;
+
+import javax.persistence.Entity;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class FirTree extends Tree {
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Footballer.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Footballer.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Footballer.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,73 @@
+//$Id: Footballer.java 14760 2008-06-11 07:33:15Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.sequences.entities;
+
+import javax.persistence.DiscriminatorColumn;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.IdClass;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+(a)IdClass(FootballerPk.class)
+@DiscriminatorColumn(name = "bibi")
+public class Footballer {
+ private String firstname;
+ private String lastname;
+ private String club;
+
+ public Footballer() {
+ }
+
+ public Footballer(String firstname, String lastname, String club) {
+ this.firstname = firstname;
+ this.lastname = lastname;
+ this.club = club;
+ }
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( !( o instanceof Footballer ) ) return false;
+
+ final Footballer footballer = (Footballer) o;
+
+ if ( !firstname.equals( footballer.firstname ) ) return false;
+ if ( !lastname.equals( footballer.lastname ) ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ int result;
+ result = firstname.hashCode();
+ result = 29 * result + lastname.hashCode();
+ return result;
+ }
+
+ @Id
+ public String getFirstname() {
+ return firstname;
+ }
+
+ public void setFirstname(String firstname) {
+ this.firstname = firstname;
+ }
+
+ @Id
+ public String getLastname() {
+ return lastname;
+ }
+
+ public void setLastname(String lastname) {
+ this.lastname = lastname;
+ }
+
+ public String getClub() {
+ return club;
+ }
+
+ public void setClub(String club) {
+ this.club = club;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/FootballerPk.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/FootballerPk.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/FootballerPk.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,62 @@
+//$Id: FootballerPk.java 14760 2008-06-11 07:33:15Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.sequences.entities;
+
+import java.io.Serializable;
+import javax.persistence.Column;
+import javax.persistence.Embeddable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Embeddable
+@SuppressWarnings("serial")
+public class FootballerPk implements Serializable {
+ private String firstname;
+ private String lastname;
+
+ @Column(name = "fb_fname")
+ public String getFirstname() {
+ return firstname;
+ }
+
+ public String getLastname() {
+ return lastname;
+ }
+
+ public void setFirstname(String firstname) {
+ this.firstname = firstname;
+ }
+
+ public void setLastname(String lastname) {
+ this.lastname = lastname;
+ }
+
+ public FootballerPk() {
+ }
+
+ public FootballerPk(String firstname, String lastname) {
+ this.firstname = firstname;
+ this.lastname = lastname;
+
+ }
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( !( o instanceof FootballerPk ) ) return false;
+
+ final FootballerPk footballerPk = (FootballerPk) o;
+
+ if ( !firstname.equals( footballerPk.firstname ) ) return false;
+ if ( !lastname.equals( footballerPk.lastname ) ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ int result;
+ result = firstname.hashCode();
+ result = 29 * result + lastname.hashCode();
+ return result;
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Furniture.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Furniture.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Furniture.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,33 @@
+//$Id: Furniture.java 14760 2008-06-11 07:33:15Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.sequences.entities;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+import org.hibernate.annotations.GenericGenerator;
+import org.hibernate.annotations.Parameter;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Furniture {
+ private Integer id;
+
+ @Id
+ @GeneratedValue(generator = "hibseq")
+ @GenericGenerator(name = "hibseq", strategy = "seqhilo",
+ parameters = {
+ @Parameter(name = "max_lo", value = "5"),
+ @Parameter(name = "sequence", value = "heybabyhey")
+ }
+ )
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/GoalKeeper.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/GoalKeeper.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/GoalKeeper.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,17 @@
+//$Id: GoalKeeper.java 14760 2008-06-11 07:33:15Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.sequences.entities;
+
+import javax.persistence.Entity;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class GoalKeeper extends Footballer {
+ public GoalKeeper() {
+ }
+
+ public GoalKeeper(String firstname, String lastname, String club) {
+ super( firstname, lastname, club );
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Home.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Home.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Home.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,26 @@
+//$Id: Home.java 14760 2008-06-11 07:33:15Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.sequences.entities;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * Default sequence generation usage
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Home {
+ private Long id;
+
+ @Id
+ @GeneratedValue
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Location.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Location.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Location.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,35 @@
+//$Id: Location.java 14760 2008-06-11 07:33:15Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.sequences.entities;
+
+import java.io.Serializable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@SuppressWarnings("serial")
+public class Location implements Serializable {
+ public double longitude;
+ public double latitude;
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( o == null || getClass() != o.getClass() ) return false;
+
+ final Location location = (Location) o;
+
+ if ( Double.compare( location.latitude, latitude ) != 0 ) return false;
+ if ( Double.compare( location.longitude, longitude ) != 0 ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ int result;
+ long temp;
+ temp = longitude != +0.0d ? Double.doubleToLongBits( longitude ) : 0L;
+ result = (int) ( temp ^ ( temp >>> 32 ) );
+ temp = latitude != +0.0d ? Double.doubleToLongBits( latitude ) : 0L;
+ result = 29 * result + (int) ( temp ^ ( temp >>> 32 ) );
+ return result;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/MilitaryBuilding.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/MilitaryBuilding.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/MilitaryBuilding.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,18 @@
+//$Id: MilitaryBuilding.java 14760 2008-06-11 07:33:15Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.sequences.entities;
+
+import javax.persistence.Id;
+import javax.persistence.IdClass;
+import javax.persistence.MappedSuperclass;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@MappedSuperclass
+(a)IdClass(Location.class)
+public class MilitaryBuilding {
+ @Id
+ public double longitude;
+ @Id
+ public double latitude;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Monkey.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Monkey.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Monkey.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,24 @@
+//$
+package org.hibernate.test.annotations.id.sequences.entities;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * @author Paul Cowan
+ */
+@Entity
+public class Monkey {
+ private String id;
+
+ @Id
+ @GeneratedValue(generator = "system-uuid-2")
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Phone.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Phone.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Phone.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,29 @@
+//$Id: Phone.java 14760 2008-06-11 07:33:15Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.sequences.entities;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity()
+public class Phone {
+ private Integer id;
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "Phone_Gen")
+ @javax.persistence.SequenceGenerator(
+ name = "Phone_Gen",
+ sequenceName = "phone_seq"
+ )
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Planet.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Planet.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Planet.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,6 @@
+// $Id: Planet.java 14785 2008-06-19 10:44:33Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.sequences.entities;
+
+public enum Planet {
+ MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE, PLUTO;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/PlanetCheatSheet.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/PlanetCheatSheet.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/PlanetCheatSheet.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,85 @@
+package org.hibernate.test.annotations.id.sequences.entities;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.EnumType;
+import javax.persistence.Enumerated;
+import javax.persistence.Id;
+
+
+/**
+ * Test entity for enum type as id.
+ *
+ * @author Hardy Ferentschik
+ * @see ANN-744
+ */
+@Entity
+public class PlanetCheatSheet {
+
+ @Id
+ @Enumerated(EnumType.STRING)
+ @Column(name = "planet")
+ private Planet planet;
+
+ private double mass;
+
+ private double radius;
+
+ private long numberOfInhabitants;
+
+ public Planet getPlanet() {
+ return planet;
+ }
+
+ public void setPlanet(Planet planet) {
+ this.planet = planet;
+ }
+
+ public double getMass() {
+ return mass;
+ }
+
+ public void setMass(double mass) {
+ this.mass = mass;
+ }
+
+ public double getRadius() {
+ return radius;
+ }
+
+ public void setRadius(double radius) {
+ this.radius = radius;
+ }
+
+ public long getNumberOfInhabitants() {
+ return numberOfInhabitants;
+ }
+
+ public void setNumberOfInhabitants(long numberOfInhabitants) {
+ this.numberOfInhabitants = numberOfInhabitants;
+ }
+
+ /**
+ * Constructs a <code>String</code> with all attributes
+ * in name = value format.
+ *
+ * @return a <code>String</code> representation
+ * of this object.
+ */
+ public String toString()
+ {
+ final String TAB = " ";
+
+ String retValue = "";
+
+ retValue = "PlanetCheatSheet ( "
+ + super.toString() + TAB
+ + "planet = " + this.planet + TAB
+ + "mass = " + this.mass + TAB
+ + "radius = " + this.radius + TAB
+ + "numberOfInhabitants = " + this.numberOfInhabitants + TAB
+ + " )";
+
+ return retValue;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/PointyTooth.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/PointyTooth.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/PointyTooth.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,44 @@
+//$Id: PointyTooth.java 14761 2008-06-11 13:51:06Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.sequences.entities;
+
+import java.io.Serializable;
+import java.math.BigInteger;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+
+import org.hibernate.annotations.GenericGenerator;
+
+/**
+ * Blown precision on related entity when @JoinColumn is used.
+ * Does not cause an issue on HyperSonic, but replicates nicely on PGSQL.
+ *
+ * @see ANN-748
+ * @author Andrew C. Oliver andyspam(a)osintegrators.com
+ */
+@Entity
+@SuppressWarnings("serial")
+public class PointyTooth implements Serializable {
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "java5_uuid")
+ @GenericGenerator(name = "java5_uuid", strategy = "org.hibernate.test.annotations.id.UUIDGenerator")
+ @Column(name = "id", precision = 128, scale = 0)
+ private BigInteger id;
+
+ @ManyToOne
+ @JoinColumn(name = "bunny_id")
+ Bunny bunny;
+
+ public void setBunny(Bunny bunny) {
+ this.bunny = bunny;
+ }
+
+ public BigInteger getId() {
+ return id;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Shoe.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Shoe.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Shoe.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,29 @@
+//$Id: Shoe.java 14760 2008-06-11 07:33:15Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.sequences.entities;
+
+import java.io.Serializable;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+
+/**
+ * sample of Sequance generator
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity
+@SuppressWarnings("serial")
+public class Shoe implements Serializable {
+ private Long id;
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_GEN")
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long long1) {
+ id = long1;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/SoundSystem.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/SoundSystem.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/SoundSystem.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,42 @@
+//$Id: SoundSystem.java 14760 2008-06-11 07:33:15Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.sequences.entities;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class SoundSystem {
+ private String id;
+ private String brand;
+ private String model;
+
+ @Id
+ @GeneratedValue(generator = "system-uuid")
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public String getBrand() {
+ return brand;
+ }
+
+ public void setBrand(String brand) {
+ this.brand = brand;
+ }
+
+ public String getModel() {
+ return model;
+ }
+
+ public void setModel(String model) {
+ this.model = model;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Store.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Store.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Store.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,33 @@
+//$Id: Store.java 14760 2008-06-11 07:33:15Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.sequences.entities;
+
+import java.io.Serializable;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+
+/**
+ * Sample of class generator
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity
+(a)javax.persistence.SequenceGenerator(
+ name = "SEQ_STORE",
+ sequenceName = "my_sequence"
+)
+@SuppressWarnings("serial")
+public class Store implements Serializable {
+ private Long id;
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_STORE")
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long long1) {
+ id = long1;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Tower.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Tower.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Tower.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,14 @@
+//$Id: Tower.java 14760 2008-06-11 07:33:15Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.sequences.entities;
+
+import javax.persistence.AttributeOverride;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@AttributeOverride(name = "longitude", column = @Column(name = "fld_longitude"))
+public class Tower extends MilitaryBuilding {
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Tree.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Tree.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/Tree.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,24 @@
+//$Id: Tree.java 14760 2008-06-11 07:33:15Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.sequences.entities;
+
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.MappedSuperclass;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@MappedSuperclass
+public class Tree {
+ private Integer id;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/TwinkleToes.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/TwinkleToes.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/entities/TwinkleToes.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,42 @@
+//$Id: TwinkleToes.java 14761 2008-06-11 13:51:06Z hardy.ferentschik $
+package org.hibernate.test.annotations.id.sequences.entities;
+
+import java.io.Serializable;
+import java.math.BigInteger;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.ManyToOne;
+
+import org.hibernate.annotations.GenericGenerator;
+
+/**
+ * Blown precision on related entity when @JoinColumn is used.
+ * Does not cause an issue on HyperSonic, but replicates nicely on PGSQL.
+ *
+ * @see ANN-748
+ * @author Andrew C. Oliver andyspam(a)osintegrators.com
+ */
+@Entity
+@SuppressWarnings("serial")
+public class TwinkleToes implements Serializable {
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "java5_uuid")
+ @GenericGenerator(name = "java5_uuid", strategy = "org.hibernate.test.annotations.id.UUIDGenerator")
+ @Column(name = "id", precision = 128, scale = 0)
+ private BigInteger id;
+
+ @ManyToOne
+ Bunny bunny;
+
+ public void setBunny(Bunny bunny) {
+ this.bunny = bunny;
+ }
+
+ public BigInteger getId() {
+ return id;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/package-info.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/package-info.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/id/sequences/package-info.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,11 @@
+//$Id: package-info.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+/**
+ * Test package for metatata facilities
+ * It contains an example of package level metadata
+ */
+(a)org.hibernate.annotations.GenericGenerator(name = "system-uuid", strategy = "uuid")
+(a)org.hibernate.annotations.GenericGenerators(
+ @org.hibernate.annotations.GenericGenerator(name = "system-uuid-2", strategy = "uuid")
+)
+package org.hibernate.test.annotations.id.sequences;
+
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/identifiercollection/IdentifierCollectionTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/identifiercollection/IdentifierCollectionTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/identifiercollection/IdentifierCollectionTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,45 @@
+//$Id: IdentifierCollectionTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.identifiercollection;
+
+import org.hibernate.test.annotations.TestCase;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class IdentifierCollectionTest extends TestCase {
+ public void testIdBag() throws Exception {
+ Passport passport = new Passport();
+ passport.setName( "Emmanuel Bernard" );
+ Stamp canada = new Stamp();
+ canada.setCountry( "Canada" );
+ passport.getStamps().add( canada );
+ passport.getVisaStamp().add( canada );
+ Stamp norway = new Stamp();
+ norway.setCountry( "Norway" );
+ passport.getStamps().add( norway );
+ passport.getStamps().add(canada);
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ s.persist( passport );
+ s.flush();
+ //s.clear();
+ passport = (Passport) s.get( Passport.class, passport.getId() );
+ int canadaCount = 0;
+ for ( Stamp stamp : passport.getStamps() ) {
+ if ( "Canada".equals( stamp.getCountry() ) ) canadaCount++;
+ }
+ assertEquals( 2, canadaCount );
+ assertEquals( 1, passport.getVisaStamp().size() );
+ tx.rollback();
+ s.close();
+ }
+ protected Class[] getMappings() {
+ return new Class[] {
+ Passport.class,
+ Stamp.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/identifiercollection/Passport.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/identifiercollection/Passport.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/identifiercollection/Passport.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,70 @@
+//$Id: Passport.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.identifiercollection;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import javax.persistence.CascadeType;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.JoinTable;
+import javax.persistence.ManyToMany;
+import javax.persistence.TableGenerator;
+
+import org.hibernate.annotations.CollectionId;
+import org.hibernate.annotations.Type;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@TableGenerator(name="ids_generator", table="IDS")
+public class Passport {
+ @Id @GeneratedValue @Column(name="passport_id") private Long id;
+ private String name;
+
+ @ManyToMany(cascade = CascadeType.ALL)
+ @JoinTable(name="PASSPORT_STAMP")
+ @CollectionId(columns = @Column(name="COLLECTION_ID"), type=@Type(type="long"), generator = "generator")
+ @TableGenerator(name="generator", table="IDSTAMP")
+ private Collection<Stamp> stamps = new ArrayList();
+
+ @ManyToMany(cascade = CascadeType.ALL)
+ @JoinTable(name="PASSPORT_VISASTAMP")
+ @CollectionId(columns = @Column(name="COLLECTION_ID"), type=@Type(type="long"), generator = "ids_generator")
+ //TODO test identity generator
+ private Collection<Stamp> visaStamp = new ArrayList();
+
+ 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<Stamp> getStamps() {
+ return stamps;
+ }
+
+ public void setStamps(Collection<Stamp> stamps) {
+ this.stamps = stamps;
+ }
+
+ public Collection<Stamp> getVisaStamp() {
+ return visaStamp;
+ }
+
+ public void setVisaStamp(Collection<Stamp> visaStamp) {
+ this.visaStamp = visaStamp;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/identifiercollection/Stamp.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/identifiercollection/Stamp.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/identifiercollection/Stamp.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,31 @@
+//$Id: Stamp.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.identifiercollection;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.GeneratedValue;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Stamp {
+ @Id @GeneratedValue private Long id;
+ private String country;
+
+ public String getCountry() {
+ return country;
+ }
+
+ public void setCountry(String country) {
+ this.country = country;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/BasketItems.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/BasketItems.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/BasketItems.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,56 @@
+//$
+package org.hibernate.test.annotations.idmanytoone;
+
+import java.io.Serializable;
+import javax.persistence.IdClass;
+import javax.persistence.Id;
+import javax.persistence.Column;
+import javax.persistence.CascadeType;
+import javax.persistence.FetchType;
+import javax.persistence.JoinColumn;
+import javax.persistence.Table;
+import javax.persistence.ManyToOne;
+import javax.persistence.Basic;
+import javax.persistence.JoinColumns;
+import javax.persistence.Entity;
+
+@Entity
+@Table(name="BasketItems")
+(a)org.hibernate.annotations.Proxy(lazy=false)
+(a)IdClass(BasketItemsPK.class)
+public class BasketItems implements Serializable {
+
+ private static final long serialVersionUID = -4580497316918713849L;
+
+ @Id
+ @ManyToOne(cascade={ CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH })
+ @JoinColumns({ @JoinColumn(name="basketDatetime", referencedColumnName="basketDatetime"), @JoinColumn(name="customerID", referencedColumnName="customerID") })
+ @Basic(fetch= FetchType.LAZY)
+ private ShoppingBaskets shoppingBaskets;
+
+ @Column(name="cost", nullable=false)
+ @Id
+ private Double cost;
+
+ public void setCost(double value) {
+ setCost(new Double(value));
+ }
+
+ public void setCost(Double value) {
+ this.cost = value;
+ }
+
+ public Double getCost() {
+ return cost;
+ }
+
+ public void setShoppingBaskets(ShoppingBaskets value) {
+ this.shoppingBaskets = value;
+ }
+
+ public ShoppingBaskets getShoppingBaskets() {
+ return shoppingBaskets;
+ }
+
+}
+
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/BasketItemsPK.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/BasketItemsPK.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/BasketItemsPK.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,72 @@
+//$
+package org.hibernate.test.annotations.idmanytoone;
+
+import java.io.Serializable;
+import javax.persistence.CascadeType;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinColumns;
+import javax.persistence.Column;
+import javax.persistence.ManyToOne;
+import javax.persistence.Basic;
+import javax.persistence.Embeddable;
+import javax.persistence.FetchType;
+
+@Embeddable
+public class BasketItemsPK implements Serializable {
+
+ private static final long serialVersionUID = 3585214409096105241L;
+
+ public boolean equals(Object aObj) {
+ if (aObj == this)
+ return true;
+ if (!(aObj instanceof BasketItemsPK))
+ return false;
+ BasketItemsPK basketitemspk = (BasketItemsPK)aObj;
+ if (getShoppingBaskets() == null && basketitemspk.getShoppingBaskets() != null)
+ return false;
+ if (!getShoppingBaskets().equals(basketitemspk.getShoppingBaskets()))
+ return false;
+ if ((getCost() != null && !getCost().equals(basketitemspk.getCost())) || (getCost() == null && basketitemspk.getCost() != null))
+ return false;
+ return true;
+ }
+
+ public int hashCode() {
+ int hashcode = 0;
+ if (getShoppingBaskets() != null) {
+ hashcode = hashcode + (getShoppingBaskets().getOwner() == null ? 0 : getShoppingBaskets().getOwner().hashCode());
+ hashcode = hashcode + (getShoppingBaskets().getBasketDatetime() == null ? 0 : getShoppingBaskets().getBasketDatetime().hashCode());
+ }
+ hashcode = hashcode + (getCost() == null ? 0 : getCost().hashCode());
+ return hashcode;
+ }
+
+ @Id
+ @ManyToOne(cascade={ CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH })
+ @JoinColumns({ @JoinColumn(name="basketDatetime", referencedColumnName="basketDatetime"), @JoinColumn(name="customerID", referencedColumnName="customerID") })
+ @Basic(fetch= FetchType.LAZY)
+ private ShoppingBaskets shoppingBaskets;
+
+ public void setShoppingBaskets(ShoppingBaskets value) {
+ this.shoppingBaskets = value;
+ }
+
+ public ShoppingBaskets getShoppingBaskets() {
+ return this.shoppingBaskets;
+ }
+
+ @Column(name="cost", nullable=false)
+ @Id
+ private Double cost;
+
+ public void setCost(Double value) {
+ this.cost = value;
+ }
+
+ public Double getCost() {
+ return this.cost;
+ }
+
+}
+
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/Card.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/Card.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/Card.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,70 @@
+//$Id: Card.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.idmanytoone;
+
+import java.io.Serializable;
+import java.util.Set;
+import javax.persistence.Embeddable;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.ManyToOne;
+import javax.persistence.CascadeType;
+import javax.persistence.FetchType;
+import javax.persistence.OneToMany;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Card {
+
+ @Id
+ private CardPrimaryKey primaryKey = new CardPrimaryKey();
+
+ @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "primaryKey.card")
+ private Set<CardField> fields;
+
+ @ManyToOne
+ private CardField mainCardField;
+
+ @Embeddable
+ public static class CardPrimaryKey implements Serializable {
+
+ public CardPrimaryKey() {}
+
+ @ManyToOne(optional = false)
+ private Project project;
+
+ public Project getProject() {
+ return project;
+ }
+
+ public void setProject(Project project) {
+ this.project = project;
+ }
+
+ }
+
+ public Set<CardField> getFields() {
+ return fields;
+ }
+
+ public void setFields(Set<CardField> fields) {
+ this.fields = fields;
+ }
+
+ public CardPrimaryKey getPrimaryKey() {
+ return primaryKey;
+ }
+
+ public void setPrimaryKey(CardPrimaryKey primaryKey) {
+ this.primaryKey = primaryKey;
+ }
+
+ public CardField getMainCardField() {
+ return mainCardField;
+ }
+
+ public void setMainCardField(CardField mainCardField) {
+ this.mainCardField = mainCardField;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/CardField.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/CardField.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/CardField.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,64 @@
+//$Id: CardField.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.idmanytoone;
+
+import java.io.Serializable;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.ManyToOne;
+import javax.persistence.Embeddable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class CardField {
+
+ @Id
+ private PrimaryKey primaryKey = new PrimaryKey();
+
+ @ManyToOne
+ private Card cardtmp;
+
+ @Embeddable
+ public static class PrimaryKey implements Serializable {
+
+ @ManyToOne(optional = false)
+ private Card card;
+
+ @ManyToOne(optional = false)
+ private CardKey key;
+
+ public Card getCard() {
+ return card;
+ }
+
+ public void setCard(Card card) {
+ this.card = card;
+ }
+
+ public CardKey getKey() {
+ return key;
+ }
+
+ public void setKey(CardKey key) {
+ this.key = key;
+ }
+ }
+
+ public Card getCardtmp() {
+ return cardtmp;
+ }
+
+ public void setCardtmp(Card cardtmp) {
+ this.cardtmp = cardtmp;
+ }
+
+ public PrimaryKey getPrimaryKey() {
+ return primaryKey;
+ }
+
+ public void setPrimaryKey(PrimaryKey primaryKey) {
+ this.primaryKey = primaryKey;
+ }
+}
+
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/CardKey.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/CardKey.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/CardKey.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,24 @@
+//$Id: CardKey.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.idmanytoone;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.GeneratedValue;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class CardKey {
+ @Id
+ @GeneratedValue
+ private int id;
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/Customer.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/Customer.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/Customer.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,28 @@
+//$Id: Customer.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.idmanytoone;
+
+import java.io.Serializable;
+import java.util.Set;
+import javax.persistence.Table;
+import javax.persistence.Entity;
+import javax.persistence.OneToMany;
+import javax.persistence.Id;
+import javax.persistence.GeneratedValue;
+
+/**
+ * @author Emmanuel Bernard
+ */
+
+
+
+@Entity
+@Table(name = "Bs")
+public class Customer implements Serializable {
+ @Id @GeneratedValue
+ public Integer id;
+
+ @OneToMany(mappedBy = "customer")
+ public Set<StoreCustomer> stores;
+
+ private static final long serialVersionUID = 3818501706063039923L;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/Customers.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/Customers.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/Customers.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,48 @@
+//$
+package org.hibernate.test.annotations.idmanytoone;
+
+import java.io.Serializable;
+import javax.persistence.Id;
+import javax.persistence.Column;
+import javax.persistence.CascadeType;
+import javax.persistence.Entity;
+import javax.persistence.OneToMany;
+import javax.persistence.Table;
+
+@Entity
+@Table(name="Customers")
+(a)org.hibernate.annotations.Proxy(lazy=false)
+public class Customers implements Serializable {
+
+ private static final long serialVersionUID = -885167444315163039L;
+
+ @Column(name="customerID", nullable=false)
+ @Id
+ private int customerID;
+
+ @OneToMany(mappedBy="owner", cascade= CascadeType.ALL, targetEntity=ShoppingBaskets.class)
+ @org.hibernate.annotations.LazyCollection(org.hibernate.annotations.LazyCollectionOption.TRUE)
+ private java.util.Set shoppingBasketses = new java.util.HashSet();
+
+ public void setCustomerID(int value) {
+ this.customerID = value;
+ }
+
+ public int getCustomerID() {
+ return customerID;
+ }
+
+ public int getORMID() {
+ return getCustomerID();
+ }
+
+ public void setShoppingBasketses(java.util.Set value) {
+ this.shoppingBasketses = value;
+ }
+
+ public java.util.Set getShoppingBasketses() {
+ return shoppingBasketses;
+ }
+
+}
+
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/IdManyToOneTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/IdManyToOneTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/IdManyToOneTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,82 @@
+//$Id: IdManyToOneTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.idmanytoone;
+
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class IdManyToOneTest extends TestCase {
+ public void testFkCreationOrdering() throws Exception {
+ //no real test case, the sessionFactory building is tested
+ Session s = openSession();
+ s.close();
+ }
+
+ public void getBiDirOneToManyInId() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ CardKey key = new CardKey();
+ s.persist( key );
+ Project project = new Project();
+ s.persist( project );
+ Card card = new Card();
+ card.getPrimaryKey().setProject( project );
+ s.persist( card );
+ CardField field = new CardField();
+ field.getPrimaryKey().setKey( key );
+ field.getPrimaryKey().setCard( card );
+ s.persist( field );
+ card.setMainCardField( field );
+ s.flush();
+ s.clear();
+ card = (Card) s.createQuery( "from Card c").list().get(0);
+ assertEquals( 1, card.getFields().size() );
+ assertEquals( card.getMainCardField(), card.getFields().iterator().next() );
+ tx.rollback();
+ s.close();
+ }
+
+ public void testIdClassManyToOne() {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Store store = new Store();
+ Customer customer = new Customer();
+ s.persist( store );
+ s.persist( customer );
+ StoreCustomer sc = new StoreCustomer( store, customer );
+ s.persist( sc );
+ s.flush();
+ s.clear();
+
+ store = (Store) s.get(Store.class, store.id );
+ assertEquals( 1, store.customers.size() );
+ assertEquals( customer.id, store.customers.iterator().next().customer.id );
+ tx.rollback();
+
+ //TODO test Customers / ShoppingBaskets / BasketItems testIdClassManyToOneWithReferenceColumn
+ s.close();
+ }
+
+ protected Class[] getMappings() {
+ return new Class[] {
+ Store.class,
+ Customer.class,
+ StoreCustomer.class,
+ CardKey.class,
+ CardField.class,
+ Card.class,
+ Project.class,
+
+ //tested only through deployment
+ //ANN-590 testIdClassManyToOneWithReferenceColumn
+ Customers.class,
+ ShoppingBaskets.class,
+ ShoppingBasketsPK.class,
+ BasketItems.class,
+ BasketItemsPK.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/Project.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/Project.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/Project.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,25 @@
+//$Id: Project.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.idmanytoone;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.GeneratedValue;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Project {
+
+ @Id
+ @GeneratedValue
+ private int id;
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/ShoppingBaskets.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/ShoppingBaskets.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/ShoppingBaskets.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,66 @@
+//$
+package org.hibernate.test.annotations.idmanytoone;
+
+import java.io.Serializable;
+
+import javax.persistence.Basic;
+import javax.persistence.CascadeType;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.Id;
+import javax.persistence.IdClass;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinColumns;
+import javax.persistence.ManyToOne;
+import javax.persistence.OneToMany;
+import javax.persistence.Table;
+
+@Entity
+@Table(name="ShoppingBasket")
+(a)org.hibernate.annotations.Proxy(lazy=false)
+(a)IdClass(ShoppingBasketsPK.class)
+public class ShoppingBaskets implements Serializable {
+
+ private static final long serialVersionUID = 4739240471638885734L;
+
+ @Id
+ @ManyToOne(cascade={ CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH })
+ @JoinColumns({ @JoinColumn(name="customerID", referencedColumnName="customerID") })
+ @Basic(fetch=FetchType.LAZY)
+ private Customers owner;
+
+ @Column(name="basketDatetime", nullable=false)
+ @Id
+ private java.util.Date basketDatetime;
+
+ @OneToMany(mappedBy="shoppingBaskets", cascade=CascadeType.ALL, targetEntity=BasketItems.class)
+ @org.hibernate.annotations.LazyCollection(org.hibernate.annotations.LazyCollectionOption.TRUE)
+ private java.util.Set items = new java.util.HashSet();
+
+ public void setBasketDatetime(java.util.Date value) {
+ this.basketDatetime = value;
+ }
+
+ public java.util.Date getBasketDatetime() {
+ return basketDatetime;
+ }
+
+ public void setOwner(Customers value) {
+ this.owner = value;
+ }
+
+ public Customers getOwner() {
+ return owner;
+ }
+
+ public void setItems(java.util.Set value) {
+ this.items = value;
+ }
+
+ public java.util.Set getItems() {
+ return items;
+ }
+
+}
+
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/ShoppingBasketsPK.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/ShoppingBasketsPK.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/ShoppingBasketsPK.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,70 @@
+//$
+package org.hibernate.test.annotations.idmanytoone;
+
+import java.io.Serializable;
+import javax.persistence.CascadeType;
+import javax.persistence.Id;
+import javax.persistence.ManyToOne;
+import javax.persistence.JoinColumns;
+import javax.persistence.FetchType;
+import javax.persistence.Basic;
+import javax.persistence.JoinColumn;
+import javax.persistence.Column;
+import javax.persistence.Embeddable;
+
+@Embeddable
+public class ShoppingBasketsPK implements Serializable {
+ private static final long serialVersionUID = 4121297376338222776L;
+
+ public boolean equals(Object aObj) {
+ if (aObj == this)
+ return true;
+ if (!(aObj instanceof ShoppingBasketsPK))
+ return false;
+ ShoppingBasketsPK shoppingbasketspk = (ShoppingBasketsPK)aObj;
+ if (getOwner() == null && shoppingbasketspk.getOwner() != null)
+ return false;
+ if (!getOwner().equals(shoppingbasketspk.getOwner()))
+ return false;
+ if (getBasketDatetime() != shoppingbasketspk.getBasketDatetime())
+ return false;
+ return true;
+ }
+
+ public int hashCode() {
+ int hashcode = 0;
+ if (getOwner() != null) {
+ hashcode = hashcode + (int) getOwner().getORMID();
+ }
+ hashcode = hashcode + (getBasketDatetime() == null ? 0 : getBasketDatetime().hashCode());
+ return hashcode;
+ }
+
+ @Id
+ @ManyToOne(cascade={ CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH })
+ @JoinColumns({ @JoinColumn(name="customerID", referencedColumnName="customerID") })
+ @Basic(fetch= FetchType.LAZY)
+ private Customers owner;
+
+ public void setOwner(Customers value) {
+ this.owner = value;
+ }
+
+ public Customers getOwner() {
+ return this.owner;
+ }
+
+ @Column(name="basketDatetime", nullable=false)
+ @Id
+ private java.util.Date basketDatetime;
+
+ public void setBasketDatetime(java.util.Date value) {
+ this.basketDatetime = value;
+ }
+
+ public java.util.Date getBasketDatetime() {
+ return this.basketDatetime;
+ }
+
+}
+
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/Store.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/Store.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/Store.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,27 @@
+//$Id: Store.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.idmanytoone;
+
+import java.io.Serializable;
+import java.util.Set;
+import javax.persistence.Table;
+import javax.persistence.Entity;
+import javax.persistence.OneToMany;
+import javax.persistence.Id;
+import javax.persistence.GeneratedValue;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Table(name = "`As`")
+public class Store implements Serializable {
+ @Id @GeneratedValue
+ public Integer id;
+
+ @OneToMany(mappedBy = "store")
+ public Set<StoreCustomer> customers;
+
+
+ private static final long serialVersionUID = 1748046699322502790L;
+}
+
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/StoreCustomer.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/StoreCustomer.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/StoreCustomer.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,38 @@
+//$Id: StoreCustomer.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.idmanytoone;
+
+import java.io.Serializable;
+import javax.persistence.Id;
+import javax.persistence.Table;
+import javax.persistence.IdClass;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+import javax.persistence.Entity;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Table(name = "ABs")
+@IdClass( StoreCustomerPK.class)
+public class StoreCustomer implements Serializable {
+ StoreCustomer() {}
+ @Id
+ @ManyToOne(optional = false)
+ @JoinColumn(name = "idA")
+ public Store store;
+
+ @Id
+ @ManyToOne(optional = false)
+ @JoinColumn(name = "idB")
+ public Customer customer;
+
+
+ public StoreCustomer(Store store, Customer customer) {
+ this.store = store;
+ this.customer = customer;
+ }
+
+
+ private static final long serialVersionUID = -8295955012787627232L;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/StoreCustomerPK.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/StoreCustomerPK.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/StoreCustomerPK.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,32 @@
+//$Id: StoreCustomerPK.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.idmanytoone;
+
+import java.io.Serializable;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class StoreCustomerPK implements Serializable {
+ StoreCustomerPK() {}
+ @Id
+ @ManyToOne(optional = false)
+ @JoinColumn(name = "idA")
+ public Store store;
+
+ @Id
+ @ManyToOne(optional = false)
+ @JoinColumn(name = "idB")
+ public Customer customer;
+
+
+ public StoreCustomerPK(Store store, Customer customer) {
+ this.store = store;
+ this.customer = customer;
+ }
+
+
+ private static final long serialVersionUID = -1102111921432271459L;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/A.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/A.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/A.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,39 @@
+//$
+package org.hibernate.test.annotations.idmanytoone.alphabetical;
+
+import java.util.List;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.OneToMany;
+
+@Entity
+public class A {
+
+ @Id
+ private int id;
+
+ @OneToMany( mappedBy = "parent" )
+ List<C> children;
+
+ public A() {
+ }
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ public List<C> getChildren() {
+ return children;
+ }
+
+ public void setChildren(List<C> children) {
+ this.children = children;
+ }
+
+
+}
+
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/Acces.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/Acces.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/Acces.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,17 @@
+//$
+package org.hibernate.test.annotations.idmanytoone.alphabetical;
+
+import java.io.Serializable;
+import java.math.BigInteger;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.ManyToOne;
+
+@Entity
+public class Acces implements Serializable {
+ @Id
+ private BigInteger idpk;
+
+ @ManyToOne
+ private Droitacces idpkdracc;
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/AlphabeticalIdManyToOneTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/AlphabeticalIdManyToOneTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/AlphabeticalIdManyToOneTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,24 @@
+//$
+package org.hibernate.test.annotations.idmanytoone.alphabetical;
+
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class AlphabeticalIdManyToOneTest extends TestCase {
+ public void testAlphabeticalTest() throws Exception {
+ //test through deployment
+ }
+
+
+ protected Class[] getMappings() {
+ return new Class[] {
+ B.class,
+ C.class,
+ A.class
+
+
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/AlphabeticalManyToOneTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/AlphabeticalManyToOneTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/AlphabeticalManyToOneTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,22 @@
+//$
+package org.hibernate.test.annotations.idmanytoone.alphabetical;
+
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class AlphabeticalManyToOneTest extends TestCase {
+ public void testAlphabeticalTest() throws Exception {
+ //test through deployment
+ }
+
+ protected Class[] getMappings() {
+ return new Class[] {
+ Acces.class,
+ Droitacces.class,
+ Benefserv.class,
+ Service.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/B.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/B.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/B.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,39 @@
+//$
+package org.hibernate.test.annotations.idmanytoone.alphabetical;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.IdClass;
+
+@Entity
+@IdClass( BId.class )
+public class B {
+
+ @Id
+ private C parent;
+
+ @Id
+ private int sequenceNumber;
+
+ public B() {
+ }
+
+ public C getParent() {
+ return parent;
+ }
+
+ public void setParent(C parent) {
+ this.parent = parent;
+ }
+
+ public int getSequenceNumber() {
+ return sequenceNumber;
+ }
+
+ public void setSequenceNumber(int sequenceNumber) {
+ this.sequenceNumber = sequenceNumber;
+ }
+
+
+}
+
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/BId.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/BId.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/BId.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,69 @@
+//$
+package org.hibernate.test.annotations.idmanytoone.alphabetical;
+
+import java.io.Serializable;
+import javax.persistence.Embeddable;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinColumns;
+import javax.persistence.ManyToOne;
+
+@Embeddable
+public class BId implements Serializable {
+
+ @ManyToOne
+ @JoinColumns( {
+ @JoinColumn( name = "aId", nullable = false ),
+ @JoinColumn( name = "bSequenceNumber", nullable = false )
+ } )
+ private C parent;
+
+ private int sequenceNumber;
+
+ public BId() {
+ }
+
+ public C getParent() {
+ return parent;
+ }
+
+ public void setParent(C parent) {
+ this.parent = parent;
+ }
+
+ public int getSequenceNumber() {
+ return sequenceNumber;
+ }
+
+ public void setSequenceNumber(int sequenceNumber) {
+ this.sequenceNumber = sequenceNumber;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ( ( parent == null ) ? 0 : parent.hashCode() );
+ result = prime * result + sequenceNumber;
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if ( this == obj )
+ return true;
+ if ( obj == null )
+ return false;
+ if ( getClass() != obj.getClass() )
+ return false;
+ final BId other = (BId) obj;
+ if ( parent == null ) {
+ if ( other.parent != null )
+ return false;
+ }
+ else if ( !parent.equals( other.parent ) )
+ return false;
+ if ( sequenceNumber != other.sequenceNumber )
+ return false;
+ return true;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/Benefserv.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/Benefserv.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/Benefserv.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,17 @@
+//$
+package org.hibernate.test.annotations.idmanytoone.alphabetical;
+
+import java.math.BigInteger;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.ManyToOne;
+
+@Entity
+public class Benefserv {
+ @Id
+ private BigInteger idpk;
+
+ @ManyToOne
+ private Service idpkser;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/C.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/C.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/C.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,52 @@
+//$
+package org.hibernate.test.annotations.idmanytoone.alphabetical;
+
+import java.util.List;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.IdClass;
+import javax.persistence.OneToMany;
+
+@Entity
+@IdClass( CId.class )
+public class C {
+
+ @Id
+ private A parent;
+
+ @Id
+ private int sequenceNumber;
+
+ @OneToMany( mappedBy = "parent" )
+ List<B> children;
+
+ public C() {
+ }
+
+ public A getParent() {
+ return parent;
+ }
+
+ public void setParent(A parent) {
+ this.parent = parent;
+ }
+
+ public int getSequenceNumber() {
+ return sequenceNumber;
+ }
+
+ public void setSequenceNumber(int sequenceNumber) {
+ this.sequenceNumber = sequenceNumber;
+ }
+
+ public List<B> getChildren() {
+ return children;
+ }
+
+ public void setChildren(List<B> children) {
+ this.children = children;
+ }
+
+
+}
+
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/CId.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/CId.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/CId.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,67 @@
+//$
+package org.hibernate.test.annotations.idmanytoone.alphabetical;
+
+import java.io.Serializable;
+import javax.persistence.Embeddable;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+
+@Embeddable
+public class CId implements Serializable {
+
+ @ManyToOne
+ @JoinColumn( name = "aId", nullable = false )
+ private A parent;
+
+ private int sequenceNumber;
+
+ public CId() {
+ }
+
+ public A getParent() {
+ return parent;
+ }
+
+ public void setParent(A parent) {
+ this.parent = parent;
+ }
+
+ public int getSequenceNumber() {
+ return sequenceNumber;
+ }
+
+ public void setSequenceNumber(int sequenceNumber) {
+ this.sequenceNumber = sequenceNumber;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ( ( parent == null ) ? 0 : parent.hashCode() );
+ result = prime * result + sequenceNumber;
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if ( this == obj )
+ return true;
+ if ( obj == null )
+ return false;
+ if ( getClass() != obj.getClass() )
+ return false;
+ final CId other = (CId) obj;
+ if ( parent == null ) {
+ if ( other.parent != null )
+ return false;
+ }
+ else if ( !parent.equals( other.parent ) )
+ return false;
+ if ( sequenceNumber != other.sequenceNumber )
+ return false;
+ return true;
+ }
+
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/Droitacces.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/Droitacces.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/Droitacces.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,17 @@
+//$
+package org.hibernate.test.annotations.idmanytoone.alphabetical;
+
+import java.math.BigInteger;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.ManyToOne;
+
+@Entity
+public class Droitacces {
+ @Id
+ private BigInteger idpk;
+
+ @ManyToOne
+ private Benefserv idpkbenef;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/Service.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/Service.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/idmanytoone/alphabetical/Service.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,14 @@
+//$
+package org.hibernate.test.annotations.idmanytoone.alphabetical;
+
+import java.math.BigInteger;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+
+@Entity
+public class Service {
+ @Id
+ private BigInteger idpk;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/immutable/Country.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/immutable/Country.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/immutable/Country.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,57 @@
+//$Id: Country.java 14801 2008-06-24 19:03:32Z hardy.ferentschik $
+package org.hibernate.test.annotations.immutable;
+
+/**
+ * @author Hardy Ferentschik
+ */
+import java.io.Serializable;
+import java.util.List;
+
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.OneToMany;
+
+import org.hibernate.annotations.Cascade;
+import org.hibernate.annotations.Immutable;
+
+@Entity
+@Immutable
+@SuppressWarnings("serial")
+public class Country implements Serializable {
+ private Integer id;
+
+ private String name;
+
+ private List<State> states;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setId(Integer integer) {
+ id = integer;
+ }
+
+ public void setName(String string) {
+ name = string;
+ }
+
+ @OneToMany(fetch = FetchType.LAZY)
+ @Cascade(org.hibernate.annotations.CascadeType.ALL)
+ @Immutable
+ public List<State> getStates() {
+ return states;
+ }
+
+ public void setStates(List<State> states) {
+ this.states = states;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/immutable/Foobar.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/immutable/Foobar.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/immutable/Foobar.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,37 @@
+// $Id: Foobar.java 14801 2008-06-24 19:03:32Z hardy.ferentschik $
+package org.hibernate.test.annotations.immutable;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+import org.hibernate.annotations.Immutable;
+
+/**
+ * @author Hardy Ferentschik
+ */
+@Entity
+public class Foobar {
+ @Id
+ @GeneratedValue
+ private Integer id;
+
+ @Immutable
+ private String name;
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/immutable/ImmutableTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/immutable/ImmutableTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/immutable/ImmutableTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,165 @@
+//$Id: ImmutableTest.java 16426 2009-04-23 16:01:18Z jcosta(a)redhat.com $
+package org.hibernate.test.annotations.immutable;
+
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.hibernate.AnnotationException;
+import org.hibernate.HibernateException;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.cfg.AnnotationConfiguration;
+import org.hibernate.dialect.SQLServerDialect;
+import org.hibernate.test.annotations.TestCase;
+import org.hibernate.test.annotations.fkcircularity.A;
+import org.hibernate.test.annotations.fkcircularity.B;
+import org.hibernate.test.annotations.fkcircularity.C;
+import org.hibernate.test.annotations.fkcircularity.D;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tests for <code>Immutable</code> annotation.
+ *
+ * @author Hardy Ferentschik
+ */
+@SuppressWarnings("unchecked")
+public class ImmutableTest extends TestCase {
+
+ private Logger log = LoggerFactory.getLogger(ImmutableTest.class);
+
+ public ImmutableTest(String x) {
+ super(x);
+ }
+
+ public void testImmutableEntity() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Country country = new Country();
+ country.setName("Germany");
+ s.persist(country);
+ tx.commit();
+ s.close();
+
+ // try changing the entity
+ s = openSession();
+ tx = s.beginTransaction();
+ Country germany = (Country) s.get(Country.class, country.getId());
+ assertNotNull(germany);
+ germany.setName("France");
+ assertEquals("Local name can be changed", "France", germany.getName());
+ s.save(germany);
+ tx.commit();
+ s.close();
+
+ // retrieving the country again - it should be unmodified
+ s = openSession();
+ tx = s.beginTransaction();
+ germany = (Country) s.get(Country.class, country.getId());
+ assertNotNull(germany);
+ assertEquals("Name should not have changed", "Germany", germany.getName());
+ tx.commit();
+ s.close();
+
+// // try deletion
+// s = openSession();
+// tx = s.beginTransaction();
+// s.delete(germany);
+// tx.commit();
+// s.close();
+//
+// s = openSession();
+// tx = s.beginTransaction();
+// germany = (Country) s.get(Country.class, country.getId());
+// assertNotNull(germany);
+// assertEquals("Name should not have changed", "Germany", germany.getName());
+// s.close();
+ }
+
+ public void testImmutableCollection() {
+ Country country = new Country();
+ country.setName("Germany");
+ List states = new ArrayList<State>();
+ State bayern = new State();
+ bayern.setName("Bayern");
+ State hessen = new State();
+ hessen.setName("Hessen");
+ State sachsen = new State();
+ sachsen.setName("Sachsen");
+ states.add(bayern);
+ states.add(hessen);
+ states.add(sachsen);
+ country.setStates(states);
+
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ s.persist(country);
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ Country germany = (Country) s.get(Country.class, country.getId());
+ assertNotNull(germany);
+ assertEquals("Wrong number of states", 3, germany.getStates().size());
+
+ // try adding a state
+ State foobar = new State();
+ foobar.setName("foobar");
+ s.save(foobar);
+ germany.getStates().add(foobar);
+ try {
+ tx.commit();
+ fail();
+ } catch (HibernateException e) {
+ assertTrue(e.getMessage().contains("changed an immutable collection instance"));
+ log.debug("success");
+ }
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ germany = (Country) s.get(Country.class, country.getId());
+ assertNotNull(germany);
+ assertEquals("Wrong number of states", 3, germany.getStates().size());
+
+ // try deleting a state
+ germany.getStates().remove(0);
+ try {
+ tx.commit();
+ fail();
+ } catch (HibernateException e) {
+ assertTrue(e.getMessage().contains("changed an immutable collection instance"));
+ log.debug("success");
+ }
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ germany = (Country) s.get(Country.class, country.getId());
+ assertNotNull(germany);
+ assertEquals("Wrong number of states", 3, germany.getStates().size());
+ tx.commit();
+ s.close();
+ }
+
+ public void testMiscplacedImmutableAnnotation() {
+ try {
+ AnnotationConfiguration config = new AnnotationConfiguration();
+ config.addAnnotatedClass(Foobar.class);
+ config.buildSessionFactory();
+ fail();
+ } catch (AnnotationException ae) {
+ log.debug("succes");
+ }
+ }
+
+ /**
+ * @see org.hibernate.test.annotations.TestCase#getMappings()
+ */
+ protected Class[] getMappings() {
+ return new Class[] { Country.class, State.class};
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/immutable/State.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/immutable/State.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/immutable/State.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,34 @@
+// $Id: State.java 14801 2008-06-24 19:03:32Z hardy.ferentschik $
+package org.hibernate.test.annotations.immutable;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * @author Hardy Ferentschik
+ */
+@Entity
+public class State {
+ @Id
+ @GeneratedValue
+ private Integer id;
+
+ private String name;
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/AddressBook.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/AddressBook.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/AddressBook.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,75 @@
+//$Id: AddressBook.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.indexcoll;
+
+import java.util.HashMap;
+import java.util.Map;
+import javax.persistence.CascadeType;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.MapKey;
+import javax.persistence.OneToMany;
+import javax.persistence.JoinTable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class AddressBook {
+ private Integer id;
+ private String owner;
+ private Map<AddressEntryPk, AddressEntry> entries = new HashMap<AddressEntryPk, AddressEntry>();
+ private Map<String, AddressEntry> lastNameEntries = new HashMap<String, AddressEntry>();
+ private Map<AlphabeticalDirectory, AddressEntry> directoryEntries = new HashMap<AlphabeticalDirectory, AddressEntry>();
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getOwner() {
+ return owner;
+ }
+
+ public void setOwner(String owner) {
+ this.owner = owner;
+ }
+
+ @MapKey
+ @OneToMany(mappedBy = "book", cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REMOVE})
+ @JoinTable(name="AddRegEntry")
+ public Map<AddressEntryPk, AddressEntry> getEntries() {
+ return entries;
+ }
+
+ public void setEntries(Map<AddressEntryPk, AddressEntry> entries) {
+ this.entries = entries;
+ }
+
+ @MapKey(name = "person.lastname")
+ @OneToMany(mappedBy = "book")
+ public Map<String, AddressEntry> getLastNameEntries() {
+ return lastNameEntries;
+ }
+
+ public void setLastNameEntries(Map<String, AddressEntry> lastNameEntries) {
+ this.lastNameEntries = lastNameEntries;
+ }
+
+ @MapKey(name = "directory")
+ @OneToMany(mappedBy = "book")
+ @JoinTable(name="Dir_Entry")
+ public Map<AlphabeticalDirectory, AddressEntry> getDirectoryEntries() {
+ return directoryEntries;
+ }
+
+ public void setDirectoryEntries(Map<AlphabeticalDirectory, AddressEntry> directoryEntries) {
+ this.directoryEntries = directoryEntries;
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/AddressEntry.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/AddressEntry.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/AddressEntry.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,76 @@
+//$Id: AddressEntry.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.indexcoll;
+
+import javax.persistence.EmbeddedId;
+import javax.persistence.Entity;
+import javax.persistence.ManyToOne;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class AddressEntry {
+ private AddressEntryPk person;
+ private String street;
+ private String city;
+ private AddressBook book;
+ private AlphabeticalDirectory directory;
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( !( o instanceof AddressEntry ) ) return false;
+
+ final AddressEntry addressEntry = (AddressEntry) o;
+
+ if ( !person.equals( addressEntry.person ) ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ return person.hashCode();
+ }
+
+ @EmbeddedId
+ public AddressEntryPk getPerson() {
+ return person;
+ }
+
+ public void setPerson(AddressEntryPk person) {
+ this.person = person;
+ }
+
+ public String getStreet() {
+ return street;
+ }
+
+ public void setStreet(String street) {
+ this.street = street;
+ }
+
+ public String getCity() {
+ return city;
+ }
+
+ public void setCity(String city) {
+ this.city = city;
+ }
+
+ @ManyToOne
+ public AddressBook getBook() {
+ return book;
+ }
+
+ public void setBook(AddressBook book) {
+ this.book = book;
+ }
+
+ @ManyToOne
+ public AlphabeticalDirectory getDirectory() {
+ return directory;
+ }
+
+ public void setDirectory(AlphabeticalDirectory directory) {
+ this.directory = directory;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/AddressEntryPk.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/AddressEntryPk.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/AddressEntryPk.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,57 @@
+//$Id: AddressEntryPk.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.indexcoll;
+
+import java.io.Serializable;
+import javax.persistence.Embeddable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Embeddable
+public class AddressEntryPk implements Serializable {
+ private String firstname;
+ private String lastname;
+
+ public AddressEntryPk() {
+ }
+
+ public AddressEntryPk(String firstname, String lastname) {
+ this.firstname = firstname;
+ this.lastname = lastname;
+ }
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( !( o instanceof AddressEntryPk ) ) return false;
+
+ final AddressEntryPk addressEntryPk = (AddressEntryPk) o;
+
+ if ( !firstname.equals( addressEntryPk.firstname ) ) return false;
+ if ( !lastname.equals( addressEntryPk.lastname ) ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ int result;
+ result = firstname.hashCode();
+ result = 29 * result + lastname.hashCode();
+ return result;
+ }
+
+ public String getFirstname() {
+ return firstname;
+ }
+
+ public void setFirstname(String firstname) {
+ this.firstname = firstname;
+ }
+
+ public String getLastname() {
+ return lastname;
+ }
+
+ public void setLastname(String lastname) {
+ this.lastname = lastname;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/AlphabeticalDirectory.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/AlphabeticalDirectory.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/AlphabeticalDirectory.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,31 @@
+//$Id: AlphabeticalDirectory.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.indexcoll;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class AlphabeticalDirectory {
+ @Id @GeneratedValue private Integer id;
+ private String name;
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Atmosphere.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Atmosphere.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Atmosphere.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,42 @@
+//$Id: Atmosphere.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.indexcoll;
+
+import java.util.HashMap;
+import java.util.Map;
+import javax.persistence.CascadeType;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.ManyToMany;
+import javax.persistence.Column;
+import javax.persistence.JoinTable;
+import javax.persistence.JoinColumn;
+
+import org.hibernate.annotations.MapKey;
+import org.hibernate.annotations.CollectionOfElements;
+import org.hibernate.annotations.MapKeyManyToMany;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Atmosphere {
+ @Id
+ @GeneratedValue
+ public Integer id;
+
+ @ManyToMany(cascade = CascadeType.ALL)
+ @MapKey(columns = {@Column(name="gas_name")})
+ public Map<String, Gas> gases = new HashMap<String, Gas>();
+
+ @ManyToMany(cascade = CascadeType.ALL)
+ @MapKeyManyToMany(joinColumns = @JoinColumn(name="gas_id") )
+ @JoinTable(name = "Gas_per_key")
+ public Map<GasKey, Gas> gasesPerKey = new HashMap<GasKey, Gas>();
+
+ @CollectionOfElements
+ @Column(name="composition_rate")
+ @MapKeyManyToMany(joinColumns = @JoinColumn(name="gas_id"))
+ @JoinTable(name = "Composition", joinColumns = @JoinColumn(name = "atmosphere_id"))
+ public Map<Gas, Double> composition = new HashMap<Gas, Double>();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Drawer.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Drawer.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Drawer.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,59 @@
+//$Id: Drawer.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.indexcoll;
+
+import java.util.List;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.OneToMany;
+
+import org.hibernate.annotations.IndexColumn;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Drawer {
+ private Long id;
+ private List<Dress> dresses;
+
+ @Id
+ @GeneratedValue
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ /**
+ * Unidirectional one to many list
+ *
+ * @return
+ */
+ @OneToMany
+ @IndexColumn(name = "from_bottom_position")
+ public List<Dress> getDresses() {
+ return dresses;
+ }
+
+ public void setDresses(List<Dress> dresses) {
+ this.dresses = dresses;
+ }
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( !( o instanceof Drawer ) ) return false;
+
+ final Drawer drawer = (Drawer) o;
+
+ if ( !getId().equals( drawer.getId() ) ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ return getId().hashCode();
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Dress.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Dress.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Dress.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,41 @@
+//$Id: Dress.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.indexcoll;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Dress {
+ private Integer id;
+
+ @Id
+ @GeneratedValue
+ @Column(name = "dress_id")
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( !( o instanceof Dress ) ) return false;
+
+ final Dress dress = (Dress) o;
+
+ if ( !getId().equals( dress.getId() ) ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ return getId().hashCode();
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Gas.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Gas.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Gas.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,18 @@
+//$Id: Gas.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.indexcoll;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Gas {
+ @Id
+ @GeneratedValue
+ public Integer id;
+ public String name;
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/GasKey.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/GasKey.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/GasKey.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,21 @@
+//$Id: GasKey.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.indexcoll;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class GasKey {
+ @Id private String name;
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Generation.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Generation.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Generation.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,27 @@
+//$Id: Generation.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.indexcoll;
+
+import javax.persistence.Embeddable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Embeddable
+public class Generation {
+
+ private String age;
+ private String culture;
+
+ public String getAge() {
+ return age;
+ }
+ public void setAge(String age) {
+ this.age = age;
+ }
+ public String getCulture() {
+ return culture;
+ }
+ public void setCulture(String culture) {
+ this.culture = culture;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/GenerationGroup.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/GenerationGroup.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/GenerationGroup.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,37 @@
+//$Id: GenerationGroup.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.indexcoll;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.GeneratedValue;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class GenerationGroup {
+
+ @Id
+ @GeneratedValue
+ private int id;
+
+ private Generation generation;
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ public Generation getGeneration() {
+ return generation;
+ }
+
+ public void setGeneration(Generation generation) {
+ this.generation = generation;
+ }
+
+
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/GenerationUser.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/GenerationUser.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/GenerationUser.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,43 @@
+//$Id: GenerationUser.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.indexcoll;
+
+import java.util.Map;
+import java.util.HashMap;
+import javax.persistence.OneToMany;
+import javax.persistence.Id;
+import javax.persistence.Entity;
+import javax.persistence.MapKey;
+import javax.persistence.GeneratedValue;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class GenerationUser {
+
+ @Id
+ @GeneratedValue
+ private int id;
+
+ @OneToMany
+ @MapKey(name="generation")
+ private Map<Generation, GenerationGroup> ref = new HashMap<Generation, GenerationGroup>();
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ public Map<Generation, GenerationGroup> getRef() {
+ return ref;
+ }
+
+ public void setRef(Map<Generation, GenerationGroup> ref) {
+ this.ref = ref;
+ }
+
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/IndexedCollectionTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/IndexedCollectionTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/IndexedCollectionTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,549 @@
+//$Id: IndexedCollectionTest.java 15025 2008-08-11 09:14:39Z hardy.ferentschik $
+package org.hibernate.test.annotations.indexcoll;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.Hibernate;
+import org.hibernate.dialect.HSQLDialect;
+import org.hibernate.test.annotations.RequiresDialect;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * Test index collections
+ *
+ * @author Emmanuel Bernard
+ */
+public class IndexedCollectionTest extends TestCase {
+ public void testFkList() throws Exception {
+ Wardrobe w = new Wardrobe();
+ Drawer d1 = new Drawer();
+ Drawer d2 = new Drawer();
+ w.setDrawers( new ArrayList<Drawer>() );
+ w.getDrawers().add( d1 );
+ w.getDrawers().add( d2 );
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ s.persist( w );
+
+ s.flush();
+ s.clear();
+
+ w = (Wardrobe) s.get( Wardrobe.class, w.getId() );
+ assertNotNull( w );
+ assertNotNull( w.getDrawers() );
+ List<Drawer> result = w.getDrawers();
+ assertEquals( 2, result.size() );
+ assertEquals( d2.getId(), result.get( 1 ).getId() );
+ result.remove( d1 );
+ s.flush();
+ d1 = (Drawer) s.merge( d1 );
+ result.add( d1 );
+
+ s.flush();
+ s.clear();
+
+ w = (Wardrobe) s.get( Wardrobe.class, w.getId() );
+ assertNotNull( w );
+ assertNotNull( w.getDrawers() );
+ result = w.getDrawers();
+ assertEquals( 2, result.size() );
+ assertEquals( d1.getId(), result.get( 1 ).getId() );
+ s.delete( result.get( 0 ) );
+ s.delete( result.get( 1 ) );
+ s.delete( w );
+ s.flush();
+ tx.rollback();
+ s.close();
+ }
+
+ public void testJoinedTableList() throws Exception {
+ Wardrobe w = new Wardrobe();
+ w.setDrawers( new ArrayList<Drawer>() );
+ Drawer d = new Drawer();
+ w.getDrawers().add( d );
+ Dress d1 = new Dress();
+ Dress d2 = new Dress();
+ d.setDresses( new ArrayList<Dress>() );
+ d.getDresses().add( d1 );
+ d.getDresses().add( d2 );
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ s.persist( d1 );
+ s.persist( d2 );
+ s.persist( w );
+
+ s.flush();
+ s.clear();
+
+ d = (Drawer) s.get( Drawer.class, d.getId() );
+ assertNotNull( d );
+ assertNotNull( d.getDresses() );
+ List<Dress> result = d.getDresses();
+ assertEquals( 2, result.size() );
+ assertEquals( d2.getId(), result.get( 1 ).getId() );
+ result.remove( d1 );
+ s.flush();
+ d1 = (Dress) s.merge( d1 );
+ result.add( d1 );
+
+ s.flush();
+ s.clear();
+
+ d = (Drawer) s.get( Drawer.class, d.getId() );
+ assertNotNull( d );
+ assertNotNull( d.getDresses() );
+ result = d.getDresses();
+ assertEquals( 2, result.size() );
+ assertEquals( d1.getId(), result.get( 1 ).getId() );
+ s.delete( result.get( 0 ) );
+ s.delete( result.get( 1 ) );
+ s.delete( d );
+ s.flush();
+ tx.rollback();
+ s.close();
+ }
+
+ public void testMapKey() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Software hibernate = new Software();
+ hibernate.setName( "Hibernate" );
+ Version v1 = new Version();
+ v1.setCodeName( "HumbaHumba" );
+ v1.setNumber( "1.0" );
+ v1.setSoftware( hibernate );
+ Version v2 = new Version();
+ v2.setCodeName( "Copacabana" );
+ v2.setNumber( "2.0" );
+ v2.setSoftware( hibernate );
+ Version v4 = new Version();
+ v4.setCodeName( "Dreamland" );
+ v4.setNumber( "4.0" );
+ v4.setSoftware( hibernate );
+ Map<String, Version> link = new HashMap<String, Version>();
+ link.put( v1.getCodeName(), v1 );
+ link.put( v2.getCodeName(), v2 );
+ link.put( v4.getCodeName(), v4 );
+ hibernate.setVersions( link );
+ s.persist( hibernate );
+ s.persist( v1 );
+ s.persist( v2 );
+ s.persist( v4 );
+
+ s.flush();
+ s.clear();
+
+ hibernate = (Software) s.get( Software.class, "Hibernate" );
+ assertEquals( 3, hibernate.getVersions().size() );
+ assertEquals( "1.0", hibernate.getVersions().get( "HumbaHumba" ).getNumber() );
+ assertEquals( "2.0", hibernate.getVersions().get( "Copacabana" ).getNumber() );
+ hibernate.getVersions().remove( v4.getCodeName() );
+
+ s.flush();
+ s.clear();
+
+ hibernate = (Software) s.get( Software.class, "Hibernate" );
+ assertEquals( "So effect on collection changes", 3, hibernate.getVersions().size() );
+ for ( Version v : hibernate.getVersions().values() ) {
+ s.delete( v );
+ }
+ s.delete( hibernate );
+
+ s.flush();
+
+ tx.rollback();
+ s.close();
+ }
+
+ public void testDefaultMapKey() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ AddressBook book = new AddressBook();
+ book.setOwner( "Emmanuel" );
+ AddressEntryPk helene = new AddressEntryPk( "Helene", "Michau" );
+ AddressEntry heleneEntry = new AddressEntry();
+ heleneEntry.setBook( book );
+ heleneEntry.setCity( "Levallois" );
+ heleneEntry.setStreet( "Louis Blanc" );
+ heleneEntry.setPerson( helene );
+ AddressEntryPk primeMinister = new AddressEntryPk( "Dominique", "Villepin" );
+ AddressEntry primeMinisterEntry = new AddressEntry();
+ primeMinisterEntry.setBook( book );
+ primeMinisterEntry.setCity( "Paris" );
+ primeMinisterEntry.setStreet( "Hotel Matignon" );
+ primeMinisterEntry.setPerson( primeMinister );
+ book.getEntries().put( helene, heleneEntry );
+ book.getEntries().put( primeMinister, primeMinisterEntry );
+ s.persist( book );
+
+ s.flush();
+ s.clear();
+
+ book = (AddressBook) s.get( AddressBook.class, book.getId() );
+ assertEquals( 2, book.getEntries().size() );
+ assertEquals( heleneEntry.getCity(), book.getEntries().get( helene ).getCity() );
+ AddressEntryPk fake = new AddressEntryPk( "Fake", "Fake" );
+ book.getEntries().put( fake, primeMinisterEntry );
+
+ s.flush();
+ s.clear();
+
+ book = (AddressBook) s.get( AddressBook.class, book.getId() );
+ assertEquals( 2, book.getEntries().size() );
+ assertNull( book.getEntries().get( fake ) );
+ s.delete( book );
+
+ s.flush();
+ tx.rollback();
+ s.close();
+ }
+
+ public void testMapKeyToEntity() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ AlphabeticalDirectory m = new AlphabeticalDirectory();
+ m.setName( "M" );
+ AlphabeticalDirectory v = new AlphabeticalDirectory();
+ v.setName( "V" );
+ s.persist( m );
+ s.persist( v );
+
+ AddressBook book = new AddressBook();
+ book.setOwner( "Emmanuel" );
+ AddressEntryPk helene = new AddressEntryPk( "Helene", "Michau" );
+ AddressEntry heleneEntry = new AddressEntry();
+ heleneEntry.setBook( book );
+ heleneEntry.setCity( "Levallois" );
+ heleneEntry.setStreet( "Louis Blanc" );
+ heleneEntry.setPerson( helene );
+ heleneEntry.setDirectory( m );
+ AddressEntryPk primeMinister = new AddressEntryPk( "Dominique", "Villepin" );
+ AddressEntry primeMinisterEntry = new AddressEntry();
+ primeMinisterEntry.setBook( book );
+ primeMinisterEntry.setCity( "Paris" );
+ primeMinisterEntry.setStreet( "Hotel Matignon" );
+ primeMinisterEntry.setPerson( primeMinister );
+ primeMinisterEntry.setDirectory( v );
+ book.getEntries().put( helene, heleneEntry );
+ book.getEntries().put( primeMinister, primeMinisterEntry );
+ s.persist( book );
+
+ s.flush();
+ s.clear();
+
+ book = (AddressBook) s.get( AddressBook.class, book.getId() );
+ assertEquals( 2, book.getEntries().size() );
+ assertEquals( heleneEntry.getCity(), book.getEntries().get( helene ).getCity() );
+ assertEquals( "M", book.getEntries().get( helene ).getDirectory().getName() );
+
+ s.delete( book );
+ tx.rollback();
+ s.close();
+ }
+
+ @RequiresDialect(HSQLDialect.class)
+ public void testComponentSubPropertyMapKey() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ AddressBook book = new AddressBook();
+ book.setOwner( "Emmanuel" );
+ AddressEntryPk helene = new AddressEntryPk( "Helene", "Michau" );
+ AddressEntry heleneEntry = new AddressEntry();
+ heleneEntry.setBook( book );
+ heleneEntry.setCity( "Levallois" );
+ heleneEntry.setStreet( "Louis Blanc" );
+ heleneEntry.setPerson( helene );
+ AddressEntryPk primeMinister = new AddressEntryPk( "Dominique", "Villepin" );
+ AddressEntry primeMinisterEntry = new AddressEntry();
+ primeMinisterEntry.setBook( book );
+ primeMinisterEntry.setCity( "Paris" );
+ primeMinisterEntry.setStreet( "Hotel Matignon" );
+ primeMinisterEntry.setPerson( primeMinister );
+ book.getEntries().put( helene, heleneEntry );
+ book.getEntries().put( primeMinister, primeMinisterEntry );
+ s.persist( book );
+
+ s.flush();
+ s.clear();
+
+ book = (AddressBook) s.get( AddressBook.class, book.getId() );
+ assertEquals( 2, book.getLastNameEntries().size() );
+ assertEquals( heleneEntry.getCity(), book.getLastNameEntries().get( "Michau" ).getCity() );
+ AddressEntryPk fake = new AddressEntryPk( "Fake", "Fake" );
+ book.getEntries().put( fake, primeMinisterEntry );
+
+ s.flush();
+ s.clear();
+
+ book = (AddressBook) s.get( AddressBook.class, book.getId() );
+ assertEquals( 2, book.getEntries().size() );
+ assertNull( book.getEntries().get( fake ) );
+ s.delete( book );
+ tx.rollback();
+ s.close();
+ }
+
+ public void testMapKeyOnManyToMany() throws Exception {
+ Session s;
+ s = openSession();
+ s.getTransaction().begin();
+ News airplane = new News();
+ airplane.setTitle( "Crash!" );
+ airplane.setDetail( "An airplaned crashed." );
+ s.persist( airplane );
+ Newspaper lemonde = new Newspaper();
+ lemonde.setName( "Lemonde" );
+ lemonde.getNews().put( airplane.getTitle(), airplane );
+ s.persist( lemonde );
+
+ s.flush();
+ s.clear();
+
+ lemonde = (Newspaper) s.get( Newspaper.class, lemonde.getId() );
+ assertEquals( 1, lemonde.getNews().size() );
+ News news = lemonde.getNews().get( airplane.getTitle() );
+ assertNotNull( news );
+ assertEquals( airplane.getTitle(), news.getTitle() );
+ s.delete( lemonde );
+ s.delete( news );
+
+ s.getTransaction().rollback();
+ s.close();
+ }
+
+ public void testMapKeyOnManyToManyOnId() throws Exception {
+ Session s;
+ s = openSession();
+ s.getTransaction().begin();
+ News hibernate1 = new News();
+ hibernate1.setTitle( "#1 ORM solution in the Java world" );
+ hibernate1.setDetail( "Well, that's no news ;-)" );
+ s.persist( hibernate1 );
+ PressReleaseAgency schwartz = new PressReleaseAgency();
+ schwartz.setName( "Schwartz" );
+ schwartz.getProvidedNews().put( hibernate1.getId(), hibernate1 );
+ s.persist( schwartz );
+
+ s.flush();
+ s.clear();
+
+ schwartz = (PressReleaseAgency) s.get( PressReleaseAgency.class, schwartz.getId() );
+ assertEquals( 1, schwartz.getProvidedNews().size() );
+ News news = schwartz.getProvidedNews().get( hibernate1.getId() );
+ assertNotNull( news );
+ assertEquals( hibernate1.getTitle(), news.getTitle() );
+ s.delete( schwartz );
+ s.delete( news );
+
+ s.getTransaction().rollback();
+ s.close();
+ }
+
+ public void testMapKeyAndIdClass() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Painter picasso = new Painter();
+ Painting laVie = new Painting( "La Vie", "Picasso", 50, 20 );
+ picasso.getPaintings().put( "La Vie", laVie );
+ Painting famille = new Painting( "La Famille du Saltimbanque", "Picasso", 50, 20 );
+ picasso.getPaintings().put( "La Famille du Saltimbanque", famille );
+ s.persist( picasso );
+
+ s.flush();
+ s.clear();
+
+ picasso = (Painter) s.get( Painter.class, picasso.getId() );
+ Painting painting = picasso.getPaintings().get( famille.getName() );
+ assertNotNull( painting );
+ assertEquals( painting.getName(), famille.getName() );
+ s.delete( picasso );
+ tx.rollback();
+ s.close();
+ }
+
+ public void testRealMap() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Atmosphere atm = new Atmosphere();
+ Atmosphere atm2 = new Atmosphere();
+ GasKey key = new GasKey();
+ key.setName( "O2" );
+ Gas o2 = new Gas();
+ o2.name = "oxygen";
+ atm.gases.put( "100%", o2 );
+ atm.gasesPerKey.put( key, o2 );
+ atm2.gases.put( "100%", o2 );
+ atm2.gasesPerKey.put( key, o2 );
+ s.persist( key );
+ s.persist( atm );
+ s.persist( atm2 );
+
+ s.flush();
+ s.clear();
+
+ atm = (Atmosphere) s.get( Atmosphere.class, atm.id );
+ key = (GasKey) s.get( GasKey.class, key.getName() );
+ assertEquals( 1, atm.gases.size() );
+ assertEquals( o2.name, atm.gases.get( "100%" ).name );
+ assertEquals( o2.name, atm.gasesPerKey.get( key ).name );
+ tx.rollback();
+ s.close();
+ }
+
+ public void testMapKeyEntityEntity() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ AddressBook book = new AddressBook();
+ s.persist( book );
+ AddressEntry entry = new AddressEntry();
+ entry.setCity( "Atlanta");
+ AddressEntryPk pk = new AddressEntryPk("Coca", "Cola" );
+ entry.setPerson( pk );
+ entry.setBook( book );
+ AlphabeticalDirectory ad = new AlphabeticalDirectory();
+ ad.setName( "C");
+ s.persist( ad );
+ entry.setDirectory( ad );
+ s.persist( entry );
+ book.getDirectoryEntries().put( ad, entry );
+
+ s.flush();
+ s.clear();
+
+ book = (AddressBook) s.get( AddressBook.class, book.getId() );
+ assertEquals( 1, book.getDirectoryEntries().size() );
+ assertEquals( "C", book.getDirectoryEntries().keySet().iterator().next().getName() );
+ tx.rollback();
+ s.close();
+ }
+
+ public void testEntityKeyElementTarget() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Atmosphere atm = new Atmosphere();
+ Gas o2 = new Gas();
+ o2.name = "oxygen";
+ atm.composition.put( o2, 94.3 );
+ s.persist( o2 );
+ s.persist( atm );
+
+ s.flush();
+ s.clear();
+
+ atm = (Atmosphere) s.get( Atmosphere.class, atm.id );
+ assertTrue( ! Hibernate.isInitialized( atm.composition ) );
+ assertEquals( 1, atm.composition.size() );
+ assertEquals( o2.name, atm.composition.keySet().iterator().next().name );
+ tx.rollback();
+ s.close();
+ }
+
+ public void testSortedMap() {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Training training = new Training();
+ Trainee trainee = new Trainee();
+ trainee.setName( "Jim" );
+ Trainee trainee2 = new Trainee();
+ trainee2.setName( "Emmanuel" );
+ s.persist( trainee );
+ s.persist( trainee2 );
+ training.getTrainees().put( "Jim", trainee );
+ training.getTrainees().put( "Emmanuel", trainee2 );
+ s.persist( training );
+
+ s.flush();
+ s.clear();
+
+ training = (Training) s.get( Training.class, training.getId() );
+ assertEquals( "Emmanuel", training.getTrainees().firstKey() );
+ assertEquals( "Jim", training.getTrainees().lastKey() );
+ tx.rollback();
+ s.close();
+ }
+
+ public void testMapKeyLoad() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Software hibernate = new Software();
+ hibernate.setName( "Hibernate" );
+ Version v1 = new Version();
+ v1.setCodeName( "HumbaHumba" );
+ v1.setNumber( "1.0" );
+ v1.setSoftware( hibernate );
+ hibernate.addVersion( v1 );
+ s.persist( hibernate );
+ s.persist( v1 );
+
+ s.flush();
+ s.clear();
+
+ hibernate = (Software) s.get( Software.class, "Hibernate" );
+ assertEquals(1, hibernate.getVersions().size() );
+ Version v2 = new Version();
+ v2.setCodeName( "HumbaHumba2" );
+ v2.setNumber( "2.0" );
+ v2.setSoftware( hibernate );
+ hibernate.addVersion( v2 );
+ assertEquals( "One loaded persisted version, and one just added", 2, hibernate.getVersions().size() );
+
+ s.flush();
+ s.clear();
+
+ hibernate = (Software) s.get( Software.class, "Hibernate" );
+ for ( Version v : hibernate.getVersions().values() ) {
+ s.delete( v );
+ }
+ s.delete( hibernate );
+ tx.rollback();
+ s.close();
+ }
+
+
+ public IndexedCollectionTest(String x) {
+ super( x );
+ }
+
+ protected Class[] getMappings() {
+ return new Class[]{
+ Wardrobe.class,
+ Drawer.class,
+ Dress.class,
+ Software.class,
+ Version.class,
+ AddressBook.class,
+ AddressEntry.class,
+ AddressEntryPk.class, //should be silently ignored
+ Newspaper.class,
+ News.class,
+ PressReleaseAgency.class,
+ Painter.class,
+ Painting.class,
+ Atmosphere.class,
+ Gas.class,
+ AlphabeticalDirectory.class,
+ GasKey.class,
+ Trainee.class,
+ Training.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/MapKeyTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/MapKeyTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/MapKeyTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,40 @@
+//$Id: MapKeyTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.indexcoll;
+
+import org.hibernate.test.annotations.TestCase;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class MapKeyTest extends TestCase {
+
+ public void testMapKeyOnEmbeddedId() {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Generation c = new Generation();
+ c.setAge( "a" );
+ c.setCulture( "b" );
+ GenerationGroup r = new GenerationGroup();
+ r.setGeneration( c );
+ s.persist( r );
+ GenerationUser m = new GenerationUser();
+ s.persist( m );
+ m.getRef().put( c, r );
+ s.flush();
+ s.clear();
+
+ m = (GenerationUser) s.get( GenerationUser.class, m.getId() );
+ assertEquals( "a", m.getRef().keySet().iterator().next().getAge() );
+ tx.rollback();
+ s.close();
+ }
+
+ protected Class[] getMappings() {
+ return new Class[] {
+ GenerationUser.class,
+ GenerationGroup.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/News.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/News.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/News.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,44 @@
+//$Id: News.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.indexcoll;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class News {
+ private Integer id;
+ private String title;
+ private String detail;
+
+ @Id
+ @GeneratedValue
+ @Column(name = "news_id")
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ public String getDetail() {
+ return detail;
+ }
+
+ public void setDetail(String detail) {
+ this.detail = detail;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Newspaper.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Newspaper.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Newspaper.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,48 @@
+//$Id: Newspaper.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.indexcoll;
+
+import java.util.HashMap;
+import java.util.Map;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.ManyToMany;
+import javax.persistence.MapKey;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Newspaper {
+ private Integer id;
+ private String name;
+ private Map<String, News> news = new HashMap<String, News>();
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @ManyToMany
+ @MapKey(name = "title")
+ public Map<String, News> getNews() {
+ return news;
+ }
+
+ public void setNews(Map<String, News> news) {
+ this.news = news;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Painter.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Painter.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Painter.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,42 @@
+//$Id: Painter.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.indexcoll;
+
+import java.util.HashMap;
+import java.util.Map;
+import javax.persistence.CascadeType;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.MapKey;
+import javax.persistence.OneToMany;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Painter {
+ private Integer id;
+ private Map<String, Painting> paintings = new HashMap<String, Painting>();
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ @OneToMany(cascade = {CascadeType.ALL})
+ @MapKey(name = "name")
+ @JoinColumn
+ public Map<String, Painting> getPaintings() {
+ return paintings;
+ }
+
+ public void setPaintings(Map<String, Painting> paintings) {
+ this.paintings = paintings;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Painting.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Painting.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Painting.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,82 @@
+//$Id: Painting.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.indexcoll;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.IdClass;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+(a)IdClass(PaintingPk.class)
+public class Painting {
+
+ private int sizeX;
+ private int sizeY;
+ private String name;
+ private String painter;
+
+ public Painting() {
+ }
+
+ public Painting(String name, String painter, int sizeX, int sizeY) {
+ this.name = name;
+ this.painter = painter;
+ this.sizeX = sizeX;
+ this.sizeY = sizeY;
+ }
+
+ @Id
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @Id
+ public String getPainter() {
+ return painter;
+ }
+
+ public void setPainter(String painter) {
+ this.painter = painter;
+ }
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( o == null || getClass() != o.getClass() ) return false;
+
+ final PaintingPk that = (PaintingPk) o;
+
+ if ( !name.equals( that.getName() ) ) return false;
+ if ( !painter.equals( that.getPainter() ) ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ int result;
+ result = name.hashCode();
+ result = 29 * result + painter.hashCode();
+ return result;
+ }
+
+ public int getSizeX() {
+ return sizeX;
+ }
+
+ public void setSizeX(int sizeX) {
+ this.sizeX = sizeX;
+ }
+
+ public int getSizeY() {
+ return sizeY;
+ }
+
+ public void setSizeY(int sizeY) {
+ this.sizeY = sizeY;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/PaintingPk.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/PaintingPk.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/PaintingPk.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,49 @@
+//$Id: PaintingPk.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.indexcoll;
+
+import java.io.Serializable;
+import javax.persistence.Embeddable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Embeddable
+public class PaintingPk implements Serializable {
+ private String name;
+ private String painter;
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getPainter() {
+ return painter;
+ }
+
+ public void setPainter(String painter) {
+ this.painter = painter;
+ }
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( o == null || getClass() != o.getClass() ) return false;
+
+ final PaintingPk that = (PaintingPk) o;
+
+ if ( !name.equals( that.name ) ) return false;
+ if ( !painter.equals( that.painter ) ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ int result;
+ result = name.hashCode();
+ result = 29 * result + painter.hashCode();
+ return result;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/PressReleaseAgency.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/PressReleaseAgency.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/PressReleaseAgency.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,54 @@
+//$Id: PressReleaseAgency.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.indexcoll;
+
+import java.util.HashMap;
+import java.util.Map;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinTable;
+import javax.persistence.ManyToMany;
+import javax.persistence.MapKey;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class PressReleaseAgency {
+ private Integer id;
+ private String name;
+ private Map<Integer, News> providedNews = new HashMap<Integer, News>();
+
+ @Id
+ @GeneratedValue
+ @Column(name = "PressReleaseAgency_id")
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @ManyToMany
+ @JoinTable(joinColumns = @JoinColumn(name = "PressReleaseAgency_id"),
+ inverseJoinColumns = @JoinColumn(name = "News_id"))
+ @MapKey
+ public Map<Integer, News> getProvidedNews() {
+ return providedNews;
+ }
+
+ public void setProvidedNews(Map<Integer, News> providedNews) {
+ this.providedNews = providedNews;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Software.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Software.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Software.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,41 @@
+//$Id: Software.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.indexcoll;
+
+import java.util.Map;
+import java.util.HashMap;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.MapKey;
+import javax.persistence.OneToMany;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Software {
+ private String name;
+ private Map<String, Version> versions = new HashMap<String, Version>();
+
+ @Id
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @OneToMany(mappedBy = "software")
+ @MapKey(name = "codeName")
+ public Map<String, Version> getVersions() {
+ return versions;
+ }
+
+ public void setVersions(Map<String, Version> versions) {
+ this.versions = versions;
+ }
+
+ public void addVersion(Version version) {
+ this.versions.put(version.getCodeName(), version);
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Trainee.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Trainee.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Trainee.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,31 @@
+//$Id: Trainee.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.indexcoll;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.GeneratedValue;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Trainee {
+ @Id @GeneratedValue private Long id;
+ private String 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;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Training.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Training.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Training.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,39 @@
+//$Id: Training.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.indexcoll;
+
+import java.util.SortedMap;
+import java.util.TreeMap;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.MapKey;
+import javax.persistence.ManyToMany;
+
+import org.hibernate.annotations.Sort;
+import org.hibernate.annotations.SortType;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Training {
+ @Id @GeneratedValue private Long id;
+ @Sort(type= SortType.NATURAL)
+ @MapKey(name="name") @ManyToMany SortedMap<String, Trainee> trainees = new TreeMap<String, Trainee>();
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public SortedMap<String, Trainee> getTrainees() {
+ return trainees;
+ }
+
+ public void setTrainees(SortedMap<String, Trainee> trainees) {
+ this.trainees = trainees;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Version.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Version.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Version.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,58 @@
+//$Id: Version.java 15049 2008-08-13 15:32:32Z epbernard $
+package org.hibernate.test.annotations.indexcoll;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.ManyToOne;
+import javax.persistence.Table;
+import javax.persistence.Column;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Table(name = "tbl_version")
+public class Version {
+ private Integer id;
+ private String codeName;
+ private String number;
+ private Software software;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ @Column(name="`code_name`")
+ public String getCodeName() {
+ return codeName;
+ }
+
+ public void setCodeName(String codeName) {
+ this.codeName = codeName;
+ }
+
+ @Column(name="version_nbr")
+ public String getNumber() {
+ return number;
+ }
+
+ public void setNumber(String number) {
+ this.number = number;
+ }
+
+ @ManyToOne
+ public Software getSoftware() {
+ return software;
+ }
+
+ public void setSoftware(Software software) {
+ this.software = software;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Wardrobe.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Wardrobe.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/indexcoll/Wardrobe.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,47 @@
+//$Id: Wardrobe.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.indexcoll;
+
+import java.util.List;
+import javax.persistence.CascadeType;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.OneToMany;
+
+import org.hibernate.annotations.IndexColumn;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Wardrobe {
+
+ private Long id;
+ private List<Drawer> drawers;
+
+ @Id
+ @GeneratedValue
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ /**
+ * unidirectional one to many list with non null foreign key (mapping
+ * not recommended).
+ */
+ @OneToMany(cascade = CascadeType.ALL)
+ @IndexColumn(name = "drawer_position", base = 1)
+ @JoinColumn(name = "wardrobe_id", nullable = false)
+ public List<Drawer> getDrawers() {
+ return drawers;
+ }
+
+ public void setDrawers(List<Drawer> drawers) {
+ this.drawers = drawers;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/Apple.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/Apple.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/Apple.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,11 @@
+//$Id: Apple.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.inheritance;
+
+import javax.persistence.Entity;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Apple extends Fruit {
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/Carrot.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/Carrot.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/Carrot.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,33 @@
+//$Id: Carrot.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.inheritance;
+
+import javax.persistence.Entity;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+import javax.persistence.PrimaryKeyJoinColumn;
+import javax.persistence.PrimaryKeyJoinColumns;
+
+import org.hibernate.annotations.OnDelete;
+import org.hibernate.annotations.OnDeleteAction;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Inheritance(strategy = InheritanceType.JOINED)
+@PrimaryKeyJoinColumns(
+ {@PrimaryKeyJoinColumn(name = "carrot_farmer", referencedColumnName = "farmer"),
+ @PrimaryKeyJoinColumn(name = "harvest", referencedColumnName = "harvestDate")
+ })
+@OnDelete(action = OnDeleteAction.CASCADE)
+public class Carrot extends Vegetable {
+ private int length;
+
+ public int getLength() {
+ return length;
+ }
+
+ public void setLength(int length) {
+ this.length = length;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/Fruit.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/Fruit.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/Fruit.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,25 @@
+//$Id: Fruit.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.inheritance;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Fruit {
+ private Integer id;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/SubclassTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/SubclassTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/SubclassTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,170 @@
+//$Id: SubclassTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.inheritance;
+
+import java.util.List;
+
+import org.hibernate.Query;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.annotations.A320;
+import org.hibernate.test.annotations.A320b;
+import org.hibernate.test.annotations.Plane;
+import org.hibernate.test.annotations.TestCase;
+import org.hibernate.test.annotations.inheritance.singletable.Funk;
+import org.hibernate.test.annotations.inheritance.singletable.Music;
+import org.hibernate.test.annotations.inheritance.singletable.Noise;
+import org.hibernate.test.annotations.inheritance.singletable.Rock;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class SubclassTest extends TestCase {
+
+ public SubclassTest(String x) {
+ super( x );
+ }
+
+ public void testPolymorphism() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Plane p = new Plane();
+ p.setNbrOfSeats( 10 );
+ A320 a = new A320();
+ a.setJavaEmbeddedVersion( "5.0" );
+ a.setNbrOfSeats( 300 );
+ s.persist( a );
+ s.persist( p );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ Query q = s.createQuery( "from " + A320.class.getName() );
+ List a320s = q.list();
+ assertNotNull( a320s );
+ assertEquals( 1, a320s.size() );
+ assertTrue( a320s.get( 0 ) instanceof A320 );
+ assertEquals( "5.0", ( (A320) a320s.get( 0 ) ).getJavaEmbeddedVersion() );
+ q = s.createQuery( "from " + Plane.class.getName() );
+ List planes = q.list();
+ assertNotNull( planes );
+ assertEquals( 2, planes.size() );
+ tx.commit();
+ s.close();
+ }
+
+ public void test2ndLevelSubClass() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ A320b a = new A320b();
+ a.setJavaEmbeddedVersion( "Elephant" );
+ a.setNbrOfSeats( 300 );
+ s.persist( a );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ Query q = s.createQuery( "from " + A320.class.getName() + " as a where a.javaEmbeddedVersion = :version" );
+ q.setString( "version", "Elephant" );
+ List a320s = q.list();
+ assertNotNull( a320s );
+ assertEquals( 1, a320s.size() );
+ tx.commit();
+ s.close();
+ }
+
+ public void testEmbeddedSuperclass() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Plane p = new Plane();
+ p.setAlive( true ); //sic
+ p.setAltitude( 10000 );
+ p.setMetricAltitude( 3000 );
+ p.setNbrOfSeats( 150 );
+ p.setSerial( "0123456789" );
+ s.persist( p );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ p = (Plane) s.get( Plane.class, p.getId() );
+ assertNotNull( p );
+ assertEquals( true, p.isAlive() );
+ assertEquals( 150, p.getNbrOfSeats() );
+ assertEquals( 10000, p.getAltitude() );
+ assertEquals( "0123456789", p.getSerial() );
+ assertFalse( 3000 == p.getMetricAltitude() );
+ s.delete( p );
+ tx.commit();
+ s.close();
+ }
+
+ public void testFormula() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Rock guns = new Rock();
+ guns.setAvgBeat( 90 );
+ guns.setType( 2 );
+ Noise white = new Noise();
+ white.setAvgBeat( 0 );
+ white.setType( null );
+
+ s.persist( guns );
+ s.persist( white );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ List result = s.createCriteria( Noise.class ).list();
+ assertNotNull( result );
+ assertEquals( 1, result.size() );
+ white = (Noise) result.get( 0 );
+ assertNull( white.getType() );
+ s.delete( white );
+ result = s.createCriteria( Rock.class ).list();
+ assertEquals( 1, result.size() );
+ s.delete( result.get( 0 ) );
+ result = s.createCriteria( Funk.class ).list();
+ assertEquals( 0, result.size() );
+
+ tx.commit();
+ s.close();
+ }
+
+ private void checkClassType(Fruit fruitToTest, Fruit f, Apple a) {
+ if ( fruitToTest.getId().equals( f.getId() ) ) {
+ assertFalse( fruitToTest instanceof Apple );
+ }
+ else if ( fruitToTest.getId().equals( a.getId() ) ) {
+ assertTrue( fruitToTest instanceof Apple );
+ }
+ else {
+ fail( "Result does not contains the previously inserted elements" );
+ }
+ }
+
+ /**
+ * @see org.hibernate.test.annotations.TestCase#getMappings()
+ */
+ protected Class[] getMappings() {
+ return new Class[]{
+ A320b.class, //subclasses should be properly reordered
+ Plane.class,
+ A320.class,
+ Fruit.class,
+ //FlyingObject.class, //had to declare embedded superclasses
+ //Thing.class,
+ Apple.class,
+ Music.class,
+ Rock.class,
+ Funk.class,
+ Noise.class
+ };
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/Tomato.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/Tomato.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/Tomato.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,33 @@
+//$Id: Tomato.java 15056 2008-08-13 18:15:05Z epbernard $
+package org.hibernate.test.annotations.inheritance;
+
+import javax.persistence.Entity;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+import javax.persistence.Column;
+
+import org.hibernate.annotations.OnDelete;
+import org.hibernate.annotations.OnDeleteAction;
+
+/**
+ * @author Emmanuel Bernard
+ */
+//FIXME HBX-55 default for composite PK does not work yet
+//FIXME Tomato is a fruit
+@Entity()
+@Inheritance(
+ strategy = InheritanceType.JOINED
+)
+@OnDelete(action = OnDeleteAction.CASCADE)
+public class Tomato extends Vegetable {
+ private int size;
+
+ @Column(name="tom_size")
+ public int getSize() {
+ return size;
+ }
+
+ public void setSize(int size) {
+ this.size = size;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/Vegetable.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/Vegetable.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/Vegetable.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,51 @@
+//$Id: Vegetable.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.inheritance;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity()
+@Inheritance(
+ strategy = InheritanceType.JOINED
+)
+public class Vegetable {
+ private VegetablePk id;
+ private long priceInCent;
+
+ @Id
+ public VegetablePk getId() {
+ return id;
+ }
+
+ public void setId(VegetablePk id) {
+ this.id = id;
+ }
+
+ public long getPriceInCent() {
+ return priceInCent;
+ }
+
+ public void setPriceInCent(long priceInCent) {
+ this.priceInCent = priceInCent;
+ }
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( !( o instanceof Vegetable ) ) return false;
+
+ final Vegetable vegetable = (Vegetable) o;
+
+ if ( !id.equals( vegetable.id ) ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ return id.hashCode();
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/VegetablePk.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/VegetablePk.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/VegetablePk.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,50 @@
+//$Id: VegetablePk.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.inheritance;
+
+import java.io.Serializable;
+import javax.persistence.Embeddable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Embeddable
+public class VegetablePk implements Serializable {
+ private String farmer;
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( !( o instanceof VegetablePk ) ) return false;
+
+ final VegetablePk vegetablePk = (VegetablePk) o;
+
+ if ( !farmer.equals( vegetablePk.farmer ) ) return false;
+ if ( !harvestDate.equals( vegetablePk.harvestDate ) ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ int result;
+ result = farmer.hashCode();
+ result = 29 * result + harvestDate.hashCode();
+ return result;
+ }
+
+ public String getFarmer() {
+ return farmer;
+ }
+
+ public void setFarmer(String farmer) {
+ this.farmer = farmer;
+ }
+
+ public String getHarvestDate() {
+ return harvestDate;
+ }
+
+ public void setHarvestDate(String harvestDate) {
+ this.harvestDate = harvestDate;
+ }
+
+ private String harvestDate;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Alarm.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Alarm.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Alarm.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,40 @@
+//$Id: Alarm.java 15074 2008-08-14 17:38:00Z epbernard $
+package org.hibernate.test.annotations.inheritance.joined;
+
+import javax.persistence.DiscriminatorValue;
+import javax.persistence.Entity;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinColumns;
+import javax.persistence.OneToOne;
+
+@Entity
+@DiscriminatorValue("AlarmT")
+public class Alarm extends EventInformation {
+
+ protected EventInformation eventInfo;
+
+ @OneToOne
+ @JoinColumns({@JoinColumn(name = "EVENTINFO_NOTIFICATIONID",
+ referencedColumnName = "NOTIFICATIONID")})
+ public EventInformation getEventInfo() {
+ return eventInfo;
+ }
+
+ public void setEventInfo(EventInformation value) {
+ this.eventInfo = value;
+ }
+
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ String eventId = ( getEventInfo() != null ?
+ getEventInfo().getNotificationId() : null );
+ sb.append(
+ "AlarmT: id = " + getNotificationId() + "\t" +
+ "has event id = " + eventId
+ );
+ return sb.toString();
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Asset.hbm.xml
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Asset.hbm.xml (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Asset.hbm.xml 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,36 @@
+<?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.annotations.inheritance.joined">
+
+ <class name="Parent">
+ <id name="id">
+ <generator class="native"/>
+ </id>
+ <set name="financialAssets" fetch="join" cascade="refresh" inverse="true">
+ <key column="PARENT_ID"/>
+ <one-to-many class="FinancialAsset"/>
+ </set>
+ <set name="propertyAssets" fetch="join" cascade="refresh" inverse="true">
+ <key column="PARENT_ID"/>
+ <one-to-many class="PropertyAsset"/>
+ </set>
+ </class>
+ <class name="Asset">
+ <id name="id">
+ <generator class="native"/>
+ </id>
+ <many-to-one name="parent" column="PARENT_ID" property-ref="parent"/>
+ <joined-subclass name="FinancialAsset">
+ <key column="ID"/>
+ <property name="price"/>
+ </joined-subclass>
+ <joined-subclass name="PropertyAsset">
+ <key column="ID"/>
+ <property name="price"/>
+ </joined-subclass>
+ </class>
+
+</hibernate-mapping>
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Asset.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Asset.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Asset.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,41 @@
+//$Id: Asset.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.inheritance.joined;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+import javax.persistence.Table;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Inheritance(strategy = InheritanceType.JOINED)
+@Table(name = "TBLASSET")
+public class Asset {
+ private Integer id;
+
+ private Parent parent = null;
+
+ @Id @GeneratedValue public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ @ManyToOne(targetEntity = Parent.class)
+ @JoinColumn(name = "PARENTID")
+ public Parent getParent() {
+ return parent;
+ }
+
+ public void setParent(Parent parent) {
+ this.parent = parent;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Clothing.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Clothing.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Clothing.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,48 @@
+//$Id: Clothing.java 15075 2008-08-14 17:43:43Z epbernard $
+package org.hibernate.test.annotations.inheritance.joined;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+import javax.persistence.Column;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Inheritance(strategy = InheritanceType.JOINED)
+public abstract class Clothing {
+ private long id;
+ private int size;
+ private String color;
+
+ @Id
+ @GeneratedValue
+ public long getId() {
+ return id;
+ }
+
+ public void setId(long id) {
+ this.id = id;
+ }
+
+ @Column(name = "cloth_size")
+ public int getSize() {
+ return size;
+ }
+
+ public void setSize(int size) {
+ this.size = size;
+ }
+
+ public String getColor() {
+ return color;
+ }
+
+ public void setColor(String color) {
+ this.color = color;
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Document.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Document.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Document.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,33 @@
+//$Id: Document.java 16296 2009-04-10 20:21:48Z gbadner $
+package org.hibernate.test.annotations.inheritance.joined;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+
+import org.hibernate.annotations.ForeignKey;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@ForeignKey(name = "FK_DOCU_FILE")
+public class Document extends File {
+ @Column(nullable = false, name="xsize")
+ private int size;
+
+ Document() {
+ }
+
+ Document(String name, int size) {
+ super( name );
+ this.size = size;
+ }
+
+ public int getSize() {
+ return size;
+ }
+
+ public void setSize(int size) {
+ this.size = size;
+ }
+}
Property changes on: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Document.java
___________________________________________________________________
Name: svn:executable
+ *
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/EventInformation.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/EventInformation.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/EventInformation.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,38 @@
+//$Id: EventInformation.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.inheritance.joined;
+
+import javax.persistence.DiscriminatorColumn;
+import javax.persistence.DiscriminatorType;
+import javax.persistence.DiscriminatorValue;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+
+
+@Entity
+@Inheritance(strategy = InheritanceType.JOINED)
+@DiscriminatorColumn(name = "DTYPE", discriminatorType = DiscriminatorType.STRING, length = 80)
+@DiscriminatorValue("EventInformationT")
+public class EventInformation implements java.io.Serializable {
+
+
+ protected String notificationId;
+
+ @Id
+ public String getNotificationId() {
+ return notificationId;
+ }
+
+ public void setNotificationId(String value) {
+ this.notificationId = value;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ sb.append( "EventInformationT: id = " + getNotificationId() );
+ return sb.toString();
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/File.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/File.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/File.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,48 @@
+//$Id: File.java 15050 2008-08-13 15:34:39Z epbernard $
+package org.hibernate.test.annotations.inheritance.joined;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+import javax.persistence.ManyToOne;
+import javax.persistence.Column;
+import javax.persistence.Table;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Inheritance(strategy = InheritanceType.JOINED)
+@Table(name="joined_file")
+public abstract class File {
+ @Id @Column(name="filename")
+ private String name;
+ @ManyToOne
+ private Folder parent;
+
+ File() {
+ }
+
+ public File(String name) {
+ this.name = name;
+ }
+
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String id) {
+ this.name = id;
+ }
+
+ public Folder getParent() {
+ return parent;
+ }
+
+ public void setParent(Folder parent) {
+ this.parent = parent;
+ }
+
+}
Property changes on: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/File.java
___________________________________________________________________
Name: svn:executable
+ *
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/FinancialAsset.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/FinancialAsset.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/FinancialAsset.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,20 @@
+//$Id: FinancialAsset.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.inheritance.joined;
+
+import javax.persistence.Entity;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class FinancialAsset extends Asset {
+ private double price;
+
+ public double getPrice() {
+ return price;
+ }
+
+ public void setPrice(double price) {
+ this.price = price;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Folder.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Folder.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Folder.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,31 @@
+//$Id: Folder.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.inheritance.joined;
+
+import java.util.HashSet;
+import java.util.Set;
+import javax.persistence.Entity;
+import javax.persistence.OneToMany;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Folder extends File {
+ @OneToMany(mappedBy = "parent")
+ private Set<File> children = new HashSet<File>();
+
+ Folder() {
+ }
+
+ public Folder(String name) {
+ super( name );
+ }
+
+ public Set<File> getChildren() {
+ return children;
+ }
+
+ public void setChildren(Set children) {
+ this.children = children;
+ }
+}
Property changes on: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Folder.java
___________________________________________________________________
Name: svn:executable
+ *
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/JoinedSubclassAndSecondaryTable.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/JoinedSubclassAndSecondaryTable.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/JoinedSubclassAndSecondaryTable.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,33 @@
+//$Id: JoinedSubclassAndSecondaryTable.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.inheritance.joined;
+
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class JoinedSubclassAndSecondaryTable extends TestCase {
+
+ public void testSecondaryTableAndJoined() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ SwimmingPool sp = new SwimmingPool();
+ sp.setAddress( "Park Avenue" );
+ s.persist( sp );
+ tx.rollback();
+ s.close();
+ }
+
+ /**
+ * @see org.hibernate.test.annotations.TestCase#getMappings()
+ */
+ protected Class[] getMappings() {
+ return new Class[]{
+ Pool.class,
+ SwimmingPool.class
+ };
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/JoinedSubclassTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/JoinedSubclassTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/JoinedSubclassTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,178 @@
+//$Id: JoinedSubclassTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.inheritance.joined;
+
+import java.util.List;
+
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class JoinedSubclassTest extends TestCase {
+
+ public JoinedSubclassTest(String x) {
+ super( x );
+ }
+
+ public void testDefault() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ File doc = new Document( "Enron Stuff To Shred", 1000 );
+ Folder folder = new Folder( "Enron" );
+ s.persist( doc );
+ s.persist( folder );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ List result = s.createCriteria( File.class ).list();
+ assertNotNull( result );
+ assertEquals( 2, result.size() );
+ File f2 = (File) result.get( 0 );
+ checkClassType( f2, doc, folder );
+ f2 = (File) result.get( 1 );
+ checkClassType( f2, doc, folder );
+ s.delete( result.get( 0 ) );
+ s.delete( result.get( 1 ) );
+ tx.commit();
+ s.close();
+ }
+
+ public void testManyToOneOnAbstract() throws Exception {
+ Folder f = new Folder();
+ f.setName( "data" );
+ ProgramExecution remove = new ProgramExecution();
+ remove.setAction( "remove" );
+ remove.setAppliesOn( f );
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ s.persist( f );
+ s.persist( remove );
+ tx.commit();
+ s.clear();
+ tx = s.beginTransaction();
+ remove = (ProgramExecution) s.get( ProgramExecution.class, remove.getId() );
+ assertNotNull( remove );
+ assertNotNull( remove.getAppliesOn().getName() );
+ s.delete( remove );
+ s.delete( remove.getAppliesOn() );
+ tx.commit();
+ s.close();
+
+ }
+
+ private void checkClassType(File fruitToTest, File f, Folder a) {
+ if ( fruitToTest.getName().equals( f.getName() ) ) {
+ assertFalse( fruitToTest instanceof Folder );
+ }
+ else if ( fruitToTest.getName().equals( a.getName() ) ) {
+ assertTrue( fruitToTest instanceof Folder );
+ }
+ else {
+ fail( "Result does not contains the previously inserted elements" );
+ }
+ }
+
+ public void testJoinedAbstractClass() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ s.getTransaction().begin();
+ Sweater sw = new Sweater();
+ sw.setColor( "Black" );
+ sw.setSize( 2 );
+ sw.setSweat( true );
+ s.persist( sw );
+ s.getTransaction().commit();
+ s.clear();
+
+ s = openSession();
+ s.getTransaction().begin();
+ sw = (Sweater) s.get( Sweater.class, sw.getId() );
+ s.delete( sw );
+ s.getTransaction().commit();
+ s.close();
+ }
+
+ public void testInheritance() throws Exception {
+ Session session = openSession();
+ Transaction transaction = session.beginTransaction();
+ String eventPK = "event1";
+ EventInformation event = (EventInformation) session.get( EventInformation.class, eventPK );
+ if ( event == null ) {
+ event = new EventInformation();
+ event.setNotificationId( eventPK );
+ session.persist( event );
+ }
+ String alarmPK = "alarm1";
+ Alarm alarm = (Alarm) session.get( Alarm.class, alarmPK );
+ if ( alarm == null ) {
+ alarm = new Alarm();
+ alarm.setNotificationId( alarmPK );
+ alarm.setEventInfo( event );
+ session.persist( alarm );
+ }
+ transaction.commit();
+ session.close();
+ }
+
+// public void testManyToOneAndJoin() throws Exception {
+// Session session = openSession();
+// Transaction transaction = session.beginTransaction();
+// Parent parent = new Parent();
+// session.persist( parent );
+// PropertyAsset property = new PropertyAsset();
+// property.setParent( parent );
+// property.setPrice( 230000d );
+// FinancialAsset financial = new FinancialAsset();
+// financial.setParent( parent );
+// financial.setPrice( 230000d );
+// session.persist( financial );
+// session.persist( property );
+// session.flush();
+// session.clear();
+// parent = (Parent) session.get( Parent.class, parent.getId() );
+// assertNotNull( parent );
+// assertEquals( 1, parent.getFinancialAssets().size() );
+// assertEquals( 1, parent.getPropertyAssets().size() );
+// assertEquals( property.getId(), parent.getPropertyAssets().iterator().next() );
+// transaction.rollback();
+// session.close();
+// }
+
+ @Override
+ protected String[] getXmlFiles() {
+ return new String[] {
+ //"org/hibernate/test/annotations/inheritance/joined/Asset.hbm.xml"
+ };
+ }
+
+ /**
+ * @see org.hibernate.test.annotations.TestCase#getMappings()
+ */
+ protected Class[] getMappings() {
+ return new Class[]{
+ File.class,
+ Folder.class,
+ Document.class,
+ SymbolicLink.class,
+ ProgramExecution.class,
+ Clothing.class,
+ Sweater.class,
+ EventInformation.class,
+ Alarm.class,
+ //Asset.class,
+ //Parent.class,
+ //PropertyAsset.class,
+ //FinancialAsset.class
+ };
+ }
+
+}
Property changes on: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/JoinedSubclassTest.java
___________________________________________________________________
Name: svn:executable
+ *
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Parent.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Parent.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Parent.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,49 @@
+//$Id: Parent.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.inheritance.joined;
+
+import java.util.HashSet;
+import java.util.Set;
+import javax.persistence.CascadeType;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.OneToMany;
+import javax.persistence.Table;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Table(name = "Parent")
+public class Parent {
+ private Integer id;
+ private Set propertyAssets = new HashSet();
+ private Set financialAssets = new HashSet();
+
+ @Id @GeneratedValue public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ @OneToMany(cascade = CascadeType.REFRESH, fetch = FetchType.EAGER, mappedBy = "parent", targetEntity = PropertyAsset.class)
+ public Set getPropertyAssets() {
+ return this.propertyAssets;
+ }
+
+ public void setPropertyAssets(Set propertyAssets) {
+ this.propertyAssets = propertyAssets;
+ }
+
+ @OneToMany(cascade = CascadeType.REFRESH, fetch = FetchType.EAGER, mappedBy = "parent", targetEntity = FinancialAsset.class)
+ public Set getFinancialAssets() {
+ return this.financialAssets;
+ }
+
+ public void setFinancialAssets(Set financialAssets) {
+ this.financialAssets = financialAssets;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Pool.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Pool.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Pool.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,38 @@
+//$Id: Pool.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.inheritance.joined;
+
+import javax.persistence.Entity;
+import javax.persistence.SecondaryTable;
+import javax.persistence.Column;
+import javax.persistence.Id;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Inheritance(strategy = InheritanceType.JOINED)
+@SecondaryTable(name="POOL_ADDRESS")
+public class Pool {
+ @Id @GeneratedValue private Integer id;
+ @Column(table = "POOL_ADDRESS")
+ private String address;
+
+ public String getAddress() {
+ return address;
+ }
+
+ public void setAddress(String address) {
+ this.address = address;
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/ProgramExecution.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/ProgramExecution.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/ProgramExecution.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,47 @@
+//$Id: ProgramExecution.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.inheritance.joined;
+
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.ManyToOne;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class ProgramExecution {
+ @Id
+ @GeneratedValue
+ private Integer id;
+ private String action;
+ @ManyToOne(fetch = FetchType.LAZY)
+ private File appliesOn;
+
+
+ public File getAppliesOn() {
+ return appliesOn;
+ }
+
+ public void setAppliesOn(File appliesOn) {
+ this.appliesOn = appliesOn;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/PropertyAsset.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/PropertyAsset.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/PropertyAsset.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,20 @@
+//$Id: PropertyAsset.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.inheritance.joined;
+
+import javax.persistence.Entity;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class PropertyAsset extends Asset {
+ private double price;
+
+ public double getPrice() {
+ return price;
+ }
+
+ public void setPrice(double price) {
+ this.price = price;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Sweater.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Sweater.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/Sweater.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,22 @@
+//$Id: Sweater.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.inheritance.joined;
+
+import javax.persistence.Entity;
+import javax.persistence.PrimaryKeyJoinColumn;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@PrimaryKeyJoinColumn(name = "clothing_id")
+public class Sweater extends Clothing {
+ private boolean isSweat;
+
+ public boolean isSweat() {
+ return isSweat;
+ }
+
+ public void setSweat(boolean sweat) {
+ isSweat = sweat;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/SwimmingPool.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/SwimmingPool.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/SwimmingPool.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,11 @@
+//$Id: SwimmingPool.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.inheritance.joined;
+
+import javax.persistence.Entity;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class SwimmingPool extends Pool {
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/SymbolicLink.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/SymbolicLink.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/SymbolicLink.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,29 @@
+//$Id: SymbolicLink.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.inheritance.joined;
+
+import javax.persistence.Entity;
+import javax.persistence.ManyToOne;
+
+@Entity
+public class SymbolicLink extends File {
+
+ @ManyToOne(optional = false)
+ File target;
+
+ SymbolicLink() {
+ }
+
+ public SymbolicLink(File target) {
+ this.target = target;
+ }
+
+ public File getTarget() {
+ return target;
+ }
+
+ public void setTarget(File target) {
+ this.target = target;
+ }
+
+
+}
Property changes on: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/joined/SymbolicLink.java
___________________________________________________________________
Name: svn:executable
+ *
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/mixed/Document.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/mixed/Document.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/mixed/Document.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,36 @@
+//$Id: Document.java 15056 2008-08-13 18:15:05Z epbernard $
+package org.hibernate.test.annotations.inheritance.mixed;
+
+import javax.persistence.Column;
+import javax.persistence.DiscriminatorValue;
+import javax.persistence.Entity;
+import javax.persistence.SecondaryTable;
+import javax.persistence.Table;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@DiscriminatorValue("D")
+@SecondaryTable(name = "DocumentMixed")
+@Table(name="Document_Wrong") //illegal use, a warn is raised
+public class Document extends File {
+ private int size;
+
+ Document() {
+ }
+
+ Document(String name, int size) {
+ super( name );
+ this.size = size;
+ }
+
+ @Column(table = "DocumentMixed", name="doc_size", nullable = false)
+ public int getSize() {
+ return size;
+ }
+
+ public void setSize(int size) {
+ this.size = size;
+ }
+}
Property changes on: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/mixed/Document.java
___________________________________________________________________
Name: svn:executable
+ *
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/mixed/File.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/mixed/File.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/mixed/File.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,52 @@
+//$Id: File.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.inheritance.mixed;
+
+import javax.persistence.DiscriminatorColumn;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+import javax.persistence.SecondaryTable;
+import javax.persistence.Table;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
+@Table(name = "FileMixed")
+@SecondaryTable(name = "FileFolderMixed")
+@DiscriminatorColumn(length = 1)
+public abstract class File {
+ private String name;
+ private Folder parent;
+
+ File() {
+ }
+
+ public File(String name) {
+ this.name = name;
+ }
+
+ @Id
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String id) {
+ this.name = id;
+ }
+
+ @ManyToOne
+ @JoinColumn(table = "FileFolderMixed")
+ public Folder getParent() {
+ return parent;
+ }
+
+ public void setParent(Folder parent) {
+ this.parent = parent;
+ }
+
+}
Property changes on: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/mixed/File.java
___________________________________________________________________
Name: svn:executable
+ *
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/mixed/Folder.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/mixed/Folder.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/mixed/Folder.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,33 @@
+//$Id: Folder.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.inheritance.mixed;
+
+import java.util.HashSet;
+import java.util.Set;
+import javax.persistence.DiscriminatorValue;
+import javax.persistence.Entity;
+import javax.persistence.OneToMany;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@DiscriminatorValue("F")
+public class Folder extends File {
+ private Set<File> children = new HashSet<File>();
+
+ Folder() {
+ }
+
+ public Folder(String name) {
+ super( name );
+ }
+
+ @OneToMany(mappedBy = "parent")
+ public Set<File> getChildren() {
+ return children;
+ }
+
+ public void setChildren(Set children) {
+ this.children = children;
+ }
+}
Property changes on: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/mixed/Folder.java
___________________________________________________________________
Name: svn:executable
+ *
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/mixed/SubclassTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/mixed/SubclassTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/mixed/SubclassTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,76 @@
+//$Id: SubclassTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.inheritance.mixed;
+
+import java.util.List;
+
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.exception.SQLGrammarException;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class SubclassTest extends TestCase {
+
+ public SubclassTest(String x) {
+ super( x );
+ }
+
+ public void testDefault() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ File doc = new Document( "Enron Stuff To Shred", 1000 );
+ Folder folder = new Folder( "Enron" );
+ s.persist( doc );
+ s.persist( folder );
+ try {
+ tx.commit();
+ }
+ catch (SQLGrammarException e) {
+ System.err.println( e.getSQLException().getNextException() );
+ }
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ List result = s.createCriteria( File.class ).list();
+ assertNotNull( result );
+ assertEquals( 2, result.size() );
+ File f2 = (File) result.get( 0 );
+ checkClassType( f2, doc, folder );
+ f2 = (File) result.get( 1 );
+ checkClassType( f2, doc, folder );
+ s.delete( result.get( 0 ) );
+ s.delete( result.get( 1 ) );
+ tx.commit();
+ s.close();
+ }
+
+ private void checkClassType(File fruitToTest, File f, Folder a) {
+ if ( fruitToTest.getName().equals( f.getName() ) ) {
+ assertFalse( fruitToTest instanceof Folder );
+ }
+ else if ( fruitToTest.getName().equals( a.getName() ) ) {
+ assertTrue( fruitToTest instanceof Folder );
+ }
+ else {
+ fail( "Result does not contains the previously inserted elements" );
+ }
+ }
+
+ /**
+ * @see org.hibernate.test.annotations.TestCase#getMappings()
+ */
+ protected Class[] getMappings() {
+ return new Class[]{
+ File.class,
+ Folder.class,
+ Document.class,
+ SymbolicLink.class
+ };
+ }
+
+}
Property changes on: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/mixed/SubclassTest.java
___________________________________________________________________
Name: svn:executable
+ *
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/mixed/SymbolicLink.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/mixed/SymbolicLink.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/mixed/SymbolicLink.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,35 @@
+//$Id: SymbolicLink.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.inheritance.mixed;
+
+import javax.persistence.DiscriminatorValue;
+import javax.persistence.Entity;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+import javax.persistence.SecondaryTable;
+
+@Entity
+@DiscriminatorValue("L")
+@SecondaryTable(name = "SymbolicLinkMixed")
+public class SymbolicLink extends File {
+
+ File target;
+
+ SymbolicLink() {
+ }
+
+ public SymbolicLink(File target) {
+ this.target = target;
+ }
+
+ @ManyToOne(optional = false)
+ @JoinColumn(table = "SymbolicLinkMixed")
+ public File getTarget() {
+ return target;
+ }
+
+ public void setTarget(File target) {
+ this.target = target;
+ }
+
+
+}
Property changes on: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/mixed/SymbolicLink.java
___________________________________________________________________
Name: svn:executable
+ *
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/singletable/Building.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/singletable/Building.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/singletable/Building.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,43 @@
+//$Id: Building.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.inheritance.singletable;
+
+import javax.persistence.Column;
+import javax.persistence.DiscriminatorColumn;
+import javax.persistence.DiscriminatorValue;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+import org.hibernate.annotations.ForceDiscriminator;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@DiscriminatorColumn(name = "discriminator_disc")
+@ForceDiscriminator
+@DiscriminatorValue("B")
+public class Building {
+ @Id
+ @GeneratedValue
+ @Column(name = "discriminator_id")
+ private Integer id;
+ @Column(name = "discriminator_street")
+ private String street;
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getStreet() {
+ return street;
+ }
+
+ public void setStreet(String street) {
+ this.street = street;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/singletable/Funk.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/singletable/Funk.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/singletable/Funk.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,22 @@
+//$Id: Funk.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.inheritance.singletable;
+
+import javax.persistence.DiscriminatorValue;
+import javax.persistence.Entity;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@DiscriminatorValue("1")
+public class Funk extends Music {
+ private int starred;
+
+ public int getStarred() {
+ return starred;
+ }
+
+ public void setStarred(int starred) {
+ this.starred = starred;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/singletable/House.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/singletable/House.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/singletable/House.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,13 @@
+//$Id: House.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.inheritance.singletable;
+
+import javax.persistence.DiscriminatorValue;
+import javax.persistence.Entity;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@DiscriminatorValue("H")
+public class House extends Building {
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/singletable/Music.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/singletable/Music.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/singletable/Music.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,53 @@
+//$Id: Music.java 16303 2009-04-11 04:42:16Z gbadner $
+package org.hibernate.test.annotations.inheritance.singletable;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.DiscriminatorColumn;
+import javax.persistence.DiscriminatorType;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.Table;
+import javax.persistence.UniqueConstraint;
+
+import org.hibernate.annotations.DiscriminatorFormula;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+(a)DiscriminatorColumn(discriminatorType=DiscriminatorType.INTEGER)
+@DiscriminatorFormula("case when zik_type is null then 0 else zik_type end")
+@Table(uniqueConstraints = @UniqueConstraint(columnNames = {"avgBeat", "starred"} ))
+public abstract class Music {
+ private Integer id;
+ private int avgBeat;
+ private Integer type;
+
+ @Column(name = "zik_type")
+ public Integer getType() {
+ return type;
+ }
+
+ public void setType(Integer type) {
+ this.type = type;
+ }
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public int getAvgBeat() {
+ return avgBeat;
+ }
+
+ public void setAvgBeat(int avgBeat) {
+ this.avgBeat = avgBeat;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/singletable/Noise.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/singletable/Noise.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/singletable/Noise.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,13 @@
+//$Id: Noise.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.inheritance.singletable;
+
+import javax.persistence.DiscriminatorValue;
+import javax.persistence.Entity;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@DiscriminatorValue("0")
+public class Noise extends Music {
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/singletable/PaperTrash.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/singletable/PaperTrash.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/singletable/PaperTrash.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,11 @@
+//$Id: PaperTrash.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.inheritance.singletable;
+
+import javax.persistence.Entity;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class PaperTrash extends Trash {
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/singletable/Rock.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/singletable/Rock.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/singletable/Rock.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,13 @@
+//$Id: Rock.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.inheritance.singletable;
+
+import javax.persistence.DiscriminatorValue;
+import javax.persistence.Entity;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@DiscriminatorValue("2")
+public class Rock extends Music {
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/singletable/Trash.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/singletable/Trash.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/singletable/Trash.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,19 @@
+//$Id: Trash.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.inheritance.singletable;
+
+import javax.persistence.DiscriminatorColumn;
+import javax.persistence.DiscriminatorType;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@DiscriminatorColumn(discriminatorType = DiscriminatorType.INTEGER)
+public class Trash {
+ @Id
+ @GeneratedValue
+ private Integer id;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/union/Document.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/union/Document.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/union/Document.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,32 @@
+//$Id: Document.java 16293 2009-04-10 19:17:45Z gbadner $
+package org.hibernate.test.annotations.inheritance.union;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Table;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Table(name = "DocumentUnion")
+public class Document extends File {
+ private int size;
+
+ Document() {
+ }
+
+ Document(String name, int size) {
+ super( name );
+ this.size = size;
+ }
+
+ @Column(name="xsize")
+ public int getSize() {
+ return size;
+ }
+
+ public void setSize(int size) {
+ this.size = size;
+ }
+}
Property changes on: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/union/Document.java
___________________________________________________________________
Name: svn:executable
+ *
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/union/File.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/union/File.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/union/File.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,44 @@
+//$Id: File.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.inheritance.union;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+import javax.persistence.ManyToOne;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
+public abstract class File {
+ private String name;
+ private Folder parent;
+
+ File() {
+ }
+
+ public File(String name) {
+ this.name = name;
+ }
+
+ @Id
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String id) {
+ this.name = id;
+ }
+
+ @ManyToOne
+ public Folder getParent() {
+ return parent;
+ }
+
+ public void setParent(Folder parent) {
+ this.parent = parent;
+ }
+
+}
Property changes on: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/union/File.java
___________________________________________________________________
Name: svn:executable
+ *
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/union/Folder.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/union/Folder.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/union/Folder.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,33 @@
+//$Id: Folder.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.inheritance.union;
+
+import java.util.HashSet;
+import java.util.Set;
+import javax.persistence.Entity;
+import javax.persistence.OneToMany;
+import javax.persistence.Table;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Table(name = "FolderUnion")
+public class Folder extends File {
+ private Set<File> children = new HashSet<File>();
+
+ Folder() {
+ }
+
+ public Folder(String name) {
+ super( name );
+ }
+
+ @OneToMany(mappedBy = "parent")
+ public Set<File> getChildren() {
+ return children;
+ }
+
+ public void setChildren(Set children) {
+ this.children = children;
+ }
+}
Property changes on: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/union/Folder.java
___________________________________________________________________
Name: svn:executable
+ *
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/union/SubclassTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/union/SubclassTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/union/SubclassTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,68 @@
+//$Id: SubclassTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.inheritance.union;
+
+import java.util.List;
+
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class SubclassTest extends TestCase {
+
+ public SubclassTest(String x) {
+ super( x );
+ }
+
+ public void testDefault() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ File doc = new Document( "Enron Stuff To Shred", 1000 );
+ Folder folder = new Folder( "Enron" );
+ s.persist( doc );
+ s.persist( folder );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ List result = s.createCriteria( File.class ).list();
+ assertNotNull( result );
+ assertEquals( 2, result.size() );
+ File f2 = (File) result.get( 0 );
+ checkClassType( f2, doc, folder );
+ f2 = (File) result.get( 1 );
+ checkClassType( f2, doc, folder );
+ tx.commit();
+ s.close();
+ }
+
+ private void checkClassType(File fruitToTest, File f, Folder a) {
+ if ( fruitToTest.getName().equals( f.getName() ) ) {
+ assertFalse( fruitToTest instanceof Folder );
+ }
+ else if ( fruitToTest.getName().equals( a.getName() ) ) {
+ assertTrue( fruitToTest instanceof Folder );
+ }
+ else {
+ fail( "Result does not contains the previously inserted elements" );
+ }
+ }
+
+ /**
+ * @see org.hibernate.test.annotations.TestCase#getMappings()
+ */
+ protected Class[] getMappings() {
+ return new Class[]{
+ File.class,
+ Folder.class,
+ Document.class,
+ SymbolicLink.class
+ };
+ }
+
+}
Property changes on: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/union/SubclassTest.java
___________________________________________________________________
Name: svn:executable
+ *
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/union/SymbolicLink.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/union/SymbolicLink.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/union/SymbolicLink.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,31 @@
+//$Id: SymbolicLink.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.inheritance.union;
+
+import javax.persistence.Entity;
+import javax.persistence.ManyToOne;
+import javax.persistence.Table;
+
+@Entity
+@Table(name = "SymbolicLinkUnion")
+public class SymbolicLink extends File {
+
+ File target;
+
+ SymbolicLink() {
+ }
+
+ public SymbolicLink(File target) {
+ this.target = target;
+ }
+
+ @ManyToOne(optional = false)
+ public File getTarget() {
+ return target;
+ }
+
+ public void setTarget(File target) {
+ this.target = target;
+ }
+
+
+}
Property changes on: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/inheritance/union/SymbolicLink.java
___________________________________________________________________
Name: svn:executable
+ *
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/interfaces/Contact.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/interfaces/Contact.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/interfaces/Contact.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,11 @@
+//$Id: Contact.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.interfaces;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public interface Contact {
+ Integer getId();
+
+ String getName();
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/interfaces/ContactImpl.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/interfaces/ContactImpl.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/interfaces/ContactImpl.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,33 @@
+//$Id: ContactImpl.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.interfaces;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class ContactImpl implements Contact {
+ private Integer id;
+ private String name;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/interfaces/InterfacesTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/interfaces/InterfacesTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/interfaces/InterfacesTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,20 @@
+//$Id: InterfacesTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.interfaces;
+
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class InterfacesTest extends TestCase {
+ public void testInterface() {
+
+ }
+
+ protected Class[] getMappings() {
+ return new Class[]{
+ ContactImpl.class,
+ UserImpl.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/interfaces/User.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/interfaces/User.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/interfaces/User.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,15 @@
+//$Id: User.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.interfaces;
+
+import java.util.Collection;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public interface User {
+ Integer getId();
+
+ Collection<Contact> getContacts();
+
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/interfaces/UserImpl.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/interfaces/UserImpl.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/interfaces/UserImpl.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,36 @@
+//$Id: UserImpl.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.interfaces;
+
+import java.util.Collection;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.OneToMany;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class UserImpl implements User {
+ private Collection<Contact> contacts;
+ private Integer id;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ @OneToMany(targetEntity = ContactImpl.class)
+ public Collection<Contact> getContacts() {
+ return contacts;
+ }
+
+ public void setContacts(Collection<Contact> contacts) {
+ this.contacts = contacts;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/A.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/A.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/A.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,24 @@
+//$Id: A.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.join;
+
+import java.util.Date;
+import javax.persistence.MappedSuperclass;
+import javax.persistence.Column;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@MappedSuperclass
+public abstract class A {
+ @Column(nullable = false)
+ private Date createDate;
+
+
+ public Date getCreateDate() {
+ return createDate;
+ }
+
+ public void setCreateDate(Date createDate) {
+ this.createDate = createDate;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/B.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/B.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/B.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,38 @@
+//$Id: B.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.join;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Inheritance( strategy = InheritanceType.SINGLE_TABLE )
+public abstract class B extends A {
+ @Id
+ @GeneratedValue
+ private Integer id;
+ @Column(nullable = false) private String name;
+
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/C.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/C.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/C.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,26 @@
+//$Id: C.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.join;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.DiscriminatorValue;
+import javax.persistence.SecondaryTable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@DiscriminatorValue("C")
+@SecondaryTable(name="C")
+public class C extends B {
+ @Column(table = "C") private int age;
+
+
+ public int getAge() {
+ return age;
+ }
+
+ public void setAge(int age) {
+ this.age = age;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/Cat.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/Cat.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/Cat.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,101 @@
+//$Id: Cat.java 16418 2009-04-23 09:55:33Z jcosta(a)redhat.com $
+package org.hibernate.test.annotations.join;
+
+import java.io.Serializable;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.SecondaryTable;
+import javax.persistence.SecondaryTables;
+import javax.persistence.UniqueConstraint;
+
+import org.hibernate.annotations.Index;
+import org.hibernate.annotations.Table;
+import org.hibernate.annotations.ForeignKey;
+import org.hibernate.annotations.Tables;
+import org.hibernate.annotations.FetchMode;
+import org.hibernate.annotations.SQLInsert;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@SecondaryTables({
+@SecondaryTable(name = "`Cat nbr1`"),
+@SecondaryTable(name = "Cat2", uniqueConstraints = {@UniqueConstraint(columnNames = {"storyPart2"})})
+ })
+@Tables( {
+ @Table(appliesTo = "Cat", indexes = @Index(name = "secondname",
+ columnNames = "secondName"), comment = "My cat table" ),
+ @Table(appliesTo = "Cat2", foreignKey = @ForeignKey(name="FK_CAT2_CAT"), fetch = FetchMode.SELECT,
+ sqlInsert=@SQLInsert(sql="insert into Cat2(storyPart2, id) values(upper(?), ?)") )
+ } )
+public class Cat implements Serializable {
+
+ private Integer id;
+ private String name;
+ private String secondName;
+ private String storyPart1;
+ private String storyPart2;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ @Index(name = "nameindex")
+ public String getName() {
+ return name;
+ }
+
+ public void setId(Integer integer) {
+ id = integer;
+ }
+
+ public void setName(String string) {
+ name = string;
+ }
+
+ public String getSecondName() {
+ return secondName;
+ }
+
+ public void setSecondName(String secondName) {
+ this.secondName = secondName;
+ }
+
+// Bug HHH-36
+// @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
+// @JoinColumn(name="CAT_ID", secondaryTable="ExtendedLife")
+// public Set<Life> getLifes() {
+// return lifes;
+// }
+//
+// public void setLifes(Set<Life> collection) {
+// lifes = collection;
+// }
+
+ @Column(table = "`Cat nbr1`")
+ @Index(name = "story1index")
+ public String getStoryPart1() {
+ return storyPart1;
+ }
+
+ @Column(table = "Cat2", nullable = false)
+ public String getStoryPart2() {
+ return storyPart2;
+ }
+
+
+ public void setStoryPart1(String string) {
+ storyPart1 = string;
+ }
+
+
+ public void setStoryPart2(String string) {
+ storyPart2 = string;
+ }
+
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/Death.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/Death.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/Death.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,30 @@
+//$Id: Death.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.join;
+
+import java.io.Serializable;
+import java.util.Date;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.SecondaryTable;
+import javax.persistence.PrimaryKeyJoinColumn;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@SecondaryTable(
+ name = "ExtendedDeath",
+ pkJoinColumns = @PrimaryKeyJoinColumn(name = "DEATH_ID")
+)
+public class Death implements Serializable {
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ public Integer id;
+ @Column(name = "death_date")
+ public Date date;
+ @Column(table = "ExtendedDeath")
+ public String howDoesItHappen;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/Dog.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/Dog.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/Dog.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,40 @@
+//$Id: Dog.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.join;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.PrimaryKeyJoinColumn;
+import javax.persistence.SecondaryTable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@SecondaryTable(
+ name = "DogThoroughbred",
+ pkJoinColumns = {@PrimaryKeyJoinColumn(name = "NAME", referencedColumnName = "name"),
+ @PrimaryKeyJoinColumn(name = "OWNER_NAME", referencedColumnName = "ownerName")}
+)
+public class Dog {
+ @Id
+ public DogPk id;
+ public int weight;
+ @Column(table = "DogThoroughbred")
+ public String thoroughbredName;
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( !( o instanceof Dog ) ) return false;
+
+ final Dog dog = (Dog) o;
+
+ if ( !id.equals( dog.id ) ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ return id.hashCode();
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/DogPk.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/DogPk.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/DogPk.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,33 @@
+//$Id: DogPk.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.join;
+
+import java.io.Serializable;
+import javax.persistence.Embeddable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Embeddable
+public class DogPk implements Serializable {
+ public String name;
+ public String ownerName;
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( !( o instanceof DogPk ) ) return false;
+
+ final DogPk dogPk = (DogPk) o;
+
+ if ( !name.equals( dogPk.name ) ) return false;
+ if ( !ownerName.equals( dogPk.ownerName ) ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ int result;
+ result = name.hashCode();
+ result = 29 * result + ownerName.hashCode();
+ return result;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/JoinTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/JoinTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/JoinTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,206 @@
+//$Id: JoinTest.java 16418 2009-04-23 09:55:33Z jcosta(a)redhat.com $
+package org.hibernate.test.annotations.join;
+
+import java.util.Date;
+
+import org.hibernate.Criteria;
+import org.hibernate.HibernateException;
+import org.hibernate.Query;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.criterion.Expression;
+import org.hibernate.mapping.Join;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class JoinTest extends TestCase {
+
+ public void testDefaultValue() throws Exception {
+ Join join = (Join) getCfg().getClassMapping( Life.class.getName() ).getJoinClosureIterator().next();
+ assertEquals( "ExtendedLife", join.getTable().getName() );
+ org.hibernate.mapping.Column owner = new org.hibernate.mapping.Column();
+ owner.setName( "LIFE_ID" );
+ assertTrue( join.getTable().getPrimaryKey().containsColumn( owner ) );
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Life life = new Life();
+ life.duration = 15;
+ life.fullDescription = "Long long description";
+ s.persist( life );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ Query q = s.createQuery( "from " + Life.class.getName() );
+ life = (Life) q.uniqueResult();
+ assertEquals( "Long long description", life.fullDescription );
+ tx.commit();
+ s.close();
+ }
+
+ public void testCompositePK() throws Exception {
+ Join join = (Join) getCfg().getClassMapping( Dog.class.getName() ).getJoinClosureIterator().next();
+ assertEquals( "DogThoroughbred", join.getTable().getName() );
+ org.hibernate.mapping.Column owner = new org.hibernate.mapping.Column();
+ owner.setName( "OWNER_NAME" );
+ assertTrue( join.getTable().getPrimaryKey().containsColumn( owner ) );
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Dog dog = new Dog();
+ DogPk id = new DogPk();
+ id.name = "Thalie";
+ id.ownerName = "Martine";
+ dog.id = id;
+ dog.weight = 30;
+ dog.thoroughbredName = "Colley";
+ s.persist( dog );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ Query q = s.createQuery( "from Dog" );
+ dog = (Dog) q.uniqueResult();
+ assertEquals( "Colley", dog.thoroughbredName );
+ tx.commit();
+ s.close();
+ }
+
+ public void testExplicitValue() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Death death = new Death();
+ death.date = new Date();
+ death.howDoesItHappen = "Well, haven't seen it";
+ s.persist( death );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ Query q = s.createQuery( "from " + Death.class.getName() );
+ death = (Death) q.uniqueResult();
+ assertEquals( "Well, haven't seen it", death.howDoesItHappen );
+ s.delete( death );
+ tx.commit();
+ s.close();
+ }
+
+ public void testManyToOne() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Life life = new Life();
+ Cat cat = new Cat();
+ cat.setName( "kitty" );
+ cat.setStoryPart2( "and the story continues" );
+ life.duration = 15;
+ life.fullDescription = "Long long description";
+ life.owner = cat;
+ s.persist( life );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ Criteria crit = s.createCriteria( Life.class );
+ crit.createCriteria( "owner" ).add( Expression.eq( "name", "kitty" ) );
+ life = (Life) crit.uniqueResult();
+ assertEquals( "Long long description", life.fullDescription );
+ s.delete( life.owner );
+ s.delete( life );
+ tx.commit();
+ s.close();
+ }
+
+ public void testUniqueConstaintOnSecondaryTable() throws Exception {
+ Cat cat = new Cat();
+ cat.setStoryPart2( "My long story" );
+ Cat cat2 = new Cat();
+ cat2.setStoryPart2( "My long story" );
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ try {
+ s.persist( cat );
+ s.persist( cat2 );
+ tx.commit();
+ fail( "unique constraints violation on secondary table" );
+ }
+ catch (HibernateException e) {
+ //success
+ }
+ finally {
+ if ( tx != null ) tx.rollback();
+ s.close();
+ }
+ }
+
+ public void testFetchModeOnSecondaryTable() throws Exception {
+ Cat cat = new Cat();
+ cat.setStoryPart2( "My long story" );
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+
+ s.persist( cat );
+ s.flush();
+ s.clear();
+
+ s.get( Cat.class, cat.getId() );
+ //Find a way to test it, I need to define the secondary table on a subclass
+
+ tx.rollback();
+ s.close();
+ }
+
+ public void testCustomSQL() throws Exception {
+ Cat cat = new Cat();
+ String storyPart2 = "My long story";
+ cat.setStoryPart2( storyPart2 );
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+
+ s.persist( cat );
+ s.flush();
+ s.clear();
+
+ Cat c = (Cat) s.get( Cat.class, cat.getId() );
+ assertEquals( storyPart2.toUpperCase(), c.getStoryPart2() );
+
+ tx.rollback();
+ s.close();
+ }
+
+ public void testMappedSuperclassAndSecondaryTable() throws Exception {
+ Session s = openSession( );
+ s.getTransaction().begin();
+ C c = new C();
+ c.setAge( 12 );
+ c.setCreateDate( new Date() );
+ c.setName( "Bob" );
+ s.persist( c );
+ s.flush();
+ s.clear();
+ c= (C) s.get( C.class, c.getId() );
+ assertNotNull( c.getCreateDate() );
+ assertNotNull( c.getName() );
+ s.getTransaction().rollback();
+ s.close();
+ }
+
+ /**
+ * @see org.hibernate.test.annotations.TestCase#getMappings()
+ */
+ protected Class[] getMappings() {
+ return new Class[]{
+ Life.class,
+ Death.class,
+ Cat.class,
+ Dog.class,
+ A.class,
+ B.class,
+ C.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/Life.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/Life.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/join/Life.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,34 @@
+//$Id: Life.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.join;
+
+import java.io.Serializable;
+import javax.persistence.CascadeType;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+import javax.persistence.SecondaryTable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@SecondaryTable(name = "ExtendedLife")
+public class Life implements Serializable {
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ @Column(name = "LIFE_ID")
+ public Integer id;
+
+ public int duration;
+ @Column(table = "ExtendedLife")
+ public String fullDescription;
+
+ @ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
+ @JoinColumn(name = "CAT_ID", table = "ExtendedLife")
+ public Cat owner;
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/loader/Loader.hbm.xml
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/loader/Loader.hbm.xml (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/loader/Loader.hbm.xml 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,21 @@
+<?xml version="1.0"?>
+<!DOCTYPE hibernate-mapping PUBLIC
+ "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+ "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
+
+<!--
+
+ Used to demonstrate the declarative configuration
+ of both hbm files and annotated classes
+ See hibernate.cfg.xml and ConfigurationTest
+
+-->
+
+<hibernate-mapping package="org.hibernate.test.annotations.loader">
+
+ <sql-query name="loadByTeam">
+ <load-collection alias="p" role="Team.players"/>
+ select {p.*} from Player p where p.team_id = ?
+ </sql-query>
+
+</hibernate-mapping>
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/loader/LoaderTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/loader/LoaderTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/loader/LoaderTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,69 @@
+//$Id: LoaderTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.loader;
+
+import java.util.Set;
+import java.util.Iterator;
+
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.annotations.TestCase;
+
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class LoaderTest extends TestCase {
+
+
+ protected String[] getXmlFiles() {
+ return new String[] {
+ "org/hibernate/test/annotations/loader/Loader.hbm.xml"
+ };
+ }
+
+ public void testBasic() throws Exception {
+ Session s = openSession( );
+ Transaction tx = s.beginTransaction();
+ Team t = new Team();
+ Player p = new Player();
+ p.setName("me");
+ t.getPlayers().add(p);
+ p.setTeam(t);
+
+
+ try {
+ s.persist(p);
+ s.persist(t);
+ tx.commit();
+ s.close();
+
+ s= openSession( );
+ tx = s.beginTransaction();
+ Team t2 = (Team)s.load(Team.class,new Long(1));
+ Set<Player> players = t2.getPlayers();
+ Iterator<Player> iterator = players.iterator();
+ assertEquals("me", iterator.next().getName());
+ tx.commit();
+
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ if ( tx != null ) tx.rollback();
+ }
+ finally {
+ s.close();
+ }
+ }
+
+ /**
+ * @see org.hibernate.test.annotations.TestCase#getMappings()
+ */
+ protected Class[] getMappings() {
+ return new Class[]{
+ Player.class,
+ Team.class
+ };
+ }
+
+}
+
Property changes on: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/loader/LoaderTest.java
___________________________________________________________________
Name: svn:executable
+ *
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/loader/Player.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/loader/Player.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/loader/Player.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,48 @@
+package org.hibernate.test.annotations.loader;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+
+import org.hibernate.annotations.Fetch;
+import org.hibernate.annotations.FetchMode;
+
+@Entity
+public class Player {
+
+ private Long id;
+ private Team team;
+ private String name;
+
+ @Id
+ @GeneratedValue
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ @ManyToOne(targetEntity = Team.class)
+ @Fetch(FetchMode.SELECT)
+ @JoinColumn(name = "team_id")
+ public Team getTeam() {
+ return team;
+ }
+
+ public void setTeam(Team team) {
+ this.team = team;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+}
Property changes on: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/loader/Player.java
___________________________________________________________________
Name: svn:executable
+ *
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/loader/Team.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/loader/Team.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/loader/Team.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,45 @@
+package org.hibernate.test.annotations.loader;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.OneToMany;
+
+import org.hibernate.annotations.Fetch;
+import org.hibernate.annotations.FetchMode;
+import org.hibernate.annotations.Loader;
+import org.hibernate.annotations.NamedNativeQueries;
+import org.hibernate.annotations.NamedNativeQuery;
+
+import javax.persistence.NamedQuery;
+
+@Entity
+public class Team {
+ private Long id;
+ private Set<Player> players = new HashSet<Player>();
+
+ @Id
+ @GeneratedValue
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ @OneToMany(targetEntity = Player.class, mappedBy = "team", fetch = FetchType.EAGER)
+ @Fetch(FetchMode.SELECT)
+ @Loader(namedQuery = "loadByTeam")
+ public Set<Player> getPlayers() {
+ return players;
+ }
+
+ public void setPlayers(Set<Player> players) {
+ this.players = players;
+ }
+}
Property changes on: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/loader/Team.java
___________________________________________________________________
Name: svn:executable
+ *
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/lob/Book.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/lob/Book.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/lob/Book.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,79 @@
+//$Id: Book.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.lob;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.Lob;
+import javax.persistence.Table;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Table(name = "lob_book")
+public class Book {
+ private Integer id;
+ private String shortDescription;
+ private String fullText;
+ private Character[] code;
+ private char[] code2;
+ private Editor editor;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getShortDescription() {
+ return shortDescription;
+ }
+
+ public void setShortDescription(String shortDescription) {
+ this.shortDescription = shortDescription;
+ }
+
+ @Lob
+ @Column(name = "fld_fulltext")
+ public String getFullText() {
+ return fullText;
+ }
+
+ public void setFullText(String fullText) {
+ this.fullText = fullText;
+ }
+
+ @Lob
+ @Column(name = "fld_code")
+ public Character[] getCode() {
+ return code;
+ }
+
+ public void setCode(Character[] code) {
+ this.code = code;
+ }
+
+ @Lob
+ public char[] getCode2() {
+ return code2;
+ }
+
+ public void setCode2(char[] code2) {
+ this.code2 = code2;
+ }
+
+ @Lob
+ public Editor getEditor() {
+ return editor;
+ }
+
+ public void setEditor(Editor editor) {
+ this.editor = editor;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/lob/CompiledCode.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/lob/CompiledCode.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/lob/CompiledCode.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,56 @@
+//$Id: CompiledCode.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.lob;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.Lob;
+
+/**
+ * Compiled code representation
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class CompiledCode {
+ private Integer id;
+ private Byte[] header;
+ private byte[] fullCode;
+ private byte[] metadata;
+
+ public byte[] getMetadata() {
+ return metadata;
+ }
+
+ public void setMetadata(byte[] metadata) {
+ this.metadata = metadata;
+ }
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ @Lob
+ public Byte[] getHeader() {
+ return header;
+ }
+
+ public void setHeader(Byte[] header) {
+ this.header = header;
+ }
+
+ @Lob
+ public byte[] getFullCode() {
+ return fullCode;
+ }
+
+ public void setFullCode(byte[] fullCode) {
+ this.fullCode = fullCode;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/lob/Editor.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/lob/Editor.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/lob/Editor.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,19 @@
+//$Id: Editor.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.lob;
+
+import java.io.Serializable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class Editor implements Serializable {
+ private String name;
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/lob/LobTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/lob/LobTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/lob/LobTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,131 @@
+//$Id: LobTest.java 17724 2009-10-13 15:47:59Z stliu $
+package org.hibernate.test.annotations.lob;
+
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class LobTest extends TestCase {
+ public void testSerializableToBlob() throws Exception {
+ Book book = new Book();
+ Editor editor = new Editor();
+ editor.setName( "O'Reilly" );
+ book.setEditor( editor );
+ book.setCode2( new char[]{'r'} );
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ s.persist( book );
+ tx.commit();
+ s.close();
+ s = openSession();
+ tx = s.beginTransaction();
+ Book loadedBook = (Book) s.get( Book.class, book.getId() );
+ assertNotNull( loadedBook.getEditor() );
+ assertEquals( book.getEditor().getName(), loadedBook.getEditor().getName() );
+ loadedBook.setEditor( null );
+ tx.commit();
+ s.close();
+ s = openSession();
+ tx = s.beginTransaction();
+ loadedBook = (Book) s.get( Book.class, book.getId() );
+ assertNull( loadedBook.getEditor() );
+ tx.commit();
+ s.close();
+
+ }
+
+ public void testClob() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Book b = new Book();
+ b.setShortDescription( "Hibernate Bible" );
+ b.setFullText( "Hibernate in Action aims to..." );
+ b.setCode( new Character[]{'a', 'b', 'c'} );
+ b.setCode2( new char[]{'a', 'b', 'c'} );
+ s.persist( b );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ Book b2 = (Book) s.get( Book.class, b.getId() );
+ assertNotNull( b2 );
+ assertEquals( b2.getFullText(), b.getFullText() );
+ assertEquals( b2.getCode()[1].charValue(), b.getCode()[1].charValue() );
+ assertEquals( b2.getCode2()[2], b.getCode2()[2] );
+ tx.commit();
+ s.close();
+ }
+
+ public void testBlob() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ CompiledCode cc = new CompiledCode();
+ Byte[] header = new Byte[2];
+ header[0] = new Byte( (byte) 3 );
+ header[1] = new Byte( (byte) 0 );
+ cc.setHeader( header );
+ int codeSize = 5;
+ byte[] full = new byte[codeSize];
+ for ( int i = 0; i < codeSize ; i++ ) {
+ full[i] = (byte) ( 1 + i );
+ }
+ cc.setFullCode( full );
+ s.persist( cc );
+ tx.commit();
+ s.close();
+ s = openSession();
+ tx = s.beginTransaction();
+ CompiledCode recompiled = (CompiledCode) s.get( CompiledCode.class, cc.getId() );
+ assertEquals( recompiled.getHeader()[1], cc.getHeader()[1] );
+ assertEquals( recompiled.getFullCode()[codeSize - 1], cc.getFullCode()[codeSize - 1] );
+ tx.commit();
+ s.close();
+ }
+
+ public void testBinary() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ CompiledCode cc = new CompiledCode();
+ byte[] metadata = new byte[2];
+ metadata[0] = (byte) 3;
+ metadata[1] = (byte) 0;
+ cc.setMetadata( metadata );
+ s.persist( cc );
+ tx.commit();
+ s.close();
+ s = openSession();
+ tx = s.beginTransaction();
+ CompiledCode recompiled = (CompiledCode) s.get( CompiledCode.class, cc.getId() );
+ assertEquals( recompiled.getMetadata()[1], cc.getMetadata()[1] );
+ tx.commit();
+ s.close();
+ }
+
+ @Override
+ protected boolean runForCurrentDialect() {
+ return super.runForCurrentDialect() && getDialect().supportsExpectedLobUsagePattern();
+ }
+
+ public LobTest(String x) {
+ super( x );
+ }
+
+ protected Class[] getMappings() {
+ return new Class[]{
+ Book.class,
+ CompiledCode.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Building.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Building.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Building.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,35 @@
+//$Id: Building.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.manytomany;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Building {
+ @Id @GeneratedValue private Long id;
+
+ @ManyToOne @JoinColumn(name="company_id", referencedColumnName = "name")
+ private BuildingCompany company;
+
+ public BuildingCompany getCompany() {
+ return company;
+ }
+
+ public void setCompany(BuildingCompany company) {
+ this.company = company;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/BuildingCompany.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/BuildingCompany.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/BuildingCompany.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,29 @@
+//$Id: BuildingCompany.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.manytomany;
+
+import java.util.Date;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.GeneratedValue;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class BuildingCompany extends Company {
+ @Id @GeneratedValue private Long id;
+ private Date foundedIn;
+
+ public Date getFoundedIn() {
+ return foundedIn;
+ }
+
+ public void setFoundedIn(Date foundedIn) {
+ this.foundedIn = foundedIn;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Cat.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Cat.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Cat.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,68 @@
+//$Id: Cat.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.manytomany;
+
+import java.util.Set;
+import javax.persistence.EmbeddedId;
+import javax.persistence.Entity;
+import javax.persistence.ManyToMany;
+import javax.persistence.Table;
+import javax.persistence.JoinTable;
+import javax.persistence.JoinColumn;
+
+import org.hibernate.annotations.Index;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Table(name = "tbl_cat")
+//ANN-630
+//(a)org.hibernate.annotations.Table(appliesTo= "TT", indexes = @Index(name = "testidx", columnNames = "cat_id"))
+public class Cat {
+ private CatPk id;
+ private int age;
+ private Set<Woman> humanContacts;
+
+ @ManyToMany
+ //@Index(name = "CAT_HUMAN_IDX")
+ @JoinTable(name="TT")
+ public Set<Woman> getHumanContacts() {
+ return humanContacts;
+ }
+
+ public void setHumanContacts(Set<Woman> humanContacts) {
+ this.humanContacts = humanContacts;
+ }
+
+ @EmbeddedId()
+ public CatPk getId() {
+ return id;
+ }
+
+ public void setId(CatPk id) {
+ this.id = id;
+ }
+
+ public int getAge() {
+ return age;
+ }
+
+ public void setAge(int age) {
+ this.age = age;
+ }
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( !( o instanceof Cat ) ) return false;
+
+ final Cat cat = (Cat) o;
+
+ if ( !id.equals( cat.id ) ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ return id.hashCode();
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/CatPk.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/CatPk.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/CatPk.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,50 @@
+//$Id: CatPk.java 16343 2009-04-15 18:33:43Z gbadner $
+package org.hibernate.test.annotations.manytomany;
+
+import java.io.Serializable;
+import javax.persistence.Column;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class CatPk implements Serializable {
+ private String name;
+ private String thoroughbred;
+
+ @Column(length=128)
+ public String getThoroughbred() {
+ return thoroughbred;
+ }
+
+ public void setThoroughbred(String thoroughbred) {
+ this.thoroughbred = thoroughbred;
+ }
+
+ @Column(length=128)
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( !( o instanceof CatPk ) ) return false;
+
+ final CatPk catPk = (CatPk) o;
+
+ if ( !name.equals( catPk.name ) ) return false;
+ if ( !thoroughbred.equals( catPk.thoroughbred ) ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ int result;
+ result = name.hashCode();
+ result = 29 * result + thoroughbred.hashCode();
+ return result;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/City.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/City.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/City.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,35 @@
+//$Id: City.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.manytomany;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Table(name = "tbl_city")
+public class City {
+ private Integer id;
+ private String name;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Company.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Company.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Company.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,22 @@
+//$Id: Company.java 17529 2009-09-19 19:59:46Z stliu $
+package org.hibernate.test.annotations.manytomany;
+
+import java.io.Serializable;
+import javax.persistence.MappedSuperclass;
+import javax.persistence.Column;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@MappedSuperclass
+public class Company implements Serializable {
+ @Column private String name;
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Contractor.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Contractor.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Contractor.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,26 @@
+//$Id: Employee.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.manytomany;
+
+import java.io.Serializable;
+
+import javax.persistence.Entity;
+
+/**
+ * Employee in an Employer-Employee relationship
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity
+@SuppressWarnings("serial")
+public class Contractor extends Employee implements Serializable {
+
+ private float hourlyRate;
+
+ public float getHourlyRate() {
+ return hourlyRate;
+ }
+
+ public void setHourlyRate(float hourlyRate) {
+ this.hourlyRate = hourlyRate;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Employee.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Employee.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Employee.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,62 @@
+//$Id: Employee.java 14781 2008-06-18 18:04:17Z hardy.ferentschik $
+package org.hibernate.test.annotations.manytomany;
+
+import java.io.Serializable;
+import java.util.Collection;
+import javax.persistence.CascadeType;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+import javax.persistence.ManyToMany;
+import javax.persistence.Column;
+
+import org.hibernate.annotations.Cascade;
+
+/**
+ * Employee in an Employer-Employee relationship
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Inheritance(strategy = InheritanceType.JOINED)
+@SuppressWarnings("serial")
+public class Employee implements Serializable {
+ private Integer id;
+ private Collection<Employer> employers;
+ private String name;
+
+ @Column(name="fld_name")
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer integer) {
+ id = integer;
+ }
+
+ @ManyToMany(
+ cascade = {CascadeType.PERSIST, CascadeType.MERGE},
+ mappedBy = "employees"
+ )
+ @Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE,
+ org.hibernate.annotations.CascadeType.PERSIST})
+ public Collection<Employer> getEmployers() {
+ return employers;
+ }
+
+ public void setEmployers(Collection<Employer> employers) {
+ this.employers = employers;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Employer.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Employer.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Employer.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,80 @@
+//$Id: Employer.java 14764 2008-06-12 13:41:16Z hardy.ferentschik $
+package org.hibernate.test.annotations.manytomany;
+
+import java.io.Serializable;
+import java.util.Collection;
+import java.util.List;
+
+import javax.persistence.CascadeType;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinTable;
+import javax.persistence.ManyToMany;
+import javax.persistence.OrderBy;
+import javax.persistence.Table;
+
+import org.hibernate.annotations.Cascade;
+
+/**
+ * Employer in a employer-Employee relationship
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity()
+@Table(name="`Employer`")
+@SuppressWarnings({"serial", "unchecked"})
+public class Employer implements Serializable {
+ private Integer id;
+ private Collection employees;
+ private List contractors;
+
+ @ManyToMany(
+ targetEntity = org.hibernate.test.annotations.manytomany.Contractor.class,
+ cascade = {CascadeType.PERSIST, CascadeType.MERGE}
+ )
+ @JoinTable(
+ name = "EMPLOYER_CONTRACTOR",
+ joinColumns = {@JoinColumn(name = "EMPLOYER_ID")},
+ inverseJoinColumns = {@JoinColumn(name = "CONTRACTOR_ID")}
+ )
+ @Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)
+ @OrderBy("name desc")
+ public List getContractors() {
+ return contractors;
+ }
+
+ public void setContractors(List contractors) {
+ this.contractors = contractors;
+ }
+
+ @ManyToMany(
+ targetEntity = org.hibernate.test.annotations.manytomany.Employee.class,
+ cascade = {CascadeType.PERSIST, CascadeType.MERGE}
+ )
+ @JoinTable(
+ name = "EMPLOYER_EMPLOYEE",
+ joinColumns = {@JoinColumn(name = "EMPER_ID")},
+ inverseJoinColumns = {@JoinColumn(name = "EMPEE_ID")}
+ )
+ @Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)
+ @OrderBy("name asc")
+ public Collection getEmployees() {
+ return employees;
+ }
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setEmployees(Collection set) {
+ employees = set;
+ }
+
+ public void setId(Integer integer) {
+ id = integer;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Friend.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Friend.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Friend.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,59 @@
+//$Id: Friend.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.manytomany;
+
+import java.io.Serializable;
+import java.util.Set;
+import javax.persistence.CascadeType;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinTable;
+import javax.persistence.ManyToMany;
+
+
+/**
+ * Friend has other friends in a many to many way
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity()
+public class Friend implements Serializable {
+ private Integer id;
+ private String name;
+ private Set<Friend> friends;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setId(Integer integer) {
+ id = integer;
+ }
+
+ public void setName(String string) {
+ name = string;
+ }
+
+ @ManyToMany(
+ cascade = {CascadeType.PERSIST, CascadeType.MERGE}
+ )
+ @JoinTable(
+ name = "FRIEND2FRIEND",
+ joinColumns = {@JoinColumn(name = "FROM_FR", nullable = false)},
+ inverseJoinColumns = {@JoinColumn(name = "TO_FR", nullable = false)}
+ )
+ public Set<Friend> getFriends() {
+ return friends;
+ }
+
+ public void setFriends(Set<Friend> friend) {
+ this.friends = friend;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Group.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Group.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Group.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,50 @@
+//$Id: Group.java 17529 2009-09-19 19:59:46Z stliu $
+package org.hibernate.test.annotations.manytomany;
+
+import java.util.Collection;
+import javax.persistence.CascadeType;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.ManyToMany;
+import javax.persistence.OrderBy;
+import javax.persistence.Table;
+
+import org.hibernate.annotations.Where;
+import org.hibernate.annotations.FilterDef;
+import org.hibernate.annotations.Filter;
+import org.hibernate.annotations.FilterJoinTable;
+import org.hibernate.annotations.WhereJoinTable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Table(name = "tbl_group")
+@FilterDef(name="Groupfilter")
+public class Group {
+ private Integer id;
+ private Collection<Permission> permissions;
+
+ @Id
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ @ManyToMany(cascade = CascadeType.PERSIST)
+ @OrderBy("expirationDate")
+ @Where(clause = "1=1")
+ @WhereJoinTable(clause = "2=2")
+ @Filter(name="Groupfilter", condition = "3=3")
+ @FilterJoinTable(name="Groupfilter", condition = "4=4")
+ public Collection<Permission> getPermissions() {
+ return permissions;
+ }
+
+ public void setPermissions(Collection<Permission> permissions) {
+ this.permissions = permissions;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/GroupWithSet.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/GroupWithSet.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/GroupWithSet.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,55 @@
+//$Id: GroupWithSet.java 17529 2009-09-19 19:59:46Z stliu $
+package org.hibernate.test.annotations.manytomany;
+
+import java.util.Collection;
+import java.util.Set;
+
+import javax.persistence.CascadeType;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinTable;
+import javax.persistence.ManyToMany;
+import javax.persistence.OrderBy;
+import javax.persistence.Table;
+import javax.persistence.UniqueConstraint;
+
+import org.hibernate.annotations.Where;
+import org.hibernate.annotations.FilterDef;
+import org.hibernate.annotations.Filter;
+import org.hibernate.annotations.FilterJoinTable;
+import org.hibernate.annotations.WhereJoinTable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Table(name = "tbl_group")
+@FilterDef(name="Groupfilter")
+public class GroupWithSet {
+ private Integer id;
+ private Set<Permission> permissions;
+
+ @Id
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ @ManyToMany(cascade = CascadeType.PERSIST)
+ @OrderBy("expirationDate")
+ @Where(clause = "1=1")
+ @WhereJoinTable(clause = "2=2")
+ @Filter(name="Groupfilter", condition = "3=3")
+ @FilterJoinTable(name="Groupfilter", condition = "4=4")
+ public Set<Permission> getPermissions() {
+ return permissions;
+ }
+
+ public void setPermissions(Set<Permission> permissions) {
+ this.permissions = permissions;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Inspector.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Inspector.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Inspector.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,37 @@
+//$Id: Inspector.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.manytomany;
+
+import java.io.Serializable;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Inheritance(strategy = InheritanceType.JOINED)
+class Inspector implements Serializable {
+ @Id
+ @GeneratedValue
+ @Column(name = "id")
+ private Long _id;
+
+ private String name;
+
+ public Long getId() {
+ return _id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
+
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/InspectorPrefixes.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/InspectorPrefixes.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/InspectorPrefixes.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,51 @@
+//$Id: InspectorPrefixes.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.manytomany;
+
+import java.util.ArrayList;
+import java.util.List;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinTable;
+import javax.persistence.ManyToMany;
+import javax.persistence.PrimaryKeyJoinColumn;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@PrimaryKeyJoinColumn(name = "inspector_id")
+class InspectorPrefixes extends Inspector {
+ @Column(name = "prefixes", nullable = false)
+ private String prefixes;
+ @ManyToMany()
+ @JoinTable(name = "deserted_area",
+ joinColumns = @JoinColumn(name = "inspector_name", referencedColumnName = "name"),
+ inverseJoinColumns = @JoinColumn(name = "area_id", referencedColumnName = "id"))
+ private List<Zone> desertedAreas = new ArrayList<Zone>();
+
+ @ManyToMany()
+ @JoinTable(name = "inspector_prefixes_areas",
+ joinColumns = @JoinColumn(name = "inspector_id", referencedColumnName = "inspector_id"),
+ inverseJoinColumns = @JoinColumn(name = "area_id", referencedColumnName = "id"))
+ private List<Zone> areas = new ArrayList<Zone>();
+
+ InspectorPrefixes() {
+ }
+
+ InspectorPrefixes(String prefixes) {
+ this.prefixes = prefixes;
+ }
+
+ public String getPrefixes() {
+ return this.prefixes;
+ }
+
+ public List<Zone> getAreas() {
+ return areas;
+ }
+
+ public List<Zone> getDesertedAreas() {
+ return desertedAreas;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/KnownClient.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/KnownClient.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/KnownClient.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,45 @@
+//$Id: KnownClient.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.manytomany;
+
+import java.util.Set;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.ManyToMany;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class KnownClient {
+ private Integer id;
+ private String name;
+ private Set<Store> stores;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @ManyToMany(mappedBy = "customers")
+ public Set<Store> getStores() {
+ return stores;
+ }
+
+ public void setStores(Set<Store> stores) {
+ this.stores = stores;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Man.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Man.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Man.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,63 @@
+//$Id: Man.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.manytomany;
+
+import java.io.Serializable;
+import java.util.Set;
+import javax.persistence.CascadeType;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.ManyToMany;
+
+/**
+ * Man knowing sevezral womens
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Man implements Serializable {
+ private ManPk id;
+ private String carName;
+ private Set<Woman> womens;
+
+ @ManyToMany(cascade = {CascadeType.ALL}, mappedBy = "mens")
+ public Set<Woman> getWomens() {
+ return womens;
+ }
+
+ public void setWomens(Set<Woman> womens) {
+ this.womens = womens;
+ }
+
+ @Id
+ public ManPk getId() {
+ return id;
+ }
+
+ public void setId(ManPk id) {
+ this.id = id;
+ }
+
+ public String getCarName() {
+ return carName;
+ }
+
+ public void setCarName(String carName) {
+ this.carName = carName;
+ }
+
+ public int hashCode() {
+ //a NPE can occurs, but I don't expect hashcode to be used before pk is set
+ return getId().hashCode();
+ }
+
+ public boolean equals(Object obj) {
+ //a NPE can occurs, but I don't expect equals to be used before pk is set
+ if ( obj != null && obj instanceof Man ) {
+ return getId().equals( ( (Man) obj ).getId() );
+ }
+ else {
+ return false;
+ }
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/ManPk.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/ManPk.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/ManPk.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,60 @@
+//$Id: ManPk.java 16343 2009-04-15 18:33:43Z gbadner $
+package org.hibernate.test.annotations.manytomany;
+
+import java.io.Serializable;
+import javax.persistence.Embeddable;
+import javax.persistence.Column;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Embeddable
+public class ManPk implements Serializable {
+ private String firstName;
+ private String lastName;
+ private boolean isElder;
+
+ public boolean isElder() {
+ return isElder;
+ }
+
+ public void setElder(boolean elder) {
+ isElder = elder;
+ }
+
+ public int hashCode() {
+ //this implem sucks
+ return getFirstName().hashCode() + getLastName().hashCode() + ( isElder() ? 0 : 1 );
+ }
+
+ public boolean equals(Object obj) {
+ //firstName and lastName are expected to be set in this implem
+ if ( obj != null && obj instanceof ManPk ) {
+ ManPk other = (ManPk) obj;
+ return getFirstName().equals( other.getFirstName() )
+ && getLastName().equals( other.getLastName() )
+ && isElder() == other.isElder();
+ }
+ else {
+ return false;
+ }
+ }
+
+ public void setFirstName(String firstName) {
+ this.firstName = firstName;
+ }
+
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+
+ @Column(length=128)
+ public String getFirstName() {
+ return firstName;
+ }
+
+ @Column(length=128)
+ public String getLastName() {
+ return lastName;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/ManyToManyTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/ManyToManyTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/ManyToManyTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,671 @@
+//$Id: ManyToManyTest.java 17529 2009-09-19 19:59:46Z stliu $
+package org.hibernate.test.annotations.manytomany;
+
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+
+import org.hibernate.Hibernate;
+import org.hibernate.JDBCException;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * Many to many tests
+ *
+ * @author Emmanuel Bernard
+ */
+@SuppressWarnings("unchecked")
+public class ManyToManyTest extends TestCase {
+
+ public ManyToManyTest(String x) {
+ super( x );
+ }
+
+ public void testDefault() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Store fnac = new Store();
+ fnac.setName( "Fnac" );
+ KnownClient emmanuel = new KnownClient();
+ emmanuel.setName( "Emmanuel" );
+ emmanuel.setStores( new HashSet<Store>() );
+ fnac.setCustomers( new HashSet<KnownClient>() );
+ fnac.getCustomers().add( emmanuel );
+ emmanuel.getStores().add( fnac );
+ fnac.setImplantedIn( new HashSet<City>() );
+ City paris = new City();
+ fnac.getImplantedIn().add( paris );
+ paris.setName( "Paris" );
+ s.persist( fnac );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ Store store;
+ KnownClient knownClient;
+ City city;
+ store = (Store) s.get( Store.class, fnac.getId() );
+ assertNotNull( store );
+ assertNotNull( store.getCustomers() );
+ assertEquals( 1, store.getCustomers().size() );
+ knownClient = (KnownClient) store.getCustomers().iterator().next();
+ assertEquals( emmanuel.getName(), knownClient.getName() );
+ assertNotNull( store.getImplantedIn() );
+ assertEquals( 1, store.getImplantedIn().size() );
+ city = (City) store.getImplantedIn().iterator().next();
+ assertEquals( paris.getName(), city.getName() );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ knownClient = (KnownClient) s.get( KnownClient.class, emmanuel.getId() );
+ assertNotNull( knownClient );
+ assertNotNull( knownClient.getStores() );
+ assertEquals( 1, knownClient.getStores().size() );
+ store = (Store) knownClient.getStores().iterator().next();
+ assertEquals( fnac.getName(), store.getName() );
+ tx.commit();
+ s.close();
+ }
+
+ public void testDefaultCompositePk() throws Exception {
+ Session s;
+ Transaction tx;
+
+ s = openSession();
+ tx = s.beginTransaction();
+ CatPk catPk = new CatPk();
+ catPk.setName( "Minou" );
+ catPk.setThoroughbred( "Persan" );
+ Cat cat = new Cat();
+ cat.setId( catPk );
+ cat.setAge( 32 );
+ Woman woman = new Woman();
+ WomanPk womanPk = new WomanPk();
+ womanPk.setFirstName( "Emma" );
+ womanPk.setLastName( "Peel" );
+ woman.setId( womanPk );
+ woman.setCats( new HashSet<Cat>() );
+ woman.getCats().add( cat );
+ cat.setHumanContacts( new HashSet<Woman>() );
+ cat.getHumanContacts().add( woman );
+ s.persist( woman );
+ s.persist( cat );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ Cat sameCat = (Cat) s.get( Cat.class, cat.getId() );
+ assertNotNull( sameCat );
+ assertNotNull( sameCat.getHumanContacts() );
+ assertEquals( 1, sameCat.getHumanContacts().size() );
+ Woman sameWoman = sameCat.getHumanContacts().iterator().next();
+ assertEquals( sameWoman.getId().getLastName(), woman.getId().getLastName() );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ sameWoman = (Woman) s.get( Woman.class, woman.getId() );
+ assertNotNull( sameWoman );
+ assertNotNull( sameWoman.getCats() );
+ assertEquals( 1, sameWoman.getCats().size() );
+ sameCat = sameWoman.getCats().iterator().next();
+ assertEquals( cat.getAge(), sameCat.getAge() );
+ tx.commit();
+ s.close();
+ }
+
+ public void testMappedBy() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Store fnac = new Store();
+ fnac.setName( "Fnac" );
+ Supplier emi = new Supplier();
+ emi.setName( "Emmanuel" );
+ emi.setSuppStores( new HashSet<Store>() );
+ fnac.setSuppliers( new HashSet<Supplier>() );
+ fnac.getSuppliers().add( emi );
+ emi.getSuppStores().add( fnac );
+ s.persist( fnac );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ Store store;
+ Supplier supplier;
+ store = (Store) s.get( Store.class, fnac.getId() );
+ assertNotNull( store );
+ assertNotNull( store.getSuppliers() );
+ assertEquals( 1, store.getSuppliers().size() );
+ supplier = (Supplier) store.getSuppliers().iterator().next();
+ assertEquals( emi.getName(), supplier.getName() );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ supplier = (Supplier) s.get( Supplier.class, emi.getId() );
+ assertNotNull( supplier );
+ assertNotNull( supplier.getSuppStores() );
+ assertEquals( 1, supplier.getSuppStores().size() );
+ store = (Store) supplier.getSuppStores().iterator().next();
+ assertEquals( fnac.getName(), store.getName() );
+ tx.commit();
+ 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 );
+ Set erColl = new HashSet();
+ Collection eeColl = new ArrayList();
+ erColl.add( ee );
+ eeColl.add( er );
+ er.setEmployees( erColl );
+ ee.setEmployers( eeColl );
+ //s.persist(ee);
+ 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();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ ee = (Employee) s.get( Employee.class, ee.getId() );
+ assertNotNull( ee );
+ assertFalse( "ManyToMany mappedBy lazyness", Hibernate.isInitialized( ee.getEmployers() ) );
+ tx.commit();
+ assertFalse( "ManyToMany mappedBy lazyness", Hibernate.isInitialized( ee.getEmployers() ) );
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ ee = (Employee) s.get( Employee.class, ee.getId() );
+ assertNotNull( ee );
+ er = ee.getEmployers().iterator().next();
+ assertTrue( "second join non lazy", Hibernate.isInitialized( er ) );
+ s.delete( er );
+ s.delete( ee );
+ tx.commit();
+ s.close();
+ }
+
+ public void testOrderByEmployee() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Employer employer = new Employer();
+ Employee employee1 = new Employee();
+ employee1.setName( "Emmanuel" );
+ Employee employee2 = new Employee();
+ employee2.setName( "Alice" );
+ s.persist( employee1 );
+ s.persist( employee2 );
+ Set erColl = new HashSet();
+ Collection eeColl = new ArrayList();
+ Collection eeColl2 = new ArrayList();
+ erColl.add( employee1 );
+ erColl.add( employee2 );
+ eeColl.add( employer );
+ eeColl2.add( employer );
+ employer.setEmployees( erColl );
+ employee1.setEmployers( eeColl );
+ employee2.setEmployers( eeColl2 );
+
+ s.flush();
+ s.clear();
+
+ employer = (Employer) s.get( Employer.class, employer.getId() );
+ assertNotNull( employer );
+ assertNotNull( employer.getEmployees() );
+ assertEquals( 2, employer.getEmployees().size() );
+ Employee eeFromDb = (Employee) employer.getEmployees().iterator().next();
+ assertEquals( employee2.getName(), eeFromDb.getName() );
+ tx.rollback();
+ s.close();
+
+ }
+
+ /**
+ * ANN-625
+ *
+ * @throws Exception in case the test fails.
+ *
+ * This test only works against databases which allow a mixed usage of
+ * table names and table aliases. The generated SQL for this test is:
+ *
+ * select
+ * contractor0_.EMPLOYER_ID as EMPLOYER1_1_,
+ * contractor0_.CONTRACTOR_ID as CONTRACTOR2_1_,
+ * contractor1_.id as id2_0_,
+ * contractor1_.fld_name as fld3_2_0_,
+ * contractor1_.hourlyRate as hourlyRate2_0_
+ * from
+ * EMPLOYER_CONTRACTOR contractor0_
+ * left outer join
+ * Employee contractor1_
+ * on contractor0_.CONTRACTOR_ID=contractor1_.id
+ * where
+ * contractor0_.EMPLOYER_ID=?
+ * order by
+ * Employee.fld_name desc
+ *
+ *
+ */
+// HHH-3577
+// public void testOrderByContractor() throws Exception {
+//
+// Session s;
+// Transaction tx;
+// s = openSession();
+// tx = s.beginTransaction();
+//
+// // create some test entities
+// Employer employer = new Employer();
+// Contractor contractor1 = new Contractor();
+// contractor1.setName( "Emmanuel" );
+// contractor1.setHourlyRate(100.0f);
+// Contractor contractor2 = new Contractor();
+// contractor2.setName( "Hardy" );
+// contractor2.setHourlyRate(99.99f);
+// s.persist( contractor1 );
+// s.persist( contractor2 );
+//
+// // add contractors to employer
+// List setOfContractors = new ArrayList();
+// setOfContractors.add( contractor1 );
+// setOfContractors.add( contractor2 );
+// employer.setContractors( setOfContractors );
+//
+// // add employer to contractors
+// Collection employerListContractor1 = new ArrayList();
+// employerListContractor1.add( employer );
+// contractor1.setEmployers( employerListContractor1 );
+//
+// Collection employerListContractor2 = new ArrayList();
+// employerListContractor2.add( employer );
+// contractor2.setEmployers( employerListContractor2 );
+//
+// s.flush();
+// s.clear();
+//
+// // assertions
+// employer = (Employer) s.get( Employer.class, employer.getId() );
+// assertNotNull( employer );
+// assertNotNull( employer.getContractors() );
+// assertEquals( 2, employer.getContractors().size() );
+// Contractor firstContractorFromDb = (Contractor) employer.getContractors().iterator().next();
+// assertEquals( contractor2.getName(), firstContractorFromDb.getName() );
+// tx.rollback();
+// s.close();
+// }
+
+ public void testRemoveInBetween() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Employer er = new Employer();
+ Employee ee = new Employee();
+ Employee ee2 = new Employee();
+ s.persist( ee );
+ s.persist( ee2 );
+ Set erColl = new HashSet();
+ Collection eeColl = new ArrayList();
+ erColl.add( ee );
+ erColl.add( ee2 );
+ eeColl.add( er );
+ er.setEmployees( erColl );
+ ee.setEmployers( eeColl );
+ //s.persist(ee);
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ er = (Employer) s.load( Employer.class, er.getId() );
+ assertNotNull( er );
+ assertNotNull( er.getEmployees() );
+ assertEquals( 2, er.getEmployees().size() );
+ Iterator iterator = er.getEmployees().iterator();
+ Employee eeFromDb = (Employee) iterator.next();
+ if ( eeFromDb.getId().equals( ee.getId() ) ) {
+ eeFromDb = (Employee) iterator.next();
+ }
+ assertEquals( ee2.getId(), eeFromDb.getId() );
+ er.getEmployees().remove( eeFromDb );
+ eeFromDb.getEmployers().remove( er );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ ee = (Employee) s.get( Employee.class, ee.getId() );
+ assertNotNull( ee );
+ assertFalse( "ManyToMany mappedBy lazyness", Hibernate.isInitialized( ee.getEmployers() ) );
+ tx.commit();
+ assertFalse( "ManyToMany mappedBy lazyness", Hibernate.isInitialized( ee.getEmployers() ) );
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ ee = (Employee) s.get( Employee.class, ee.getId() );
+ assertNotNull( ee );
+ er = ee.getEmployers().iterator().next();
+ assertTrue( "second join non lazy", Hibernate.isInitialized( er ) );
+ assertEquals( 1, er.getEmployees().size() );
+ s.delete( er );
+ s.delete( ee );
+ tx.commit();
+ s.close();
+ }
+
+ public void testSelf() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Friend f = new Friend();
+ Friend sndF = new Friend();
+ f.setName( "Starsky" );
+ sndF.setName( "Hutch" );
+ Set frnds = new HashSet();
+ frnds.add( sndF );
+ f.setFriends( frnds );
+ //Starsky is a friend of Hutch but hutch is not
+ s.persist( f );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ f = (Friend) s.load( Friend.class, f.getId() );
+ assertNotNull( f );
+ assertNotNull( f.getFriends() );
+ assertEquals( 1, f.getFriends().size() );
+ Friend fromDb2ndFrnd = (Friend) f.getFriends().iterator().next();
+ assertEquals( fromDb2ndFrnd.getId(), sndF.getId() );
+ assertEquals( 0, fromDb2ndFrnd.getFriends().size() );
+ tx.commit();
+ s.close();
+ }
+
+ public void testCompositePk() throws Exception {
+ Session s;
+ Transaction tx;
+
+ ManPk m1pk = new ManPk();
+ m1pk.setElder( true );
+ m1pk.setFirstName( "Lucky" );
+ m1pk.setLastName( "Luke" );
+ ManPk m2pk = new ManPk();
+ m2pk.setElder( false );
+ m2pk.setFirstName( "Joe" );
+ m2pk.setLastName( "Dalton" );
+
+ Man m1 = new Man();
+ m1.setId( m1pk );
+ m1.setCarName( "Jolly Jumper" );
+ Man m2 = new Man();
+ m2.setId( m2pk );
+
+ WomanPk w1pk = new WomanPk();
+ w1pk.setFirstName( "Ma" );
+ w1pk.setLastName( "Dalton" );
+ WomanPk w2pk = new WomanPk();
+ w2pk.setFirstName( "Carla" );
+ w2pk.setLastName( "Bruni" );
+
+ Woman w1 = new Woman();
+ w1.setId( w1pk );
+ Woman w2 = new Woman();
+ w2.setId( w2pk );
+
+ Set<Woman> womens = new HashSet<Woman>();
+ womens.add( w1 );
+ m1.setWomens( womens );
+ Set<Woman> womens2 = new HashSet<Woman>();
+ womens2.add( w1 );
+ womens2.add( w2 );
+ m2.setWomens( womens2 );
+
+ Set<Man> mens = new HashSet<Man>();
+ mens.add( m1 );
+ mens.add( m2 );
+ w1.setMens( mens );
+ Set<Man> mens2 = new HashSet<Man>();
+ mens2.add( m2 );
+ w2.setMens( mens2 );
+
+ s = openSession();
+ tx = s.beginTransaction();
+ s.persist( m1 );
+ s.persist( m2 );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ m1 = (Man) s.load( Man.class, m1pk );
+ assertFalse( m1.getWomens().isEmpty() );
+ assertEquals( 1, m1.getWomens().size() );
+ w1 = (Woman) s.load( Woman.class, w1pk );
+ assertFalse( w1.getMens().isEmpty() );
+ assertEquals( 2, w1.getMens().size() );
+
+ tx.commit();
+ s.close();
+ }
+
+ public void testAssociationTableUniqueConstraints() throws Exception {
+ Session s = openSession();
+ Permission readAccess = new Permission();
+ readAccess.setPermission( "read" );
+ readAccess.setExpirationDate( new Date() );
+ Collection<Permission> coll = new ArrayList<Permission>( 2 );
+ coll.add( readAccess );
+ coll.add( readAccess );
+ Group group = new Group();
+ group.setId( new Integer( 1 ) );
+ group.setPermissions( coll );
+ s.getTransaction().begin();
+ try {
+ s.persist( group );
+ s.getTransaction().commit();
+ fail( "Unique constraints not applied on association table" );
+ }
+ catch (JDBCException e) {
+ //success
+ s.getTransaction().rollback();
+ }
+ finally {
+ s.close();
+ }
+ }
+
+ public void testAssociationTableAndOrderBy() throws Exception {
+ Session s = openSession();
+ s.enableFilter( "Groupfilter" );
+ Permission readAccess = new Permission();
+ readAccess.setPermission( "read" );
+ readAccess.setExpirationDate( new Date() );
+ Permission writeAccess = new Permission();
+ writeAccess.setPermission( "write" );
+ writeAccess.setExpirationDate( new Date( new Date().getTime() - 10*60*1000 ) );
+ Collection<Permission> coll = new ArrayList<Permission>( 2 );
+ coll.add( readAccess );
+ coll.add( writeAccess );
+ Group group = new Group();
+ group.setId( new Integer( 1 ) );
+ group.setPermissions( coll );
+ s.getTransaction().begin();
+ s.persist( group );
+ s.flush();
+ s.clear();
+ group = (Group) s.get( Group.class, group.getId() );
+ s.createQuery( "select g from Group g join fetch g.permissions").list();
+ assertEquals( "write", group.getPermissions().iterator().next().getPermission() );
+ s.getTransaction().rollback();
+ s.close();
+ }
+
+ public void testAssociationTableAndOrderByWithSet() throws Exception {
+ Session s = openSession();
+ s.enableFilter( "Groupfilter" );
+
+ Permission readAccess = new Permission();
+ readAccess.setPermission( "read" );
+ readAccess.setExpirationDate( new Date() );
+
+ Permission writeAccess = new Permission();
+ writeAccess.setPermission( "write" );
+ writeAccess.setExpirationDate( new Date( new Date().getTime() - 10*60*1000 ) );
+
+ Permission executeAccess = new Permission();
+ executeAccess.setPermission( "execute" );
+ executeAccess.setExpirationDate( new Date( new Date().getTime() - 5*60*1000 ) );
+
+ Set<Permission> coll = new HashSet<Permission>( 3 );
+ coll.add( readAccess );
+ coll.add( writeAccess );
+ coll.add( executeAccess );
+
+ GroupWithSet group = new GroupWithSet();
+ group.setId( new Integer( 1 ) );
+ group.setPermissions( coll );
+ s.getTransaction().begin();
+ s.persist( group );
+ s.flush();
+ s.clear();
+
+ group = (GroupWithSet) s.get( GroupWithSet.class, group.getId() );
+ s.createQuery( "select g from Group g join fetch g.permissions").list();
+ Iterator<Permission> permIter = group.getPermissions().iterator();
+ assertEquals( "write", permIter.next().getPermission() );
+ assertEquals( "execute", permIter.next().getPermission() );
+ assertEquals( "read", permIter.next().getPermission() );
+ s.getTransaction().rollback();
+ s.close();
+ }
+
+ public void testJoinedSubclassManyToMany() throws Exception {
+ Session s = openSession();
+ Zone a = new Zone();
+ InspectorPrefixes ip = new InspectorPrefixes( "dgi" );
+ Transaction tx = s.beginTransaction();
+ s.save( a );
+ s.save( ip );
+ ip.getAreas().add( a );
+ tx.commit();
+ s.close();
+ s = openSession();
+ tx = s.beginTransaction();
+ ip = (InspectorPrefixes) s.get( InspectorPrefixes.class, ip.getId() );
+ assertNotNull( ip );
+ assertEquals( 1, ip.getAreas().size() );
+ assertEquals( a.getId(), ip.getAreas().get( 0 ).getId() );
+ s.delete( ip );
+ s.delete( ip.getAreas().get( 0 ) );
+ tx.commit();
+ s.close();
+ }
+
+ public void testJoinedSubclassManyToManyWithNonPkReference() throws Exception {
+ Session s = openSession();
+ Zone a = new Zone();
+ InspectorPrefixes ip = new InspectorPrefixes( "dgi" );
+ ip.setName( "Inspector" );
+ Transaction tx = s.beginTransaction();
+ s.save( a );
+ s.save( ip );
+ ip.getDesertedAreas().add( a );
+ tx.commit();
+ s.close();
+ s = openSession();
+ tx = s.beginTransaction();
+ ip = (InspectorPrefixes) s.get( InspectorPrefixes.class, ip.getId() );
+ assertNotNull( ip );
+ assertEquals( 1, ip.getDesertedAreas().size() );
+ assertEquals( a.getId(), ip.getDesertedAreas().get( 0 ).getId() );
+ s.delete( ip );
+ s.delete( ip.getDesertedAreas().get( 0 ) );
+ tx.commit();
+ s.close();
+ }
+
+ public void testReferencedColumnNameToSuperclass() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ BuildingCompany comp = new BuildingCompany();
+ comp.setFoundedIn( new Date() );
+ comp.setName( "Builder century corp.");
+ s.persist( comp );
+ Building building = new Building();
+ building.setCompany( comp );
+ s.persist( building );
+ s.flush();
+ s.clear();
+ building = (Building) s.get( Building.class, building.getId() );
+ assertEquals( comp.getName(), building.getCompany().getName() );
+ tx.rollback();
+ s.close();
+ }
+
+ /**
+ * @see org.hibernate.test.annotations.TestCase#getMappings()
+ */
+ protected Class[] getMappings() {
+ return new Class[]{
+ Friend.class,
+ Employer.class,
+ Employee.class,
+ Contractor.class,
+ Man.class,
+ Woman.class,
+ Store.class,
+ KnownClient.class,
+ Supplier.class,
+ City.class,
+ Cat.class,
+ Group.class,
+ GroupWithSet.class,
+ Permission.class,
+ Zone.class,
+ Inspector.class,
+ InspectorPrefixes.class,
+ BuildingCompany.class,
+ Building.class
+ };
+ }
+
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Permission.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Permission.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Permission.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,32 @@
+//$Id: Permission.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.manytomany;
+
+import java.util.Date;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Permission {
+ private String permission;
+ private Date expirationDate;
+
+ @Id
+ public String getPermission() {
+ return permission;
+ }
+
+ public void setPermission(String permission) {
+ this.permission = permission;
+ }
+
+ public Date getExpirationDate() {
+ return expirationDate;
+ }
+
+ public void setExpirationDate(Date expirationDate) {
+ this.expirationDate = expirationDate;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Store.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Store.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Store.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,74 @@
+//$Id: Store.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.manytomany;
+
+import java.util.Set;
+import javax.persistence.CascadeType;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinTable;
+import javax.persistence.ManyToMany;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Store {
+ private Integer id;
+ private String name;
+ private Set<KnownClient> customers;
+ private Set<Supplier> suppliers;
+
+ @ManyToMany(cascade = CascadeType.PERSIST)
+ public Set<City> getImplantedIn() {
+ return implantedIn;
+ }
+
+ public void setImplantedIn(Set<City> implantedIn) {
+ this.implantedIn = implantedIn;
+ }
+
+ private Set<City> implantedIn;
+
+ @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
+ @JoinTable(
+ name = "StoreSupplier",
+ joinColumns = @JoinColumn(name = "store"),
+ inverseJoinColumns = @JoinColumn(name = "supplier")
+ )
+ public Set<Supplier> getSuppliers() {
+ return suppliers;
+ }
+
+ public void setSuppliers(Set<Supplier> suppliers) {
+ this.suppliers = suppliers;
+ }
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
+ public Set<KnownClient> getCustomers() {
+ return customers;
+ }
+
+ public void setCustomers(Set<KnownClient> customers) {
+ this.customers = customers;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Supplier.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Supplier.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Supplier.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,46 @@
+//$Id: Supplier.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.manytomany;
+
+import java.util.Set;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.ManyToMany;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Supplier {
+ private Integer id;
+ private String name;
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ private Set<Store> suppStores;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ @ManyToMany(mappedBy = "suppliers")
+ public Set<Store> getSuppStores() {
+ return suppStores;
+ }
+
+ public void setSuppStores(Set<Store> suppStores) {
+ this.suppStores = suppStores;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Woman.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Woman.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Woman.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,91 @@
+//$Id: Woman.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.manytomany;
+
+import java.io.Serializable;
+import java.util.Set;
+import javax.persistence.CascadeType;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinTable;
+import javax.persistence.ManyToMany;
+
+import org.hibernate.annotations.ForeignKey;
+
+/**
+ * Woman knowing several mens
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Woman implements Serializable {
+ private WomanPk id;
+ private String carName;
+ private Set<Man> mens;
+ private Set<Cat> cats;
+
+ @ManyToMany(mappedBy = "humanContacts")
+ public Set<Cat> getCats() {
+ return cats;
+ }
+
+ public void setCats(Set<Cat> cats) {
+ this.cats = cats;
+ }
+
+ @ManyToMany(cascade = {CascadeType.ALL})
+ @JoinTable(
+ name = "Man_Woman",
+ joinColumns = {
+ @JoinColumn(name = "womanLastName", referencedColumnName = "lastName"),
+ @JoinColumn(name = "womanFirstName", referencedColumnName = "firstName")
+ },
+ inverseJoinColumns = {
+ @JoinColumn(name = "manIsElder", referencedColumnName = "elder"),
+ @JoinColumn(name = "manLastName", referencedColumnName = "lastName"),
+ @JoinColumn(name = "manFirstName", referencedColumnName = "firstName")
+ }
+ )
+ @ForeignKey(name = "WM_W_FK", inverseName = "WM_M_FK")
+ public Set<Man> getMens() {
+ return mens;
+ }
+
+ public void setMens(Set<Man> mens) {
+ this.mens = mens;
+ }
+
+ @Id
+ public WomanPk getId() {
+ return id;
+ }
+
+ public void setId(WomanPk id) {
+ this.id = id;
+ }
+
+ public String getCarName() {
+ return carName;
+ }
+
+ public void setCarName(String carName) {
+ this.carName = carName;
+ }
+
+
+ public int hashCode() {
+ //a NPE can occurs, but I don't expect hashcode to be used before pk is set
+ return getId().hashCode();
+ }
+
+ public boolean equals(Object obj) {
+ //a NPE can occurs, but I don't expect equals to be used before pk is set
+ if ( obj != null && obj instanceof Woman ) {
+ return getId().equals( ( (Woman) obj ).getId() );
+ }
+ else {
+ return false;
+ }
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/WomanPk.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/WomanPk.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/WomanPk.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,52 @@
+//$Id: WomanPk.java 16343 2009-04-15 18:33:43Z gbadner $
+package org.hibernate.test.annotations.manytomany;
+
+import java.io.Serializable;
+import javax.persistence.Embeddable;
+import javax.persistence.Column;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Embeddable
+public class WomanPk implements Serializable {
+
+
+ private String firstName;
+ private String lastName;
+
+ public int hashCode() {
+ //this implem sucks
+ return getFirstName().hashCode() + getLastName().hashCode();
+ }
+
+ public boolean equals(Object obj) {
+ //firstName and lastName are expected to be set in this implem
+ if ( obj != null && obj instanceof WomanPk ) {
+ WomanPk other = (WomanPk) obj;
+ return getFirstName().equals( other.getFirstName() )
+ && getLastName().equals( other.getLastName() );
+ }
+ else {
+ return false;
+ }
+ }
+
+ public void setFirstName(String firstName) {
+ this.firstName = firstName;
+ }
+
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+
+ @Column(length=128)
+ public String getFirstName() {
+ return firstName;
+ }
+
+ @Column(length=128)
+ public String getLastName() {
+ return lastName;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Zone.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Zone.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytomany/Zone.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,27 @@
+//$Id: Zone.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.manytomany;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Zone {
+ private Integer id;
+
+ @Id
+ @GeneratedValue
+ @Column(name = "id")
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/BiggestForest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/BiggestForest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/BiggestForest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,34 @@
+//$Id: BiggestForest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.manytoone;
+
+import javax.persistence.Entity;
+import javax.persistence.OneToOne;
+import javax.persistence.Id;
+import javax.persistence.GeneratedValue;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class BiggestForest {
+ private Integer id;
+ private ForestType type;
+
+ @Id @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ @OneToOne(mappedBy = "biggestRepresentative")
+ public ForestType getType() {
+ return type;
+ }
+
+ public void setType(ForestType type) {
+ this.type = type;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Car.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Car.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Car.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,51 @@
+//$Id: Car.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.manytoone;
+
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.ManyToOne;
+
+import org.hibernate.annotations.ForeignKey;
+
+/**
+ * Many to one sample using default mapping values
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Car {
+ private Integer id;
+ private Color bodyColor;
+ private Parent owner;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ @ManyToOne(fetch = FetchType.EAGER)
+ @ForeignKey(name="BODY_COLOR_FK")
+ public Color getBodyColor() {
+ return bodyColor;
+ }
+
+ public void setBodyColor(Color bodyColor) {
+ this.bodyColor = bodyColor;
+ }
+
+ @ManyToOne
+ public Parent getOwner() {
+ return owner;
+ }
+
+ public void setOwner(Parent owner) {
+ this.owner = owner;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Carz.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Carz.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Carz.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,124 @@
+//$Id: Carz.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.manytoone;
+
+import java.io.Serializable;
+import java.util.Date;
+import javax.persistence.Entity;
+import javax.persistence.ManyToOne;
+import javax.persistence.Column;
+import javax.persistence.JoinColumns;
+import javax.persistence.FetchType;
+import javax.persistence.JoinColumn;
+import javax.persistence.TemporalType;
+import javax.persistence.Id;
+import javax.persistence.Temporal;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Carz implements Serializable {
+ @Id
+ private Integer id;
+
+ @Column( name = "make", nullable = false )
+ private String make;
+
+ @Column( name = "model", nullable = false )
+ private String model;
+
+ @Column( name = "manufactured", nullable = false )
+ @Temporal( TemporalType.TIMESTAMP )
+ private Date manufactured;
+
+ @ManyToOne( fetch = FetchType.LAZY )
+ @JoinColumn( name = "loc_code", referencedColumnName = "loc_code" )
+ private Lotz lot;
+
+ public Carz() {
+ }
+
+ public Integer getId() {
+ return this.id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public Lotz getLot() {
+ return this.lot;
+ }
+
+ public void setLot(Lotz lot) {
+ this.lot = lot;
+ }
+
+ public String getMake() {
+ return this.make;
+ }
+
+ public void setMake(String make) {
+ this.make = make;
+ }
+
+ public Date getManufactured() {
+ return this.manufactured;
+ }
+
+ public void setManufactured(Date manufactured) {
+ this.manufactured = manufactured;
+ }
+
+ public String getModel() {
+ return this.model;
+ }
+
+ public void setModel(String model) {
+ this.model = model;
+ }
+
+ @Override
+ public int hashCode() {
+ final int PRIME = 31;
+ int result = 1;
+ result = PRIME * result + ( ( this.id == null ) ?
+ 0 :
+ this.id.hashCode() );
+ result = PRIME * result + ( ( this.make == null ) ?
+ 0 :
+ this.make.hashCode() );
+ result = PRIME * result + ( ( this.manufactured == null ) ?
+ 0 :
+ this.manufactured.hashCode() );
+ result = PRIME * result + ( ( this.model == null ) ?
+ 0 :
+ this.model.hashCode() );
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if ( this == obj ) return true;
+ if ( obj == null ) return false;
+ if ( getClass() != obj.getClass() ) return false;
+ final Carz other = (Carz) obj;
+ if ( this.id == null ) {
+ if ( other.id != null ) return false;
+ }
+ else if ( !this.id.equals( other.id ) ) return false;
+ if ( this.make == null ) {
+ if ( other.make != null ) return false;
+ }
+ else if ( !this.make.equals( other.make ) ) return false;
+ if ( this.manufactured == null ) {
+ if ( other.manufactured != null ) return false;
+ }
+ else if ( !this.manufactured.equals( other.manufactured ) ) return false;
+ if ( this.model == null ) {
+ if ( other.model != null ) return false;
+ }
+ else if ( !this.model.equals( other.model ) ) return false;
+ return true;
+ }
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Child.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Child.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Child.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,32 @@
+//$Id: Child.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.manytoone;
+
+import java.io.Serializable;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinColumns;
+import javax.persistence.ManyToOne;
+import javax.persistence.Table;
+
+/**
+ * TODO: change this sample with an Address -> Country relation. This is more accurate
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Table(name = "tbl_child")
+public class Child implements Serializable {
+ @Id
+ @GeneratedValue
+ public Integer id;
+
+ @ManyToOne()
+ @JoinColumns({
+ @JoinColumn(name = "parentCivility", referencedColumnName = "isMale"),
+ @JoinColumn(name = "parentLastName", referencedColumnName = "lastName"),
+ @JoinColumn(name = "parentFirstName", referencedColumnName = "firstName")
+ })
+ public Parent parent;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Color.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Color.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Color.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,37 @@
+//$Id: Color.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.manytoone;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * Color showing a surrogate key and a unique constraint to ensure business rule
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Color {
+ private Integer id;
+ private String name;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ @Column(unique = true)
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Customer.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Customer.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Customer.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,16 @@
+//$Id: Customer.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.manytoone;
+
+import java.io.Serializable;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity(name="DealedCustomer")
+public class Customer implements Serializable {
+ @Id @GeneratedValue public Integer id;
+ public String userId;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Deal.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Deal.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Deal.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,19 @@
+//$Id: Deal.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.manytoone;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.GeneratedValue;
+import javax.persistence.ManyToOne;
+import javax.persistence.JoinColumn;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Deal {
+ @Id @GeneratedValue public Integer id;
+ @ManyToOne @JoinColumn(referencedColumnName = "userId") public Customer from;
+ @ManyToOne @JoinColumn(referencedColumnName = "userId") public Customer to;
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/DistrictUser.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/DistrictUser.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/DistrictUser.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,43 @@
+package org.hibernate.test.annotations.manytoone;
+
+import java.util.Date;
+import javax.persistence.CascadeType;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinColumns;
+import javax.persistence.ManyToOne;
+import javax.persistence.Table;
+
+@Entity
+@Table(name = "CLRUS2DI")
+public class DistrictUser {
+ @Id
+ @GeneratedValue
+ @Column(name = "CLRUS2DI_KEY")
+ private Long id;
+
+ @Column(name = "CLRUS2DI_CREATE_USERS_KEY")
+ private Long createdBy;
+
+ @Column(name = "CLRUS2DI_CREATE_DATE")
+ private Date createdOn;
+
+ //@ManyToOne(cascade = CascadeType.ALL)
+ //@JoinColumn(name = "CLRUS2DI_DISTR_KEY")
+ //private District district;
+
+ @ManyToOne(cascade = CascadeType.ALL)
+ @JoinColumns({@JoinColumn(name = "CLRUS2DI_USERS_KEY", referencedColumnName = "CTVUSERS_KEY"),
+ @JoinColumn(name = "CLRUS2DI_BEGIN_DATE", referencedColumnName = "CTVUSERS_START_DATE"),
+ @JoinColumn(name = "CLRUS2DI_END_DATE", referencedColumnName = "CTVUSERS_END_DATE")})
+ private User user;
+
+ @Column(name = "CLRUS2DI_LDTMD_KEY")
+ private Long ldtmd;
+
+ @Column(name = "CLRUS2DI_PMTMP_KEY")
+ private Long pmtmp;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/ForestType.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/ForestType.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/ForestType.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,66 @@
+//$Id: ForestType.java 15074 2008-08-14 17:38:00Z epbernard $
+package org.hibernate.test.annotations.manytoone;
+
+import java.util.Set;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.OneToMany;
+import javax.persistence.OneToOne;
+import javax.persistence.JoinTable;
+import javax.persistence.JoinColumn;
+
+import org.hibernate.annotations.ForeignKey;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class ForestType {
+ private Integer id;
+ private String name;
+ private Set<TreeType> trees;
+ private BiggestForest biggestRepresentative;
+
+ @OneToOne
+ @JoinTable(name="BiggestRepPerForestType",
+ joinColumns = @JoinColumn(name="forest_type"),
+ inverseJoinColumns = @JoinColumn(name="forest")
+ )
+ @ForeignKey(name="A_TYP_FK",
+ inverseName = "A_FOR_FK" //inverse fail cause it involves a Join
+ )
+ public BiggestForest getBiggestRepresentative() {
+ return biggestRepresentative;
+ }
+
+ public void setBiggestRepresentative(BiggestForest biggestRepresentative) {
+ this.biggestRepresentative = biggestRepresentative;
+ }
+
+ @OneToMany(mappedBy="forestType")
+ public Set<TreeType> getTrees() {
+ return trees;
+ }
+
+ public void setTrees(Set<TreeType> trees) {
+ this.trees = trees;
+ }
+
+ @Id @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Frame.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Frame.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Frame.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,51 @@
+//$Id: Frame.java 17529 2009-09-19 19:59:46Z stliu $
+package org.hibernate.test.annotations.manytoone;
+
+import java.util.Set;
+import java.io.Serializable;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.OneToMany;
+
+import org.hibernate.annotations.Formula;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Frame implements Serializable {
+ @Id
+ @GeneratedValue
+ private Long id;
+ @OneToMany( mappedBy = "frame" )
+ private Set<Lens> lenses;
+ private String name;
+ @Formula("lower(name)")
+ private String lowerName;
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public Set<Lens> getLenses() {
+ return lenses;
+ }
+
+ public void setLenses(Set<Lens> lenses) {
+ this.lenses = lenses;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Lens.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Lens.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Lens.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,58 @@
+//$Id: Lens.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.manytoone;
+
+import javax.persistence.Entity;
+import javax.persistence.ManyToOne;
+import javax.persistence.JoinColumn;
+import javax.persistence.Id;
+import javax.persistence.GeneratedValue;
+
+import org.hibernate.annotations.Formula;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Lens {
+ @Id
+ @GeneratedValue
+ private Long id;
+ private float focal;
+ @Formula("(1/focal)")
+ private float length;
+ @ManyToOne()
+ @JoinColumn(name="`frame_fk`", referencedColumnName = "name")
+ private Frame frame;
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public float getFocal() {
+ return focal;
+ }
+
+ public void setFocal(float focal) {
+ this.focal = focal;
+ }
+
+ public float getLength() {
+ return length;
+ }
+
+ public void setLength(float length) {
+ this.length = length;
+ }
+
+ public Frame getFrame() {
+ return frame;
+ }
+
+ public void setFrame(Frame frame) {
+ this.frame = frame;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Lotz.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Lotz.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Lotz.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,101 @@
+//$Id: Lotz.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.manytoone;
+
+import java.util.List;
+import java.io.Serializable;
+import javax.persistence.Entity;
+import javax.persistence.EmbeddedId;
+import javax.persistence.Column;
+import javax.persistence.FetchType;
+import javax.persistence.OneToMany;
+import javax.persistence.CascadeType;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Lotz implements Serializable {
+ @EmbeddedId
+ protected LotzPK lotPK;
+
+ @Column( name = "name", nullable = false )
+ private String name;
+
+ @Column( name = "location", nullable = false )
+ private String location;
+
+ @OneToMany( mappedBy = "lot", fetch = FetchType.LAZY, cascade = CascadeType.ALL )
+ private List<Carz> cars;
+
+ public Lotz() {
+ }
+
+ public List<Carz> getCars() {
+ return this.cars;
+ }
+
+ public void setCars(List<Carz> cars) {
+ this.cars = cars;
+ }
+
+ public String getLocation() {
+ return this.location;
+ }
+
+ public void setLocation(String location) {
+ this.location = location;
+ }
+
+ public LotzPK getLotPK() {
+ return this.lotPK;
+ }
+
+ public void setLotPK(LotzPK lotPK) {
+ this.lotPK = lotPK;
+ }
+
+ public String getName() {
+ return this.name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @Override
+ public int hashCode() {
+ final int PRIME = 31;
+ int result = 1;
+ result = PRIME * result + ( ( this.location == null ) ?
+ 0 :
+ this.location.hashCode() );
+ result = PRIME * result + ( ( this.lotPK == null ) ?
+ 0 :
+ this.lotPK.hashCode() );
+ result = PRIME * result + ( ( this.name == null ) ?
+ 0 :
+ this.name.hashCode() );
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if ( this == obj ) return true;
+ if ( obj == null ) return false;
+ if ( getClass() != obj.getClass() ) return false;
+ final Lotz other = (Lotz) obj;
+ if ( this.location == null ) {
+ if ( other.location != null ) return false;
+ }
+ else if ( !this.location.equals( other.location ) ) return false;
+ if ( this.lotPK == null ) {
+ if ( other.lotPK != null ) return false;
+ }
+ else if ( !this.lotPK.equals( other.lotPK ) ) return false;
+ if ( this.name == null ) {
+ if ( other.name != null ) return false;
+ }
+ else if ( !this.name.equals( other.name ) ) return false;
+ return true;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/LotzPK.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/LotzPK.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/LotzPK.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,34 @@
+//$Id: LotzPK.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.manytoone;
+
+import java.io.Serializable;
+import javax.persistence.Column;
+import javax.persistence.Embeddable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Embeddable
+public class LotzPK implements Serializable {
+ @Column( name = "id", nullable = false )
+ private Integer id;
+
+ @Column( name = "loc_code", nullable = false, unique = true )
+ private String locCode;
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getLocCode() {
+ return locCode;
+ }
+
+ public void setLocCode(String locCode) {
+ this.locCode = locCode;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/ManyToOneJoinTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/ManyToOneJoinTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/ManyToOneJoinTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,62 @@
+//$Id: ManyToOneJoinTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.manytoone;
+
+import org.hibernate.test.annotations.TestCase;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class ManyToOneJoinTest extends TestCase {
+ public void testManyToOneJoinTable() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ ForestType forest = new ForestType();
+ forest.setName( "Original forest" );
+ s.persist( forest );
+ TreeType tree = new TreeType();
+ tree.setForestType( forest );
+ tree.setAlternativeForestType( forest );
+ tree.setName( "just a tree");
+ s.persist( tree );
+ s.flush();
+ s.clear();
+ tree = (TreeType) s.get(TreeType.class, tree.getId() );
+ assertNotNull( tree.getForestType() );
+ assertNotNull( tree.getAlternativeForestType() );
+ s.clear();
+ forest = (ForestType) s.get( ForestType.class, forest.getId() );
+ assertEquals( 1, forest.getTrees().size() );
+ assertEquals( tree.getId(), forest.getTrees().iterator().next().getId() );
+ tx.rollback();
+ s.close();
+ }
+
+ public void testOneToOneJoinTable() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ ForestType forest = new ForestType();
+ forest.setName( "Original forest" );
+ s.persist( forest );
+ BiggestForest forestRepr = new BiggestForest();
+ forestRepr.setType( forest );
+ forest.setBiggestRepresentative( forestRepr );
+ s.persist( forestRepr );
+ s.flush();
+ s.clear();
+ forest = (ForestType) s.get( ForestType.class, forest.getId() );
+ assertNotNull( forest.getBiggestRepresentative() );
+ assertEquals( forest, forest.getBiggestRepresentative().getType() );
+ tx.rollback();
+ s.close();
+ }
+
+ protected Class[] getMappings() {
+ return new Class[] {
+ BiggestForest.class,
+ ForestType.class,
+ TreeType.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/ManyToOneOnNonPkTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/ManyToOneOnNonPkTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/ManyToOneOnNonPkTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,54 @@
+//$Id: ManyToOneOnNonPkTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.manytoone;
+
+import java.util.Date;
+
+import org.hibernate.test.annotations.TestCase;
+import org.hibernate.Session;
+
+
+/**
+ * FIXME test for ANN-548
+ * @author Emmanuel Bernard
+ */
+public class ManyToOneOnNonPkTest extends TestCase {
+
+ public void testNonPkPartOfPk() throws Exception {
+// Session s = openSession( );
+// s.getTransaction().begin();
+//
+// LotzPK pk = new LotzPK();
+// pk.setId( 1 );
+// pk.setLocCode( "fr" );
+// Lotz lot = new Lotz();
+// lot.setLocation( "France" );
+// lot.setName( "Chez Dede" );
+// lot.setLotPK( pk );
+// Carz car = new Carz();
+// car.setId( 1 );
+// car.setLot( lot );
+// car.setMake( "Citroen" );
+// car.setManufactured( new Date() );
+// car.setModel( "C5" );
+// s.persist( lot );
+// s.persist( car );
+//
+// s.flush();
+// s.clear();
+// s.clear();
+//
+// car = (Carz) s.createQuery( "from Carz car left join fetch car.lot").uniqueResult();
+// assertNotNull( car.getLot() );
+//
+// s.getTransaction().commit();
+// s.close();
+//
+ }
+
+ protected Class[] getMappings() {
+ return new Class[] {
+ //Carz.class,
+ //Lotz.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/ManyToOneTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/ManyToOneTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/ManyToOneTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,346 @@
+//$Id: ManyToOneTest.java 17529 2009-09-19 19:59:46Z stliu $
+package org.hibernate.test.annotations.manytoone;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+import org.hibernate.Hibernate;
+import org.hibernate.Query;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.annotations.Company;
+import org.hibernate.test.annotations.Customer;
+import org.hibernate.test.annotations.Discount;
+import org.hibernate.test.annotations.Flight;
+import org.hibernate.test.annotations.Passport;
+import org.hibernate.test.annotations.TestCase;
+import org.hibernate.test.annotations.Ticket;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class ManyToOneTest extends TestCase {
+
+ public ManyToOneTest(String x) {
+ super( x );
+ }
+
+ public void testEager() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Color c = new Color();
+ c.setName( "Yellow" );
+ s.persist( c );
+ Car car = new Car();
+ car.setBodyColor( c );
+ s.persist( car );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ car = (Car) s.get( Car.class, car.getId() );
+ tx.commit();
+ s.close();
+ assertNotNull( car );
+ assertNotNull( car.getBodyColor() );
+ assertEquals( "Yellow", car.getBodyColor().getName() );
+
+ }
+
+ public void testDefaultMetadata() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Color c = new Color();
+ c.setName( "Blue" );
+ s.persist( c );
+ Car car = new Car();
+ car.setBodyColor( c );
+ s.persist( car );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ car = (Car) s.get( Car.class, car.getId() );
+ assertNotNull( car );
+ assertNotNull( car.getBodyColor() );
+ assertEquals( c.getId(), car.getBodyColor().getId() );
+ tx.rollback();
+ s.close();
+ }
+
+ public void testCreate() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Flight firstOne = new Flight();
+ firstOne.setId( new Long( 1 ) );
+ firstOne.setName( "AF0101" );
+ firstOne.setDuration( new Long( 1000 ) );
+ Company frenchOne = new Company();
+ frenchOne.setName( "Air France" );
+ firstOne.setCompany( frenchOne );
+ s.persist( firstOne );
+ tx.commit();
+ s.close();
+ assertNotNull( "identity id should work", frenchOne.getId() );
+
+ s = openSession();
+ tx = s.beginTransaction();
+ firstOne = (Flight) s.get( Flight.class, new Long( 1 ) );
+ assertNotNull( firstOne.getCompany() );
+ assertEquals( frenchOne.getName(), firstOne.getCompany().getName() );
+ tx.commit();
+ s.close();
+ }
+
+ public void testCascade() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Discount discount = new Discount();
+ discount.setDiscount( 20.12 );
+ Customer customer = new Customer();
+ Collection discounts = new ArrayList();
+ discounts.add( discount );
+ customer.setName( "Quentin Tarantino" );
+ discount.setOwner( customer );
+ customer.setDiscountTickets( discounts );
+ s.persist( discount );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ discount = (Discount) s.get( Discount.class, discount.getId() );
+ assertNotNull( discount );
+ assertEquals( 20.12, discount.getDiscount() );
+ assertNotNull( discount.getOwner() );
+ customer = new Customer();
+ customer.setName( "Clooney" );
+ discount.setOwner( customer );
+ discounts = new ArrayList();
+ discounts.add( discount );
+ customer.setDiscountTickets( discounts );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ discount = (Discount) s.get( Discount.class, discount.getId() );
+ assertNotNull( discount );
+ assertNotNull( discount.getOwner() );
+ assertEquals( "Clooney", discount.getOwner().getName() );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ customer = (Customer) s.get( Customer.class, customer.getId() );
+ s.delete( customer );
+ tx.commit();
+ s.close();
+ }
+
+ public void testFetch() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Discount discount = new Discount();
+ discount.setDiscount( 20 );
+ Customer customer = new Customer();
+ Collection discounts = new ArrayList();
+ discounts.add( discount );
+ customer.setName( "Quentin Tarantino" );
+ discount.setOwner( customer );
+ customer.setDiscountTickets( discounts );
+ s.persist( discount );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ discount = (Discount) s.get( Discount.class, discount.getId() );
+ assertNotNull( discount );
+ assertFalse( Hibernate.isInitialized( discount.getOwner() ) );
+ tx.commit();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ discount = (Discount) s.load( Discount.class, discount.getId() );
+ assertNotNull( discount );
+ assertFalse( Hibernate.isInitialized( discount.getOwner() ) );
+ tx.commit();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ s.delete( s.get( Discount.class, discount.getId() ) );
+ tx.commit();
+ s.close();
+ }
+
+ public void testCompositeFK() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ ParentPk ppk = new ParentPk();
+ ppk.firstName = "John";
+ ppk.lastName = "Doe";
+ Parent p = new Parent();
+ p.age = 45;
+ p.id = ppk;
+ s.persist( p );
+ Child c = new Child();
+ c.parent = p;
+ s.persist( c );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ //FIXME: fix this when the small parser bug will be fixed
+ Query q = s.createQuery( "from " + Child.class.getName() ); //+ " c where c.parent.id.lastName = :lastName");
+ //q.setString("lastName", p.id.lastName);
+ List result = q.list();
+ assertEquals( 1, result.size() );
+ Child c2 = (Child) result.get( 0 );
+ assertEquals( c2.id, c.id );
+ tx.commit();
+ s.close();
+ }
+
+ public void testImplicitCompositeFk() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Node n1 = new Node();
+ n1.setDescription( "Parent" );
+ NodePk n1pk = new NodePk();
+ n1pk.setLevel( 1 );
+ n1pk.setName( "Root" );
+ n1.setId( n1pk );
+ Node n2 = new Node();
+ NodePk n2pk = new NodePk();
+ n2pk.setLevel( 2 );
+ n2pk.setName( "Level 1: A" );
+ n2.setParent( n1 );
+ n2.setId( n2pk );
+ s.persist( n2 );
+ tx.commit();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ n2 = (Node) s.get( Node.class, n2pk );
+ assertNotNull( n2 );
+ assertNotNull( n2.getParent() );
+ assertEquals( 1, n2.getParent().getId().getLevel() );
+ tx.commit();
+ s.close();
+ }
+
+ public void testManyToOneNonPk() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Order order = new Order();
+ order.setOrderNbr( "123" );
+ s.persist( order );
+ OrderLine ol = new OrderLine();
+ ol.setItem( "Mouse" );
+ ol.setOrder( order );
+ s.persist( ol );
+ s.flush();
+ s.clear();
+ ol = (OrderLine) s.get( OrderLine.class, ol.getId() );
+ assertNotNull( ol.getOrder() );
+ assertEquals( "123", ol.getOrder().getOrderNbr() );
+ assertTrue( ol.getOrder().getOrderLines().contains( ol ) );
+ tx.rollback();
+ s.close();
+ }
+
+ public void testTwoManyToOneNonPk() throws Exception {
+ //2 many to one non pk pointing to the same referencedColumnName should not fail
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ org.hibernate.test.annotations.manytoone.Customer customer = new org.hibernate.test.annotations.manytoone.Customer();
+ customer.userId="123";
+ org.hibernate.test.annotations.manytoone.Customer customer2 = new org.hibernate.test.annotations.manytoone.Customer();
+ customer2.userId="124";
+ s.persist( customer2 );
+ s.persist( customer );
+ Deal deal = new Deal();
+ deal.from = customer;
+ deal.to = customer2;
+ s.persist( deal );
+ s.flush();
+ s.clear();
+ deal = (Deal) s.get( Deal.class, deal.id );
+ assertNotNull( deal.from );
+ assertNotNull( deal.to );
+ tx.rollback();
+ s.close();
+ }
+
+ public void testFormulaOnOtherSide() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Frame frame = new Frame();
+ frame.setName( "Prada" );
+ s.persist( frame );
+ Lens l = new Lens();
+ l.setFocal( 2.5f );
+ l.setFrame( frame );
+ s.persist( l );
+ Lens r = new Lens();
+ r.setFocal( 1.2f);
+ r.setFrame( frame );
+ s.persist( r );
+ s.flush();
+ s.clear();
+ frame = (Frame) s.get( Frame.class, frame.getId() );
+ assertEquals( 2, frame.getLenses().size() );
+ assertTrue( frame.getLenses().iterator().next().getLength() <= 1/1.2f );
+ assertTrue( frame.getLenses().iterator().next().getLength() >= 1/2.5f );
+ tx.rollback();
+ s.close();
+ }
+
+ /**
+ * @see org.hibernate.test.annotations.TestCase#getMappings()
+ */
+ protected java.lang.Class[] getMappings() {
+ return new java.lang.Class[]{
+ Deal.class,
+ org.hibernate.test.annotations.manytoone.Customer.class,
+ Car.class,
+ Color.class,
+ Flight.class,
+ Company.class,
+ Customer.class,
+ Discount.class,
+ Ticket.class,
+ Passport.class,
+ Parent.class,
+ Child.class,
+ Node.class,
+ User.class,
+ DistrictUser.class,
+ Order.class,
+ OrderLine.class,
+ Frame.class,
+ Lens.class
+ };
+ }
+
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Node.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Node.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Node.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,68 @@
+//$Id: Node.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.manytoone;
+
+import java.io.Serializable;
+import javax.persistence.CascadeType;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinColumns;
+import javax.persistence.ManyToOne;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Node implements Serializable {
+
+ private NodePk id;
+ private String description;
+ private Node parent;
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( !( o instanceof Node ) ) return false;
+
+ final Node node = (Node) o;
+
+ if ( !id.equals( node.id ) ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ return id.hashCode();
+ }
+
+ @Id
+ public NodePk getId() {
+ return id;
+ }
+
+ public void setId(NodePk id) {
+ this.id = id;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
+ @JoinColumns({
+ @JoinColumn(name = "parentName"),
+ @JoinColumn(name = "parentLevel")
+ })
+ public Node getParent() {
+ return parent;
+ }
+
+ public void setParent(Node parent) {
+ this.parent = parent;
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/NodePk.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/NodePk.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/NodePk.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,51 @@
+//$Id: NodePk.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.manytoone;
+
+import java.io.Serializable;
+import javax.persistence.Column;
+import javax.persistence.Embeddable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Embeddable
+public class NodePk implements Serializable {
+ private String name;
+ private int level;
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( !( o instanceof NodePk ) ) return false;
+
+ final NodePk nodePk = (NodePk) o;
+
+ if ( level != nodePk.level ) return false;
+ if ( !name.equals( nodePk.name ) ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ int result;
+ result = name.hashCode();
+ result = 29 * result + level;
+ return result;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @Column(name = "fld_lvl")
+ public int getLevel() {
+ return level;
+ }
+
+ public void setLevel(int level) {
+ this.level = level;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Order.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Order.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Order.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,50 @@
+//$Id: Order.java 17529 2009-09-19 19:59:46Z stliu $
+package org.hibernate.test.annotations.manytoone;
+
+import java.io.Serializable;
+import java.util.Set;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.Column;
+import javax.persistence.Table;
+import javax.persistence.OneToMany;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Table(name="ORDERS")
+public class Order implements Serializable {
+ private Integer id;
+ private String orderNbr;
+ private Set<OrderLine> orderLines;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ @Column(name="order_nbr")
+ public String getOrderNbr() {
+ return orderNbr;
+ }
+
+ public void setOrderNbr(String orderNbr) {
+ this.orderNbr = orderNbr;
+ }
+
+ @OneToMany(mappedBy = "order")
+ public Set<OrderLine> getOrderLines() {
+ return orderLines;
+ }
+
+ public void setOrderLines(Set<OrderLine> orderLines) {
+ this.orderLines = orderLines;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/OrderLine.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/OrderLine.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/OrderLine.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,45 @@
+//$Id: OrderLine.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.manytoone;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.GeneratedValue;
+import javax.persistence.ManyToOne;
+import javax.persistence.JoinColumn;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class OrderLine {
+ private Integer id;
+ private String item;
+ private Order order;
+
+ @Id @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getItem() {
+ return item;
+ }
+
+ public void setItem(String item) {
+ this.item = item;
+ }
+
+ @ManyToOne
+ @JoinColumn(name="order_nbr", referencedColumnName = "order_nbr", unique = true)
+ public Order getOrder() {
+ return order;
+ }
+
+ public void setOrder(Order order) {
+ this.order = order;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Parent.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Parent.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/Parent.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,33 @@
+//$Id: Parent.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.manytoone;
+
+import java.io.Serializable;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Table(name = "tbl_parent")
+public class Parent implements Serializable {
+ @Id
+ public ParentPk id;
+ public int age;
+
+ public int hashCode() {
+ //a NPE can occurs, but I don't expect hashcode to be used before pk is set
+ return id.hashCode();
+ }
+
+ public boolean equals(Object obj) {
+ //a NPE can occurs, but I don't expect equals to be used before pk is set
+ if ( obj != null && obj instanceof Parent ) {
+ return id.equals( ( (Parent) obj ).id );
+ }
+ else {
+ return false;
+ }
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/ParentPk.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/ParentPk.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/ParentPk.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,40 @@
+//$Id: ParentPk.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.manytoone;
+
+import java.io.Serializable;
+import javax.persistence.Column;
+import javax.persistence.Embeddable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Embeddable
+public class ParentPk implements Serializable {
+ @Column(length = 50)
+ String firstName;
+ String lastName;
+
+ /**
+ * is a male or a female
+ */
+ //show hetereogenous PK types
+ boolean isMale;
+
+ public int hashCode() {
+ //this implem sucks
+ return firstName.hashCode() + lastName.hashCode() + ( isMale ? 0 : 1 );
+ }
+
+ public boolean equals(Object obj) {
+ //firstName and lastName are expected to be set in this implem
+ if ( obj != null && obj instanceof ParentPk ) {
+ ParentPk other = (ParentPk) obj;
+ return firstName.equals( other.firstName )
+ && lastName.equals( other.lastName )
+ && isMale == other.isMale;
+ }
+ else {
+ return false;
+ }
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/TreeType.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/TreeType.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/TreeType.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,61 @@
+//$Id: TreeType.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.manytoone;
+
+import javax.persistence.Entity;
+import javax.persistence.ManyToOne;
+import javax.persistence.JoinTable;
+import javax.persistence.Id;
+import javax.persistence.GeneratedValue;
+import javax.persistence.JoinColumn;
+import javax.persistence.FetchType;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class TreeType {
+ private Integer id;
+ private String name;
+ private ForestType forestType;
+ private ForestType alternativeForestType;
+
+ @ManyToOne(fetch = FetchType.LAZY)
+ @JoinTable(name="Tree_Forest")
+ public ForestType getForestType() {
+ return forestType;
+ }
+
+ public void setForestType(ForestType forestType) {
+ this.forestType = forestType;
+ }
+
+ @ManyToOne(fetch = FetchType.LAZY)
+ @JoinTable(name="Atl_Forest_Type",
+ joinColumns = @JoinColumn(name="tree_id"),
+ inverseJoinColumns = @JoinColumn(name="forest_id") )
+ public ForestType getAlternativeForestType() {
+ return alternativeForestType;
+ }
+
+ public void setAlternativeForestType(ForestType alternativeForestType) {
+ this.alternativeForestType = alternativeForestType;
+ }
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/User.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/User.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/User.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,113 @@
+package org.hibernate.test.annotations.manytoone;
+
+import java.util.Date;
+import java.util.Set;
+import javax.persistence.CascadeType;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.Id;
+import javax.persistence.IdClass;
+import javax.persistence.OneToMany;
+import javax.persistence.SequenceGenerator;
+import javax.persistence.Table;
+
+@Entity
+@Table(name = "CTVUSERS")
+(a)IdClass(UserPK.class)
+@SequenceGenerator(name = "UserSeq", sequenceName = "SQ_USER")
+public class User {
+ @Id
+ @Column(name = "CTVUSERS_KEY")
+ private Long userKey;
+
+ @Id
+ @Column(name = "CTVUSERS_START_DATE")
+ private Date startDate;
+
+ @Id
+ @Column(name = "CTVUSERS_END_DATE")
+ private Date endDate;
+
+ @Column(name = "CTVUSERS_CREATE_USERS_KEY")
+ private Long createdBy;
+
+ @Column(name = "CTVUSERS_CREATE_DATE")
+ private Date createdOn;
+
+ @Column(name = "CTVUSERS_ID")
+ private String userId;
+
+ @Column(name = "CTVUSERS_PREFX_KEY")
+ private Integer prefix;
+
+ @Column(name = "CTVUSERS_FIRST_NAME")
+ private String firstName;
+
+ @Column(name = "CTVUSERS_LAST_NAME1")
+ private String lastName1;
+
+ @Column(name = "CTVUSERS_LAST_NAME2")
+ private String lastName2;
+
+ @Column(name = "CTVUSERS_MIDDLE_NAME1")
+ private String middleName1;
+
+ @Column(name = "CTVUSERS_MIDDLE_NAME2")
+ private String middleName2;
+
+ @Column(name = "CTVUSERS_SUFFX_KEY")
+ private Integer suffix;
+
+ @Column(name = "CTVUSERS_BIRTH_DATE")
+ private Date birthDate;
+
+ @Column(name = "CTVUSERS_BIRTH_STATE_KEY")
+ private Integer birthState;
+
+ @Column(name = "CTVUSERS_BIRTH_CNTRY_KEY")
+ private Integer birthCountry;
+
+ @Column(name = "CTVUSERS_USERNAME")
+ private String username;
+
+ @Column(name = "CTVUSERS_PASSWORD")
+ private String password;
+
+ @Column(name = "CTVUSERS_LOTYP_KEY")
+ private Integer userType;
+
+ @Column(name = "CTVUSERS_PRIVL_KEY")
+ private Integer privilege;
+
+ @Column(name = "CTVUSERS_STATE_KEY")
+ private Integer state;
+
+ @Column(name = "CTVUSERS_CNTRY_KEY")
+ private Integer country;
+
+ @Column(name = "CTVUSERS_PREFERRED_NAME")
+ private String preferredName;
+
+ @Column(name = "CTVUSERS_BIRTH_PLACE")
+ private String birthPlace;
+
+ @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "user")
+ private Set<DistrictUser> districtUsers;
+
+ @Column(name = "CTVUSERS_SCHOL_KEY")
+ private Long school;
+
+ @Column(name = "CTVUSERS_CLSTR_KEY")
+ private Long cluster;
+
+ @Column(name = "CTVUSERS_LDTMM_KEY")
+ private Long ldtmm;
+
+ @Column(name = "CTVUSERS_LDTMD_KEY")
+ private Long ldtmd;
+
+ @Column(name = "CTVUSERS_PMTMP_KEY")
+ private Long pmtmp;
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/UserPK.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/UserPK.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/UserPK.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,39 @@
+package org.hibernate.test.annotations.manytoone;
+
+import java.io.Serializable;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import javax.persistence.Column;
+
+public class UserPK implements Serializable {
+ private static final long serialVersionUID = -7720874756224520523L;
+ @Column(name = "CTVUSERS_KEY")
+ public Long userKey;
+
+ @Column(name = "CTVUSERS_START_DATE")
+ public Date startDate;
+
+
+ @Column(name = "CTVUSERS_END_DATE")
+ public Date endDate;
+
+ public UserPK() {
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if ( !( obj instanceof UserPK ) ) {
+ return false;
+ }
+ UserPK userPK = (UserPK) obj;
+ SimpleDateFormat formatter = new SimpleDateFormat( "MM/dd/yyyy" );
+ return userKey.equals( userPK.userKey ) && formatter.format( startDate )
+ .equals( formatter.format( userPK.startDate ) )
+ && formatter.format( endDate ).equals( formatter.format( userPK.endDate ) );
+ }
+
+ @Override
+ public int hashCode() {
+ return userKey.hashCode() * startDate.hashCode() * endDate.hashCode();
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/referencedcolumnname/GenericObject.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/referencedcolumnname/GenericObject.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/referencedcolumnname/GenericObject.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,68 @@
+//$
+package org.hibernate.test.annotations.manytoone.referencedcolumnname;
+
+import java.io.Serializable;
+import java.rmi.server.UID;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.MappedSuperclass;
+import javax.persistence.Transient;
+import javax.persistence.Version;
+
+@MappedSuperclass
+public class GenericObject implements Serializable {
+ protected int id;
+ protected int version;
+ protected UID uid = new UID();
+
+ @Id
+ @GeneratedValue( strategy = GenerationType.IDENTITY )
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ @Version
+ public int getVersion() {
+ return version;
+ }
+
+ public void setVersion(int version) {
+ this.version = version;
+ }
+
+ public void incrementVersion() {
+ this.version++;
+ }
+
+ public boolean equals(Object other) {
+ if ( this == other )
+ return true;
+ if ( ( other == null ) || !( other.getClass().equals( this.getClass() ) ) )
+ return false;
+ GenericObject anObject = (GenericObject) other;
+ if ( this.id == 0 || anObject.id == 0 )
+ return false;
+
+ return ( this.id == anObject.id );
+ }
+
+ public int hashCode() {
+ if ( this.id == 0 )
+ return super.hashCode();
+ return this.id;
+ }
+
+ @Transient
+ public UID getUid() {
+ return uid;
+ }
+
+ public void setUid(UID uid) {
+ this.uid = uid;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/referencedcolumnname/Item.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/referencedcolumnname/Item.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/referencedcolumnname/Item.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,13 @@
+//$
+package org.hibernate.test.annotations.manytoone.referencedcolumnname;
+
+import java.util.HashSet;
+import java.util.Set;
+import javax.persistence.Entity;
+import javax.persistence.OneToMany;
+import javax.persistence.Transient;
+
+
+@Entity
+public class Item extends GenericObject {
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/referencedcolumnname/ManyToOneReferencedColumnNameTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/referencedcolumnname/ManyToOneReferencedColumnNameTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/referencedcolumnname/ManyToOneReferencedColumnNameTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,55 @@
+//$
+package org.hibernate.test.annotations.manytoone.referencedcolumnname;
+
+import java.math.BigDecimal;
+
+import org.hibernate.test.annotations.TestCase;
+import org.hibernate.Session;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class ManyToOneReferencedColumnNameTest extends TestCase {
+ public void testReoverableExceptionInFkOrdering() throws Exception {
+ //SF should not blow up
+ Vendor v = new Vendor();
+ Item i = new Item();
+ ZItemCost ic = new ZItemCost();
+ ic.setCost( new BigDecimal(2) );
+ ic.setItem( i );
+ ic.setVendor( v );
+ WarehouseItem wi = new WarehouseItem();
+ wi.setDefaultCost( ic );
+ wi.setItem( i );
+ wi.setVendor( v );
+ wi.setQtyInStock( new BigDecimal(2) );
+ Session s = openSession( );
+ s.getTransaction().begin();
+ s.save( i );
+ s.save( v );
+ s.save( ic );
+ s.save( wi );
+ s.flush();
+ s.getTransaction().rollback();
+ s.close();
+
+ }
+
+
+
+ @Override
+ protected boolean runForCurrentDialect() {
+ return super.runForCurrentDialect() && getDialect().supportsIdentityColumns();
+ }
+
+
+
+ protected Class[] getMappings() {
+ return new Class[] {
+ Item.class,
+ Vendor.class,
+ WarehouseItem.class,
+ ZItemCost.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/referencedcolumnname/Vendor.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/referencedcolumnname/Vendor.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/referencedcolumnname/Vendor.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,12 @@
+//$
+package org.hibernate.test.annotations.manytoone.referencedcolumnname;
+
+import java.util.HashSet;
+import java.util.Set;
+import javax.persistence.Entity;
+import javax.persistence.OneToMany;
+import javax.persistence.Transient;
+
+@Entity
+public class Vendor extends GenericObject {
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/referencedcolumnname/WarehouseItem.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/referencedcolumnname/WarehouseItem.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/referencedcolumnname/WarehouseItem.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,62 @@
+//$
+package org.hibernate.test.annotations.manytoone.referencedcolumnname;
+
+import java.math.BigDecimal;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinColumns;
+import javax.persistence.ManyToOne;
+
+@Entity
+public class WarehouseItem extends GenericObject {
+
+
+ Item item;
+ Vendor vendor;
+ ZItemCost defaultCost;
+ BigDecimal qtyInStock;
+
+
+ public BigDecimal getQtyInStock() {
+ return qtyInStock;
+ }
+
+ public void setQtyInStock(BigDecimal qtyInStock) {
+ this.qtyInStock = qtyInStock;
+ }
+
+ @ManyToOne
+//(fetch=FetchType.LAZY)
+ @JoinColumn( name = "ITEM_ID", unique = false, nullable = false, insertable = true, updatable = true )
+ public Item getItem() {
+ return item;
+ }
+
+ public void setItem(Item item) {
+ this.item = item;
+ }
+
+ @ManyToOne( fetch = FetchType.LAZY )
+ @JoinColumn( name = "VENDOR_ID", unique = false, nullable = false, insertable = true, updatable = true )
+ public Vendor getVendor() {
+ return vendor;
+ }
+
+ public void setVendor(Vendor vendor) {
+ this.vendor = vendor;
+ }
+
+ @ManyToOne
+ @JoinColumns( {
+ @JoinColumn( name = "vendor_id", referencedColumnName = "vendor_id", insertable = false, updatable = false ),
+ @JoinColumn( name = "item_id", referencedColumnName = "item_id", insertable = false, updatable = false )
+ } )
+ public ZItemCost getDefaultCost() {
+ return defaultCost;
+ }
+
+ public void setDefaultCost(ZItemCost defaultCost) {
+ this.defaultCost = defaultCost;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/referencedcolumnname/ZItemCost.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/referencedcolumnname/ZItemCost.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/manytoone/referencedcolumnname/ZItemCost.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,46 @@
+//$
+package org.hibernate.test.annotations.manytoone.referencedcolumnname;
+
+import java.math.BigDecimal;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.ManyToOne;
+import javax.persistence.Transient;
+import javax.persistence.JoinColumn;
+
+@Entity
+public class ZItemCost extends GenericObject {
+
+ Item item;
+ Vendor vendor;
+ BigDecimal cost;
+
+ @ManyToOne( fetch = FetchType.LAZY )
+ //@JoinColumn(name="ITEM_ID", unique=false, nullable=false, insertable=true, updatable=true)
+ public Item getItem() {
+ return item;
+ }
+
+ public void setItem(Item item) {
+ this.item = item;
+ }
+
+ @ManyToOne( fetch = FetchType.LAZY )
+ //@JoinColumn(name="VENDOR_ID", unique=false, nullable=false, insertable=true, updatable=true)
+ public Vendor getVendor() {
+ return vendor;
+ }
+
+ public void setVendor(Vendor vendor) {
+ this.vendor = vendor;
+ }
+
+ public BigDecimal getCost() {
+ return cost;
+ }
+
+ public void setCost(BigDecimal cost) {
+ this.cost = cost;
+ }
+}
+
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/namingstrategy/Address.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/namingstrategy/Address.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/namingstrategy/Address.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,34 @@
+// $Id: Address.java 14741 2008-06-05 11:25:56Z hardy.ferentschik $
+package org.hibernate.test.annotations.namingstrategy;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.JoinTable;
+import javax.persistence.ManyToOne;
+
+@Entity
+public class Address {
+
+ @Id
+ private long id;
+
+ @ManyToOne
+ @JoinTable(name = "person_address")
+ private Person person;
+
+ public long getId() {
+ return id;
+ }
+
+ public void setId(long id) {
+ this.id = id;
+ }
+
+ public Person getPerson() {
+ return person;
+ }
+
+ public void setPerson(Person person) {
+ this.person = person;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/namingstrategy/DummyNamingStrategy.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/namingstrategy/DummyNamingStrategy.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/namingstrategy/DummyNamingStrategy.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,13 @@
+// $Id: DummyNamingStrategy.java 14741 2008-06-05 11:25:56Z hardy.ferentschik $
+package org.hibernate.test.annotations.namingstrategy;
+
+import org.hibernate.cfg.EJB3NamingStrategy;
+
+@SuppressWarnings("serial")
+public class DummyNamingStrategy extends EJB3NamingStrategy {
+
+ public String tableName(String tableName) {
+ return "T" + tableName;
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/namingstrategy/NamingStrategyTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/namingstrategy/NamingStrategyTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/namingstrategy/NamingStrategyTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,52 @@
+// $Id: NamingStrategyTest.java 14741 2008-06-05 11:25:56Z hardy.ferentschik $
+package org.hibernate.test.annotations.namingstrategy;
+
+import java.io.PrintWriter;
+import java.io.StringWriter;
+
+import junit.framework.TestCase;
+
+import org.hibernate.cfg.AnnotationConfiguration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Test harness for ANN-716.
+ *
+ * @author Hardy Ferentschik
+ */
+public class NamingStrategyTest extends TestCase {
+
+ private Logger log = LoggerFactory.getLogger(NamingStrategyTest.class);
+
+ public void testWithCustomNamingStrategy() throws Exception {
+ try {
+ AnnotationConfiguration config = new AnnotationConfiguration();
+ config.setNamingStrategy(new DummyNamingStrategy());
+ config.addAnnotatedClass(Address.class);
+ config.addAnnotatedClass(Person.class);
+ config.buildSessionFactory();
+ }
+ catch( Exception e ) {
+ StringWriter writer = new StringWriter();
+ e.printStackTrace(new PrintWriter(writer));
+ log.debug(writer.toString());
+ fail(e.getMessage());
+ }
+ }
+
+ public void testWithoutCustomNamingStrategy() throws Exception {
+ try {
+ AnnotationConfiguration config = new AnnotationConfiguration();
+ config.addAnnotatedClass(Address.class);
+ config.addAnnotatedClass(Person.class);
+ config.buildSessionFactory();
+ }
+ catch( Exception e ) {
+ StringWriter writer = new StringWriter();
+ e.printStackTrace(new PrintWriter(writer));
+ log.debug(writer.toString());
+ fail(e.getMessage());
+ }
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/namingstrategy/Person.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/namingstrategy/Person.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/namingstrategy/Person.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,35 @@
+// $Id: Person.java 14741 2008-06-05 11:25:56Z hardy.ferentschik $
+package org.hibernate.test.annotations.namingstrategy;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.OneToMany;
+
+@Entity
+public class Person {
+
+ @Id
+ private long id;
+
+ @OneToMany(mappedBy = "person")
+ private Set<Address> addresses = new HashSet<Address>();
+
+ public long getId() {
+ return id;
+ }
+
+ public void setId(long id) {
+ this.id = id;
+ }
+
+ public Set<Address> getAddresses() {
+ return addresses;
+ }
+
+ public void setAddresses(Set<Address> addresses) {
+ this.addresses = addresses;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/naturalid/Citizen.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/naturalid/Citizen.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/naturalid/Citizen.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,67 @@
+//$Id: Citizen.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.naturalid;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.ManyToOne;
+
+import org.hibernate.annotations.NaturalId;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Citizen {
+ @Id
+ @GeneratedValue
+ private Integer id;
+ private String firstname;
+ private String lastname;
+ @NaturalId
+ @ManyToOne
+ private State state;
+ @NaturalId
+ private String ssn;
+
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getFirstname() {
+ return firstname;
+ }
+
+ public void setFirstname(String firstname) {
+ this.firstname = firstname;
+ }
+
+ public String getLastname() {
+ return lastname;
+ }
+
+ public void setLastname(String lastname) {
+ this.lastname = lastname;
+ }
+
+ public State getState() {
+ return state;
+ }
+
+ public void setState(State state) {
+ this.state = state;
+ }
+
+ public String getSsn() {
+ return ssn;
+ }
+
+ public void setSsn(String ssn) {
+ this.ssn = ssn;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/naturalid/NaturalIdOnManyToOne.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/naturalid/NaturalIdOnManyToOne.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/naturalid/NaturalIdOnManyToOne.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,42 @@
+package org.hibernate.test.annotations.naturalid;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.ManyToOne;
+
+import org.hibernate.annotations.NaturalId;
+
+@Entity
+/**
+ * Test case for NaturalId annotation - ANN-750
+ *
+ * @author Emmanuel Bernard
+ * @author Hardy Ferentschik
+ */
+class NaturalIdOnManyToOne {
+
+ @Id
+ @GeneratedValue
+ int id;
+
+ @NaturalId
+ @ManyToOne
+ Citizen citizen;
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ public Citizen getCitizen() {
+ return citizen;
+ }
+
+ public void setCitizen(Citizen citizen) {
+ this.citizen = citizen;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/naturalid/NaturalIdOnSingleManyToOneTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/naturalid/NaturalIdOnSingleManyToOneTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/naturalid/NaturalIdOnSingleManyToOneTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,95 @@
+//$Id: NaturalIdOnSingleManyToOneTest.java 14786 2008-06-19 14:59:11Z hardy.ferentschik $
+package org.hibernate.test.annotations.naturalid;
+
+import java.util.List;
+
+import org.hibernate.Criteria;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.criterion.Restrictions;
+import org.hibernate.metadata.ClassMetadata;
+import org.hibernate.stat.Statistics;
+import org.hibernate.test.annotations.TestCase;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Test case for NaturalId annotation. See ANN-750.
+ *
+ * @author Emmanuel Bernard
+ * @author Hardy Ferentschik
+ */
+@SuppressWarnings("unchecked")
+public class NaturalIdOnSingleManyToOneTest extends TestCase {
+
+ private Logger log = LoggerFactory.getLogger(NaturalIdOnManyToOne.class);
+
+ public void testMappingProperties() {
+ log.warn("Commented out test");
+
+ ClassMetadata metaData = getSessions().getClassMetadata(
+ NaturalIdOnManyToOne.class);
+ assertTrue("Class should have a natural key", metaData
+ .hasNaturalIdentifier());
+ int[] propertiesIndex = metaData.getNaturalIdentifierProperties();
+ assertTrue("Wrong number of elements", propertiesIndex.length == 1);
+ }
+
+ public void testManyToOneNaturalIdCached() {
+ NaturalIdOnManyToOne singleManyToOne = new NaturalIdOnManyToOne();
+ Citizen c1 = new Citizen();
+ c1.setFirstname("Emmanuel");
+ c1.setLastname("Bernard");
+ c1.setSsn("1234");
+
+ State france = new State();
+ france.setName("Ile de France");
+ c1.setState(france);
+
+ singleManyToOne.setCitizen(c1);
+
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ s.persist(france);
+ s.persist(c1);
+ s.persist(singleManyToOne);
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ Criteria criteria = s.createCriteria(NaturalIdOnManyToOne.class);
+ criteria.add(Restrictions.naturalId().set("citizen", c1));
+ criteria.setCacheable(true);
+
+ Statistics stats = getSessions().getStatistics();
+ stats.setStatisticsEnabled(true);
+ stats.clear();
+ assertEquals("Cache hits should be empty", 0, stats
+ .getQueryCacheHitCount());
+
+ // first query
+ List results = criteria.list();
+ assertEquals(1, results.size());
+ assertEquals("Cache hits should be empty", 0, stats
+ .getQueryCacheHitCount());
+ assertEquals("First query should be a miss", 1, stats
+ .getQueryCacheMissCount());
+ assertEquals("Query result should be added to cache", 1, stats
+ .getQueryCachePutCount());
+
+ // query a second time - result should be cached
+ results = criteria.list();
+ assertEquals("Cache hits should be empty", 1, stats
+ .getQueryCacheHitCount());
+
+ // cleanup
+ tx.rollback();
+ s.close();
+ }
+
+ protected Class[] getMappings() {
+ return new Class[] { Citizen.class, State.class,
+ NaturalIdOnManyToOne.class };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/naturalid/NaturalIdTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/naturalid/NaturalIdTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/naturalid/NaturalIdTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,137 @@
+//$Id: NaturalIdTest.java 14786 2008-06-19 14:59:11Z hardy.ferentschik $
+package org.hibernate.test.annotations.naturalid;
+
+import java.util.List;
+
+import org.hibernate.Criteria;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.criterion.Restrictions;
+import org.hibernate.metadata.ClassMetadata;
+import org.hibernate.stat.Statistics;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * Test case for NaturalId annotation
+ *
+ * @author Emmanuel Bernard
+ * @author Hardy Ferentschik
+ */
+@SuppressWarnings("unchecked")
+public class NaturalIdTest extends TestCase {
+
+ public void testMappingProperties() {
+ ClassMetadata metaData = getSessions().getClassMetadata(
+ Citizen.class);
+ assertTrue("Class should have a natural key", metaData
+ .hasNaturalIdentifier());
+ int[] propertiesIndex = metaData.getNaturalIdentifierProperties();
+ assertTrue("Wrong number of elements", propertiesIndex.length == 2);
+ }
+
+ public void testNaturalIdCached() {
+ saveSomeCitizens();
+
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ State france = (State) s.load(State.class, new Integer(2));
+ Criteria criteria = s.createCriteria(Citizen.class);
+ criteria.add(Restrictions.naturalId().set("ssn", "1234").set("state",
+ france));
+ criteria.setCacheable(true);
+
+ Statistics stats = getSessions().getStatistics();
+ stats.setStatisticsEnabled(true);
+ stats.clear();
+ assertEquals("Cache hits should be empty", 0, stats
+ .getQueryCacheHitCount());
+
+ // first query
+ List results = criteria.list();
+ assertEquals(1, results.size());
+ assertEquals("Cache hits should be empty", 0, stats
+ .getQueryCacheHitCount());
+ assertEquals("First query should be a miss", 1, stats
+ .getQueryCacheMissCount());
+ assertEquals("Query result should be added to cache", 1, stats
+ .getQueryCachePutCount());
+
+ // query a second time - result should be cached
+ results = criteria.list();
+ assertEquals("Cache hits should be empty", 1, stats
+ .getQueryCacheHitCount());
+
+ // cleanup
+ tx.rollback();
+ s.close();
+ }
+
+ public void testNaturalIdUncached() {
+
+ saveSomeCitizens();
+
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ State france = (State) s.load(State.class, new Integer(2));
+ Criteria criteria = s.createCriteria(Citizen.class);
+ criteria.add(Restrictions.naturalId().set("ssn", "1234").set("state",
+ france));
+ criteria.setCacheable(false);
+
+ Statistics stats = getSessions().getStatistics();
+ stats.setStatisticsEnabled(true);
+ stats.clear();
+ assertEquals("Cache hits should be empty", 0, stats
+ .getQueryCacheHitCount());
+
+ // first query
+ List results = criteria.list();
+ assertEquals(1, results.size());
+ assertEquals("Cache hits should be empty", 0, stats
+ .getQueryCacheHitCount());
+ assertEquals("Query result should be added to cache", 0, stats
+ .getQueryCachePutCount());
+
+ // query a second time
+ results = criteria.list();
+ assertEquals("Cache hits should be empty", 0, stats
+ .getQueryCacheHitCount());
+
+ // cleanup
+ tx.rollback();
+ s.close();
+ }
+
+ protected Class[] getMappings() {
+ return new Class[] { Citizen.class, State.class,
+ NaturalIdOnManyToOne.class };
+ }
+
+ private void saveSomeCitizens() {
+ Citizen c1 = new Citizen();
+ c1.setFirstname("Emmanuel");
+ c1.setLastname("Bernard");
+ c1.setSsn("1234");
+
+ State france = new State();
+ france.setName("Ile de France");
+ c1.setState(france);
+
+ Citizen c2 = new Citizen();
+ c2.setFirstname("Gavin");
+ c2.setLastname("King");
+ c2.setSsn("000");
+ State australia = new State();
+ australia.setName("Australia");
+ c2.setState(australia);
+
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ s.persist(australia);
+ s.persist(france);
+ s.persist(c1);
+ s.persist(c2);
+ tx.commit();
+ s.close();
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/naturalid/State.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/naturalid/State.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/naturalid/State.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,33 @@
+//$Id: State.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.naturalid;
+
+import javax.persistence.Id;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Entity;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class State {
+ @Id
+ @GeneratedValue
+ private Integer id;
+ private String name;
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/notfound/Coin.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/notfound/Coin.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/notfound/Coin.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,50 @@
+//$Id: Coin.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.notfound;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+
+import org.hibernate.annotations.NotFound;
+import org.hibernate.annotations.NotFoundAction;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Coin {
+ private Integer id;
+ private String name;
+ private Currency currency;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @ManyToOne
+ @JoinColumn(name = "currency", referencedColumnName = "name")
+ @NotFound(action = NotFoundAction.IGNORE)
+ public Currency getCurrency() {
+ return currency;
+ }
+
+ public void setCurrency(Currency currency) {
+ this.currency = currency;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/notfound/Currency.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/notfound/Currency.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/notfound/Currency.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,34 @@
+//$Id: Currency.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.notfound;
+
+import java.io.Serializable;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Currency implements Serializable {
+ private Integer id;
+ private String name;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/notfound/NotFoundTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/notfound/NotFoundTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/notfound/NotFoundTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,45 @@
+//$Id: NotFoundTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.notfound;
+
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class NotFoundTest extends TestCase {
+
+ public void testManyToOne() throws Exception {
+ Currency euro = new Currency();
+ euro.setName( "Euro" );
+ Coin fiveC = new Coin();
+ fiveC.setName( "Five cents" );
+ fiveC.setCurrency( euro );
+ Session s = openSession();
+ s.getTransaction().begin();
+ s.persist( euro );
+ s.persist( fiveC );
+ s.getTransaction().commit();
+ s.clear();
+ Transaction tx = s.beginTransaction();
+ euro = (Currency) s.get( Currency.class, euro.getId() );
+ s.delete( euro );
+ tx.commit();
+ s.clear();
+ tx = s.beginTransaction();
+ fiveC = (Coin) s.get( Coin.class, fiveC.getId() );
+ assertNull( fiveC.getCurrency() );
+ s.delete( fiveC );
+ tx.commit();
+ s.close();
+
+ }
+
+ protected Class[] getMappings() {
+ return new Class[]{
+ Coin.class,
+ Currency.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Child.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Child.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Child.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,33 @@
+//$Id: Child.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetomany;
+
+import java.io.Serializable;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinColumns;
+import javax.persistence.ManyToOne;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Child implements Serializable {
+ @Id
+ @GeneratedValue
+ public Integer id;
+
+ @ManyToOne()
+ @JoinColumns({
+ @JoinColumn(name = "parentCivility", referencedColumnName = "isMale"),
+ @JoinColumn(name = "parentLastName", referencedColumnName = "lastName"),
+ @JoinColumn(name = "parentFirstName", referencedColumnName = "firstName")
+ })
+ public Parent parent;
+ @Column(name = "fav_sup_hero")
+ public String favoriteSuperhero;
+ @Column(name = "fav_singer")
+ public String favoriteSinger;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/City.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/City.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/City.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,72 @@
+//$Id: City.java 15046 2008-08-13 14:59:47Z epbernard $
+package org.hibernate.test.annotations.onetomany;
+
+import java.util.ArrayList;
+import java.util.List;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.OneToMany;
+import javax.persistence.OrderBy;
+
+import org.hibernate.annotations.ForeignKey;
+import org.hibernate.annotations.Immutable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+class City {
+ private Integer id;
+ private String name;
+ private List<Street> streets;
+ private List<Street> mainStreets;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @OneToMany(mappedBy = "city")
+ @OrderBy("streetNameCopy, id")
+ public synchronized List<Street> getStreets() {
+ return streets;
+ }
+
+ public void setStreets(List<Street> streets) {
+ this.streets = streets;
+ }
+
+ @OneToMany()
+ @JoinColumn(name = "mainstreetcity_id")
+ @ForeignKey(name = "CITYSTR_FK")
+ @OrderBy
+ @Immutable
+ public List<Street> getMainStreets() {
+ return mainStreets;
+ }
+
+ public void setMainStreets(List<Street> streets) {
+ this.mainStreets = streets;
+ }
+
+ public void addMainStreet(Street street) {
+ if ( mainStreets == null ) mainStreets = new ArrayList<Street>();
+ mainStreets.add( street );
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Monkey.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Monkey.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Monkey.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,33 @@
+//$Id: Monkey.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetomany;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Monkey {
+ private Integer id;
+ private String name;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/OneToManyTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/OneToManyTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/OneToManyTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,432 @@
+//$Id: OneToManyTest.java 16346 2009-04-15 19:14:22Z gbadner $
+package org.hibernate.test.annotations.onetomany;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.SortedSet;
+import java.util.TreeSet;
+
+import org.hibernate.Hibernate;
+import org.hibernate.HibernateException;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.dialect.HSQLDialect;
+import org.hibernate.test.annotations.Customer;
+import org.hibernate.test.annotations.Discount;
+import org.hibernate.test.annotations.Passport;
+import org.hibernate.test.annotations.RequiresDialect;
+import org.hibernate.test.annotations.TestCase;
+import org.hibernate.test.annotations.Ticket;
+import org.hibernate.test.annotations.TicketComparator;
+
+/**
+ * Test various case of a one to many relationship
+ *
+ * @author Emmanuel Bernard
+ */
+@SuppressWarnings("unchecked")
+public class OneToManyTest extends TestCase {
+
+ public OneToManyTest(String x) {
+ super( x );
+ }
+
+ public void testColumnDefinitionPropagation() throws Exception {
+ Session s;
+ s = openSession();
+ s.getTransaction().begin();
+ Politician casimir = new Politician();
+ casimir.setName( "Casimir" );
+ PoliticalParty dream = new PoliticalParty();
+ dream.setName( "Dream" );
+ dream.addPolitician( casimir );
+ s.persist( dream );
+ s.getTransaction().commit();
+ s.clear();
+
+ Transaction tx = s.beginTransaction();
+ s.delete( s.get( PoliticalParty.class, dream.getName() ) );
+ tx.commit();
+ s.close();
+ }
+
+ public void testListWithBagSemanticAndOrderBy() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ City paris = new City();
+ paris.setName( "Paris" );
+ s.persist( paris );
+ Street rochechoir = new Street();
+ rochechoir.setStreetName( "Rochechoir" );
+ rochechoir.setCity( paris );
+ Street chmpsElysees = new Street();
+ chmpsElysees.setStreetName( "Champs Elysees" );
+ chmpsElysees.setCity( paris );
+ Street grandeArmee = new Street();
+ grandeArmee.setStreetName( "Grande Armee" );
+ grandeArmee.setCity( paris );
+ s.persist( rochechoir );
+ s.persist( chmpsElysees );
+ s.persist( grandeArmee );
+ paris.addMainStreet( chmpsElysees );
+ paris.addMainStreet( grandeArmee );
+
+ s.flush();
+ s.clear();
+
+ //testing @OrderBy with explicit values including Formula
+ paris = (City) s.get( City.class, paris.getId() );
+ assertEquals( 3, paris.getStreets().size() );
+ assertEquals( chmpsElysees.getStreetName(), paris.getStreets().get( 0 ).getStreetName() );
+ List<Street> mainStreets = paris.getMainStreets();
+ assertEquals( 2, mainStreets.size() );
+ Integer previousId = new Integer( -1 );
+ for ( Street street : mainStreets ) {
+ assertTrue( previousId < street.getId() );
+ previousId = street.getId();
+ }
+ tx.rollback();
+ s.close();
+
+ }
+
+ public void testUnidirectionalDefault() throws Exception {
+ Session s;
+ Transaction tx;
+ Trainer trainer = new Trainer();
+ trainer.setName( "First trainer" );
+ Tiger regularTiger = new Tiger();
+ regularTiger.setName( "Regular Tiger" );
+ Tiger whiteTiger = new Tiger();
+ whiteTiger.setName( "White Tiger" );
+ trainer.setTrainedTigers( new HashSet<Tiger>() );
+ s = openSession();
+ tx = s.beginTransaction();
+ s.persist( trainer );
+ s.persist( regularTiger );
+ s.persist( whiteTiger );
+ trainer.getTrainedTigers().add( regularTiger );
+ trainer.getTrainedTigers().add( whiteTiger );
+
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ trainer = (Trainer) s.get( Trainer.class, trainer.getId() );
+ assertNotNull( trainer );
+ assertNotNull( trainer.getTrainedTigers() );
+ assertEquals( 2, trainer.getTrainedTigers().size() );
+ tx.rollback();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ trainer = new Trainer();
+ trainer.setName( "new trainer" );
+ trainer.setTrainedTigers( new HashSet<Tiger>() );
+ trainer.getTrainedTigers().add( whiteTiger );
+ try {
+ s.persist( trainer );
+ tx.commit();
+ fail( "A one to many should not allow several trainer per Tiger" );
+ }
+ catch (HibernateException ce) {
+ tx.rollback();
+ //success
+ }
+ s.close();
+ }
+
+ public void testUnidirectionalExplicit() throws Exception {
+ Session s;
+ Transaction tx;
+ Trainer trainer = new Trainer();
+ trainer.setName( "First trainer" );
+ Monkey regularMonkey = new Monkey();
+ regularMonkey.setName( "Regular Monkey" );
+ Monkey miniMonkey = new Monkey();
+ miniMonkey.setName( "Mini Monkey" );
+ trainer.setTrainedMonkeys( new HashSet<Monkey>() );
+ s = openSession();
+ tx = s.beginTransaction();
+ s.persist( trainer );
+ s.persist( regularMonkey );
+ s.persist( miniMonkey );
+ trainer.getTrainedMonkeys().add( regularMonkey );
+ trainer.getTrainedMonkeys().add( miniMonkey );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ trainer = (Trainer) s.get( Trainer.class, trainer.getId() );
+ assertNotNull( trainer );
+ assertNotNull( trainer.getTrainedMonkeys() );
+ assertEquals( 2, trainer.getTrainedMonkeys().size() );
+ tx.rollback();
+ s.close();
+ }
+
+ public void testFetching() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Troop t = new Troop();
+ t.setName( "Final cut" );
+ Soldier vandamme = new Soldier();
+ vandamme.setName( "JC Vandamme" );
+ t.addSoldier( vandamme );
+ Soldier rambo = new Soldier();
+ rambo.setName( "Rambo" );
+ t.addSoldier( rambo );
+ s.persist( t );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ t = (Troop) s.get( Troop.class, t.getId() );
+ assertNotNull( t.getSoldiers() );
+ assertFalse( Hibernate.isInitialized( t.getSoldiers() ) );
+ assertEquals( 2, t.getSoldiers().size() );
+ assertEquals( rambo.getName(), t.getSoldiers().iterator().next().getName() );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ t = (Troop) s.createQuery( "from " + Troop.class.getName() + " as t where t.id = :id" )
+ .setParameter( "id", t.getId() ).uniqueResult();
+ assertFalse( Hibernate.isInitialized( t.getSoldiers() ) );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ rambo = (Soldier) s.get( Soldier.class, rambo.getId() );
+ assertTrue( Hibernate.isInitialized( rambo.getTroop() ) );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ rambo = (Soldier) s.createQuery( "from " + Soldier.class.getName() + " as s where s.id = :rid" )
+ .setParameter( "rid", rambo.getId() ).uniqueResult();
+ assertTrue( "fetching strategy used when we do query", Hibernate.isInitialized( rambo.getTroop() ) );
+ tx.commit();
+ s.close();
+ }
+
+ public void testCascadeDeleteOrphan() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Troop disney = new Troop();
+ disney.setName( "Disney" );
+ Soldier mickey = new Soldier();
+ mickey.setName( "Mickey" );
+ disney.addSoldier( mickey );
+ s.persist( disney );
+ tx.commit();
+ s.close();
+ s = openSession();
+ tx = s.beginTransaction();
+ Troop troop = (Troop) s.get( Troop.class, disney.getId() );
+ Soldier soldier = (Soldier) troop.getSoldiers().iterator().next();
+ tx.commit();
+ s.close();
+ //troop.getSoldiers().remove(soldier);
+ troop.getSoldiers().clear();
+ s = openSession();
+ tx = s.beginTransaction();
+ s.merge( troop );
+ tx.commit();
+ s.close();
+ s = openSession();
+ tx = s.beginTransaction();
+ soldier = (Soldier) s.get( Soldier.class, mickey.getId() );
+ assertNull( "delete-orphan should work", soldier );
+ troop = (Troop) s.get( Troop.class, disney.getId() );
+ s.delete( troop );
+ tx.commit();
+ s.close();
+ }
+
+ public void testCascadeDelete() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Troop disney = new Troop();
+ disney.setName( "Disney" );
+ Soldier mickey = new Soldier();
+ mickey.setName( "Mickey" );
+ disney.addSoldier( mickey );
+ s.persist( disney );
+ tx.commit();
+ s.close();
+ s = openSession();
+ tx = s.beginTransaction();
+ Troop troop = (Troop) s.get( Troop.class, disney.getId() );
+ s.delete( troop );
+ tx.commit();
+ s.close();
+ s = openSession();
+ tx = s.beginTransaction();
+ Soldier soldier = (Soldier) s.get( Soldier.class, mickey.getId() );
+ assertNull( "delete-orphan should work", soldier );
+ tx.commit();
+ s.close();
+ }
+
+ public void testSimpleOneToManySet() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Ticket t = new Ticket();
+ t.setNumber( "33A" );
+ Ticket t2 = new Ticket();
+ t2.setNumber( "234ER" );
+ Customer c = new Customer();
+ s.persist( c );
+ //s.persist(t);
+ SortedSet<Ticket> tickets = new TreeSet<Ticket>( new TicketComparator() );
+ tickets.add( t );
+ tickets.add( t2 );
+ c.setTickets( tickets );
+
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ c = (Customer) s.load( Customer.class, c.getId() );
+ assertNotNull( c );
+ assertTrue( Hibernate.isInitialized( c.getTickets() ) );
+ assertNotNull( c.getTickets() );
+ tickets = c.getTickets();
+ assertTrue( tickets.size() > 0 );
+ assertEquals( t2.getNumber(), c.getTickets().first().getNumber() );
+ tx.commit();
+ s.close();
+ }
+
+ public void testSimpleOneToManyCollection() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Discount d = new Discount();
+ d.setDiscount( 10 );
+ Customer c = new Customer();
+ List discounts = new ArrayList();
+ discounts.add( d );
+ d.setOwner( c );
+ c.setDiscountTickets( discounts );
+ s.persist( c );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ c = (Customer) s.load( Customer.class, c.getId() );
+ assertNotNull( c );
+ assertFalse( Hibernate.isInitialized( c.getDiscountTickets() ) );
+ assertNotNull( c.getDiscountTickets() );
+ Collection collecDiscount = c.getDiscountTickets();
+ assertTrue( collecDiscount.size() > 0 );
+ tx.commit();
+ s.close();
+ }
+
+ public void testJoinColumns() throws Exception {
+ Parent parent = new Parent();
+ ParentPk pk = new ParentPk();
+ pk.firstName = "Bruce";
+ pk.lastName = "Willis";
+ pk.isMale = true;
+ parent.id = pk;
+ parent.age = 40;
+ Child child = new Child();
+ Child child2 = new Child();
+ parent.addChild( child );
+ parent.addChild( child2 );
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ s.persist( parent );
+ tx.commit();
+ s.close();
+
+ assertNotNull( child.id );
+ assertNotNull( child2.id );
+ assertNotSame( child.id, child2.id );
+
+ s = openSession();
+ tx = s.beginTransaction();
+ parent = (Parent) s.get( Parent.class, pk );
+ assertNotNull( parent.children );
+ Hibernate.initialize( parent.children );
+ assertEquals( 2, parent.children.size() );
+ tx.commit();
+ s.close();
+ }
+
+ @RequiresDialect(HSQLDialect.class)
+ public void testOrderByOnSuperclassProperty() {
+ OrganisationUser user = new OrganisationUser();
+ user.setFirstName( "Emmanuel" );
+ user.setLastName( "Bernard" );
+ user.setIdPerson( new Long(1) );
+ user.setSomeText( "SomeText" );
+ Organisation org = new Organisation();
+ org.setIdOrganisation( new Long(1) );
+ org.setName( "S Diego Zoo" );
+ user.setOrganisation( org );
+ Session s = openSession();
+ s.getTransaction().begin();
+ s.persist( user );
+ s.persist( org );
+ s.flush();
+ s.clear();
+ s.createQuery( "select org from Organisation org left join fetch org.organisationUsers" ).list();
+ s.getTransaction().rollback();
+ s.close();
+ }
+
+ /**
+ * @see org.hibernate.test.annotations.TestCase#getMappings()
+ */
+ protected Class[] getMappings() {
+ return new Class[]{
+ Troop.class,
+ Soldier.class,
+ Customer.class,
+ Ticket.class,
+ Discount.class,
+ Passport.class,
+ Parent.class,
+ Child.class,
+ Trainer.class,
+ Tiger.class,
+ Monkey.class,
+ City.class,
+ Street.class,
+ PoliticalParty.class,
+ Politician.class,
+ Person.class,
+ Organisation.class,
+ OrganisationUser.class
+ };
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Order.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Order.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Order.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,70 @@
+//$Id: Order.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetomany;
+
+import java.util.LinkedHashSet;
+import java.util.Set;
+import java.util.List;
+import java.util.ArrayList;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.IdClass;
+import javax.persistence.OneToMany;
+import javax.persistence.OrderBy;
+import javax.persistence.Table;
+
+@Entity
+@Table( name = "Order_tbl" )
+@IdClass( OrderID.class )
+public class Order {
+ private String schoolId;
+ private Integer schoolIdSort;
+ private Integer academicYear;
+
+ private List<OrderItem> itemList = new ArrayList<OrderItem>();
+
+ public boolean equals(Object obj) {
+ return super.equals( obj );
+ }
+
+ public int hashCode() {
+ return 10;
+ }
+
+ @Id
+ public Integer getAcademicYear() {
+ return this.academicYear;
+ }
+
+ protected void setAcademicYear(Integer academicYear) {
+ this.academicYear = academicYear;
+ }
+
+ @Id
+ public String getSchoolId() {
+ return this.schoolId;
+ }
+
+ protected void setSchoolId(String schoolId) {
+ this.schoolId = schoolId;
+ }
+
+ @OneToMany( mappedBy = "order" )
+ @OrderBy( "dayNo desc" )
+ public List<OrderItem> getItemList() {
+ return this.itemList;
+ }
+
+ public void setItemList(List<OrderItem> itemList) {
+ this.itemList = itemList;
+ }
+
+ public Integer getSchoolIdSort() {
+ return this.schoolIdSort;
+ }
+
+ public void setSchoolIdSort(Integer schoolIdSort) {
+ this.schoolIdSort = schoolIdSort;
+ }
+
+
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/OrderByTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/OrderByTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/OrderByTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,52 @@
+//$Id: OrderByTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetomany;
+
+import org.hibernate.test.annotations.TestCase;
+import org.hibernate.Session;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class OrderByTest extends TestCase {
+ public void testOrderByOnIdClassProperties() throws Exception {
+ Session s = openSession( );
+ s.getTransaction().begin();
+ Order o = new Order();
+ o.setAcademicYear( 2000 );
+ o.setSchoolId( "Supelec" );
+ o.setSchoolIdSort( 1 );
+ s.persist( o );
+ OrderItem oi1 = new OrderItem();
+ oi1.setAcademicYear( 2000 );
+ oi1.setDayName( "Monday" );
+ oi1.setSchoolId( "Supelec" );
+ oi1.setOrder( o );
+ oi1.setDayNo( 23 );
+ s.persist( oi1 );
+ OrderItem oi2 = new OrderItem();
+ oi2.setAcademicYear( 2000 );
+ oi2.setDayName( "Tuesday" );
+ oi2.setSchoolId( "Supelec" );
+ oi2.setOrder( o );
+ oi2.setDayNo( 30 );
+ s.persist( oi2 );
+ s.flush();
+ s.clear();
+
+ OrderID oid = new OrderID();
+ oid.setAcademicYear( 2000 );
+ oid.setSchoolId( "Supelec" );
+ o = (Order) s.get( Order.class, oid );
+ assertEquals( 30, o.getItemList().get( 0 ).getDayNo().intValue() );
+
+ s.getTransaction().rollback();
+ s.close();
+ }
+
+ protected Class[] getMappings() {
+ return new Class[] {
+ Order.class,
+ OrderItem.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/OrderID.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/OrderID.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/OrderID.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,31 @@
+//$Id: OrderID.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetomany;
+
+import java.io.Serializable;
+import javax.persistence.Column;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class OrderID implements Serializable {
+ private String schoolId;
+ private Integer academicYear;
+
+ @Column( name = "Academic_Yr" )
+ public Integer getAcademicYear() {
+ return this.academicYear;
+ }
+
+ public void setAcademicYear(Integer academicYear) {
+ this.academicYear = academicYear;
+ }
+
+ @Column( name = "School_Id" )
+ public String getSchoolId() {
+ return this.schoolId;
+ }
+
+ public void setSchoolId(String schoolId) {
+ this.schoolId = schoolId;
+ }
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/OrderItem.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/OrderItem.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/OrderItem.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,73 @@
+//$Id: OrderItem.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetomany;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.Id;
+import javax.persistence.IdClass;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinColumns;
+import javax.persistence.ManyToOne;
+import javax.persistence.Table;
+
+@Entity
+@Table( name = "OrderItem_tbl" )
+@IdClass( OrderItemID.class )
+public class OrderItem {
+ String schoolId;
+ Integer academicYear;
+ Integer dayNo;
+ String dayName;
+ private Order order;
+
+ @Id
+ public Integer getDayNo() {
+ return dayNo;
+ }
+
+ public void setDayNo(Integer dayNo) {
+ this.dayNo = dayNo;
+ }
+
+ @Id
+ public String getSchoolId() {
+ return schoolId;
+ }
+
+ public void setSchoolId(String schoolId) {
+ this.schoolId = schoolId;
+ }
+
+ @Id
+ public Integer getAcademicYear() {
+ return academicYear;
+ }
+
+ public void setAcademicYear(Integer academicYear) {
+ this.academicYear = academicYear;
+ }
+
+ @Column( name = "Day_Name" )
+ public String getDayName() {
+ return dayName;
+ }
+
+ public void setDayName(String dayName) {
+ this.dayName = dayName;
+ }
+
+ @ManyToOne( fetch = FetchType.LAZY )
+ @JoinColumns( {
+ @JoinColumn( name = "School_Id", referencedColumnName = "School_Id", insertable = false, updatable = false ),
+ @JoinColumn( name = "Academic_Yr", referencedColumnName = "Academic_Yr", insertable = false, updatable = false )
+ } )
+ public Order getOrder() {
+ return this.order;
+ }
+
+ public void setOrder(Order order) {
+ this.order = order;
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/OrderItemID.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/OrderItemID.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/OrderItemID.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,41 @@
+//$Id: OrderItemID.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetomany;
+
+import java.io.Serializable;
+import javax.persistence.Column;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class OrderItemID implements Serializable {
+ String schoolId;
+ Integer academicYear;
+ Integer dayNo;
+
+ @Column( name = "Academic_Yr" )
+ public Integer getAcademicYear() {
+ return this.academicYear;
+ }
+
+ public void setAcademicYear(Integer academicYear) {
+ this.academicYear = academicYear;
+ }
+
+ @Column( name = "Day_No" )
+ public Integer getDayNo() {
+ return this.dayNo;
+ }
+
+ public void setDayNo(Integer dayNo) {
+ this.dayNo = dayNo;
+ }
+
+ @Column( name = "School_Id" )
+ public String getSchoolId() {
+ return this.schoolId;
+ }
+
+ public void setSchoolId(String schoolId) {
+ this.schoolId = schoolId;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Organisation.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Organisation.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Organisation.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,60 @@
+//$Id: Organisation.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetomany;
+
+import java.io.Serializable;
+import java.util.Set;
+import javax.persistence.Entity;
+import javax.persistence.Table;
+import javax.persistence.Column;
+import javax.persistence.Id;
+import javax.persistence.OneToMany;
+import javax.persistence.OrderBy;
+import javax.persistence.CascadeType;
+import javax.persistence.FetchType;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Table( name = "ORGANISATION" )
+public class Organisation implements Serializable {
+
+ private Long idOrganisation;
+ private String name;
+ private Set<OrganisationUser> organisationUsers;
+
+ public Organisation() {
+ }
+
+ public void setIdOrganisation(Long idOrganisation) {
+ this.idOrganisation = idOrganisation;
+ }
+
+ @Id
+ @Column( name = "id_organisation", nullable = false )
+ public Long getIdOrganisation() {
+ return idOrganisation;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @Column( name = "name", nullable = false, length = 40 )
+ public String getName() {
+ return name;
+ }
+
+ public void setOrganisationUsers(Set<OrganisationUser> organisationUsers) {
+ this.organisationUsers = organisationUsers;
+ }
+
+ @OneToMany( mappedBy = "organisation",
+ fetch = FetchType.LAZY,
+ cascade = {CascadeType.PERSIST, CascadeType.MERGE} )
+ @OrderBy( value = "firstName" )
+ public Set<OrganisationUser> getOrganisationUsers() {
+ return organisationUsers;
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/OrganisationUser.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/OrganisationUser.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/OrganisationUser.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,46 @@
+//$Id: OrganisationUser.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetomany;
+
+import java.io.Serializable;
+import javax.persistence.CascadeType;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+import javax.persistence.PrimaryKeyJoinColumn;
+import javax.persistence.Table;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@PrimaryKeyJoinColumn( name = "id_organisation_user" )
+@Table( name = "ORGANISATION_USER" )
+public class OrganisationUser extends Person implements Serializable {
+
+ private String someText;
+ private Organisation organisation;
+
+ public OrganisationUser() {
+ }
+
+ public void setSomeText(String someText) {
+ this.someText = someText;
+ }
+
+ @Column( name = "some_text", nullable=true,length=1024)
+ public String getSomeText() {
+ return someText;
+ }
+
+ public void setOrganisation(Organisation organisation) {
+ this.organisation = organisation;
+ }
+
+ @ManyToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE} )
+ @JoinColumn( name = "fk_id_organisation", nullable = false )
+ public Organisation getOrganisation() {
+ return organisation;
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Parent.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Parent.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Parent.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,50 @@
+//$Id: Parent.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetomany;
+
+import java.io.Serializable;
+import java.util.HashSet;
+import java.util.Set;
+import javax.persistence.CascadeType;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.OneToMany;
+
+import org.hibernate.annotations.BatchSize;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Parent implements Serializable {
+ @Id
+ public ParentPk id;
+ public int age;
+
+ @OneToMany(cascade = CascadeType.ALL, mappedBy = "parent")
+ @BatchSize(size = 5)
+ @javax.persistence.OrderBy("favoriteSuperhero asc, favoriteSinger desc")
+ public Set<Child> children;
+
+ public int hashCode() {
+ //a NPE can occurs, but I don't expect hashcode to be used before pk is set
+ return id.hashCode();
+ }
+
+ public boolean equals(Object obj) {
+ //a NPE can occurs, but I don't expect equals to be used before pk is set
+ if ( obj != null && obj instanceof Parent ) {
+ return id.equals( ( (Parent) obj ).id );
+ }
+ else {
+ return false;
+ }
+ }
+
+ public void addChild(Child child) {
+ if ( children == null ) {
+ children = new HashSet();
+ }
+ child.parent = this;
+ children.add( child );
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/ParentPk.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/ParentPk.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/ParentPk.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,38 @@
+//$Id: ParentPk.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetomany;
+
+import java.io.Serializable;
+import javax.persistence.Embeddable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Embeddable
+public class ParentPk implements Serializable {
+ String firstName;
+ String lastName;
+
+ /**
+ * is a male or a female
+ */
+ //show hetereogenous PK types
+ boolean isMale;
+
+ public int hashCode() {
+ //this implem sucks
+ return firstName.hashCode() + lastName.hashCode() + ( isMale ? 0 : 1 );
+ }
+
+ public boolean equals(Object obj) {
+ //firstName and lastName are expected to be set in this implem
+ if ( obj != null && obj instanceof ParentPk ) {
+ ParentPk other = (ParentPk) obj;
+ return firstName.equals( other.firstName )
+ && lastName.equals( other.lastName )
+ && isMale == other.isMale;
+ }
+ else {
+ return false;
+ }
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Person.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Person.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Person.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,55 @@
+//$Id: Person.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetomany;
+
+import java.io.Serializable;
+import javax.persistence.Column;
+import javax.persistence.Id;
+import javax.persistence.Entity;
+import javax.persistence.Table;
+import javax.persistence.InheritanceType;
+import javax.persistence.Inheritance;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Inheritance( strategy = InheritanceType.JOINED )
+@Table( name = "PERSON_Orderby" )
+public class Person implements Serializable {
+
+ private Long idPerson;
+ private String firstName, lastName;
+
+ public Person() {
+ }
+
+ public void setIdPerson(Long idPerson) {
+ this.idPerson = idPerson;
+ }
+
+ @Id
+ @Column( name = "id_person", nullable = false )
+ public Long getIdPerson() {
+ return idPerson;
+ }
+
+ public void setFirstName(String firstName) {
+ this.firstName = firstName;
+ }
+
+ @Column( name = "first_name", length = 40, nullable = false )
+ public String getFirstName() {
+ return firstName;
+ }
+
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+
+ @Column( name = "last_name", length = 40, nullable = false )
+ public String getLastName() {
+ return lastName;
+ }
+
+}
+
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/PoliticalParty.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/PoliticalParty.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/PoliticalParty.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,43 @@
+//$Id: PoliticalParty.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetomany;
+
+import java.util.HashSet;
+import java.util.Set;
+import javax.persistence.CascadeType;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.OneToMany;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class PoliticalParty {
+ private String name;
+ private Set<Politician> politicians = new HashSet<Politician>();
+
+ @Id
+ @Column(columnDefinition = "VARCHAR(60)")
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @OneToMany(mappedBy = "party", cascade = CascadeType.ALL)
+ public Set<Politician> getPoliticians() {
+ return politicians;
+ }
+
+ public void setPoliticians(Set<Politician> politicians) {
+ this.politicians = politicians;
+ }
+
+ public void addPolitician(Politician politician) {
+ politicians.add( politician );
+ politician.setParty( this );
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Politician.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Politician.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Politician.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,37 @@
+//$Id: Politician.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetomany;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Politician {
+ private String name;
+ private PoliticalParty party;
+
+ @Id
+ @Column(columnDefinition = "VARCHAR(30)")
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @ManyToOne
+ @JoinColumn(name = "party_fk")
+ public PoliticalParty getParty() {
+ return party;
+ }
+
+ public void setParty(PoliticalParty party) {
+ this.party = party;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Soldier.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Soldier.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Soldier.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,62 @@
+//$Id: Soldier.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetomany;
+
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Soldier {
+ private Integer id;
+ private String name;
+ private Troop troop;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @ManyToOne(fetch = FetchType.EAGER)
+ @JoinColumn(name = "troop_fk")
+ public Troop getTroop() {
+ return troop;
+ }
+
+ public void setTroop(Troop troop) {
+ this.troop = troop;
+ }
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( !( o instanceof Soldier ) ) return false;
+
+ final Soldier soldier = (Soldier) o;
+
+ if ( !name.equals( soldier.name ) ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ return name.hashCode();
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Street.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Street.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Street.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,58 @@
+//$Id: Street.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetomany;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.ManyToOne;
+import javax.persistence.Column;
+
+import org.hibernate.annotations.Formula;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Street {
+ private Integer id;
+ private String streetName;
+ private String streetNameCopy;
+ private City city;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ @Column(name="STREET_NAME")
+ public String getStreetName() {
+ return streetName;
+ }
+
+ public void setStreetName(String streetName) {
+ this.streetName = streetName;
+ }
+
+ @Formula("STREET_NAME")
+ public String getStreetNameCopy() {
+ return streetNameCopy;
+ }
+
+ public void setStreetNameCopy(String streetNameCopy) {
+ this.streetNameCopy = streetNameCopy;
+ }
+
+ @ManyToOne
+ public City getCity() {
+ return city;
+ }
+
+ public void setCity(City city) {
+ this.city = city;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Tiger.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Tiger.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Tiger.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,33 @@
+//$Id: Tiger.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetomany;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Tiger {
+ private Integer id;
+ private String name;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Trainer.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Trainer.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Trainer.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,67 @@
+//$Id: Trainer.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetomany;
+
+import java.util.Set;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinTable;
+import javax.persistence.OneToMany;
+
+import org.hibernate.annotations.ForeignKey;
+
+/**
+ * Unidirectional one to many sample
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity()
+public class Trainer {
+ private Integer id;
+ private String name;
+ private Set<Tiger> trainedTigers;
+ private Set<Monkey> trainedMonkeys;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @OneToMany
+ public Set<Tiger> getTrainedTigers() {
+ return trainedTigers;
+ }
+
+ public void setTrainedTigers(Set<Tiger> trainedTigers) {
+ this.trainedTigers = trainedTigers;
+ }
+
+ @OneToMany
+ @JoinTable(
+ name = "TrainedMonkeys",
+ joinColumns = {@JoinColumn(name = "trainer_id")},
+ inverseJoinColumns = @JoinColumn(name = "monkey_id")
+ )
+ @ForeignKey(name = "TM_TRA_FK", inverseName = "TM_MON_FK")
+ public Set<Monkey> getTrainedMonkeys() {
+ return trainedMonkeys;
+ }
+
+ public void setTrainedMonkeys(Set<Monkey> trainedMonkeys) {
+ this.trainedMonkeys = trainedMonkeys;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Troop.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Troop.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetomany/Troop.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,64 @@
+//$Id: Troop.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetomany;
+
+import java.util.HashSet;
+import java.util.Set;
+import javax.persistence.CascadeType;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.OneToMany;
+
+import org.hibernate.annotations.OnDelete;
+import org.hibernate.annotations.OnDeleteAction;
+import org.hibernate.annotations.OrderBy;
+
+/**
+ * Shows a default one to many
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Troop {
+ private Integer id;
+ private String name;
+ private Set<Soldier> soldiers;
+
+ @OneToMany(mappedBy = "troop", cascade = {CascadeType.ALL}, fetch = FetchType.LAZY)
+ @OrderBy(clause = "name desc")
+ @org.hibernate.annotations.Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
+ @OnDelete(action = OnDeleteAction.CASCADE)
+ public Set<Soldier> getSoldiers() {
+ return soldiers;
+ }
+
+ public void setSoldiers(Set<Soldier> soldiers) {
+ this.soldiers = soldiers;
+ }
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public void addSoldier(Soldier s) {
+ if ( soldiers == null ) soldiers = new HashSet<Soldier>();
+ soldiers.add( s );
+ s.setTroop( this );
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/Address.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/Address.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/Address.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,34 @@
+//$Id: Address.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetoone;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Address {
+
+ private Integer id;
+ private String city;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getCity() {
+ return city;
+ }
+
+ public void setCity(String city) {
+ this.city = city;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/Body.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/Body.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/Body.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,35 @@
+//$Id: Body.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetoone;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.OneToOne;
+import javax.persistence.PrimaryKeyJoinColumn;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Body {
+ private Integer id;
+ private Heart heart;
+
+ @OneToOne
+ @PrimaryKeyJoinColumn
+ public Heart getHeart() {
+ return heart;
+ }
+
+ public void setHeart(Heart heart) {
+ this.heart = heart;
+ }
+
+ @Id
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/Client.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/Client.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/Client.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,49 @@
+//$Id: Client.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetoone;
+
+import javax.persistence.CascadeType;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.OneToOne;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Client {
+
+ private Integer id;
+ private String name;
+ private Address address;
+
+ @OneToOne(cascade = CascadeType.ALL)
+ @JoinColumn(name = "ADDRESS_ID")
+ public Address getAddress() {
+ return address;
+ }
+
+ public void setAddress(Address address) {
+ this.address = address;
+ }
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/Computer.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/Computer.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/Computer.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,73 @@
+//$Id: Computer.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetoone;
+
+import javax.persistence.AttributeOverride;
+import javax.persistence.AttributeOverrides;
+import javax.persistence.CascadeType;
+import javax.persistence.Column;
+import javax.persistence.EmbeddedId;
+import javax.persistence.Entity;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinColumns;
+import javax.persistence.OneToOne;
+
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Computer {
+
+ private ComputerPk id;
+ private String cpu;
+ private SerialNumber serial;
+
+ @OneToOne(cascade = {CascadeType.PERSIST})
+ @JoinColumns({
+ @JoinColumn(name = "serialbrand", referencedColumnName = "brand"),
+ @JoinColumn(name = "serialmodel", referencedColumnName = "model")
+ })
+ public SerialNumber getSerial() {
+ return serial;
+ }
+
+ public void setSerial(SerialNumber serial) {
+ this.serial = serial;
+ }
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( !( o instanceof Computer ) ) return false;
+
+ final Computer computer = (Computer) o;
+
+ if ( !id.equals( computer.id ) ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ return id.hashCode();
+ }
+
+ @EmbeddedId
+ @AttributeOverrides({
+ @AttributeOverride(name = "brand", column = @Column(name = "computer_brand")),
+ @AttributeOverride(name = "model", column = @Column(name = "computer_model"))
+ })
+ public ComputerPk getId() {
+ return id;
+ }
+
+ public void setId(ComputerPk id) {
+ this.id = id;
+ }
+
+ public String getCpu() {
+ return cpu;
+ }
+
+ public void setCpu(String cpu) {
+ this.cpu = cpu;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/ComputerPk.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/ComputerPk.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/ComputerPk.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,49 @@
+//$Id: ComputerPk.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetoone;
+
+import java.io.Serializable;
+import javax.persistence.Embeddable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Embeddable
+public class ComputerPk implements Serializable {
+ private String brand;
+ private String model;
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( !( o instanceof ComputerPk ) ) return false;
+
+ final ComputerPk computerPk = (ComputerPk) o;
+
+ if ( !brand.equals( computerPk.brand ) ) return false;
+ if ( !model.equals( computerPk.model ) ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ int result;
+ result = brand.hashCode();
+ result = 29 * result + model.hashCode();
+ return result;
+ }
+
+ public String getBrand() {
+ return brand;
+ }
+
+ public void setBrand(String brand) {
+ this.brand = brand;
+ }
+
+ public String getModel() {
+ return model;
+ }
+
+ public void setModel(String model) {
+ this.model = model;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/Heart.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/Heart.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/Heart.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,22 @@
+//$Id: Heart.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetoone;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Heart {
+ private Integer id;
+
+ @Id
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/OneToOneErrorTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/OneToOneErrorTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/OneToOneErrorTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,27 @@
+//$Id: OneToOneErrorTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetoone;
+
+import org.hibernate.cfg.AnnotationConfiguration;
+import org.hibernate.cfg.Environment;
+import org.hibernate.test.annotations.IncorrectEntity;
+import org.hibernate.SessionFactory;
+import org.hibernate.AnnotationException;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class OneToOneErrorTest extends junit.framework.TestCase {
+ public void testWrongOneToOne() throws Exception {
+ AnnotationConfiguration cfg = new AnnotationConfiguration();
+ cfg.addAnnotatedClass( Show.class )
+ .addAnnotatedClass( ShowDescription.class );
+ cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
+ try {
+ SessionFactory sf = cfg.buildSessionFactory();
+ fail( "Wrong mappedBy does not fail property" );
+ }
+ catch (AnnotationException e) {
+ //success
+ }
+ }
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/OneToOneTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/OneToOneTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/OneToOneTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,268 @@
+//$Id: OneToOneTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetoone;
+
+import org.hibernate.Query;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.annotations.Customer;
+import org.hibernate.test.annotations.Discount;
+import org.hibernate.test.annotations.Passport;
+import org.hibernate.test.annotations.TestCase;
+import org.hibernate.test.annotations.Ticket;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class OneToOneTest extends TestCase {
+
+ public OneToOneTest(String x) {
+ super( x );
+ }
+
+ public void testEagerFetching() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Client c = new Client();
+ c.setName( "Emmanuel" );
+ Address a = new Address();
+ a.setCity( "Courbevoie" );
+ c.setAddress( a );
+ s.persist( c );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ Query q = s.createQuery( "select c from Client c where c.name = :name" );
+ q.setString( "name", c.getName() );
+ c = (Client) q.uniqueResult();
+ //c = (Client) s.get(Client.class, c.getId());
+ assertNotNull( c );
+ tx.commit();
+ s.close();
+ assertNotNull( c.getAddress() );
+ //assertTrue( "Should be eager fetched", Hibernate.isInitialized( c.getAddress() ) );
+
+ }
+
+ public void testDefaultOneToOne() throws Exception {
+ //test a default one to one and a mappedBy in the other side
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Customer c = new Customer();
+ c.setName( "Hibernatus" );
+ Passport p = new Passport();
+ p.setNumber( "123456789" );
+ s.persist( c ); //we need the id to assigned it to passport
+ c.setPassport( p );
+ p.setOwner( c );
+ p.setId( c.getId() );
+ tx.commit();
+ s.close();
+ s = openSession();
+ tx = s.beginTransaction();
+ c = (Customer) s.get( Customer.class, c.getId() );
+ assertNotNull( c );
+ p = c.getPassport();
+ assertNotNull( p );
+ assertEquals( "123456789", p.getNumber() );
+ assertNotNull( p.getOwner() );
+ assertEquals( "Hibernatus", p.getOwner().getName() );
+ tx.commit(); // commit or rollback is the same, we don't care for read queries
+ s.close();
+ }
+
+ public void testOneToOneWithExplicitFk() throws Exception {
+ Client c = new Client();
+ Address a = new Address();
+ a.setCity( "Paris" );
+ c.setName( "Emmanuel" );
+ c.setAddress( a );
+
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ s.persist( c );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ c = (Client) s.get( Client.class, c.getId() );
+ assertNotNull( c );
+ assertNotNull( c.getAddress() );
+ assertEquals( "Paris", c.getAddress().getCity() );
+ tx.commit();
+ s.close();
+ }
+
+ public void testUnidirectionalTrueOneToOne() throws Exception {
+ Body b = new Body();
+ Heart h = new Heart();
+ b.setHeart( h );
+ b.setId( new Integer( 1 ) );
+ h.setId( b.getId() ); //same PK
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ s.persist( h );
+ s.persist( b );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ b = (Body) s.get( Body.class, b.getId() );
+ assertNotNull( b );
+ assertNotNull( b.getHeart() );
+ assertEquals( h.getId(), b.getHeart().getId() );
+ tx.commit();
+ s.close();
+
+ }
+
+ public void testCompositePk() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ ComputerPk cid = new ComputerPk();
+ cid.setBrand( "IBM" );
+ cid.setModel( "ThinkPad" );
+ Computer c = new Computer();
+ c.setId( cid );
+ c.setCpu( "2 GHz" );
+ SerialNumberPk sid = new SerialNumberPk();
+ sid.setBrand( cid.getBrand() );
+ sid.setModel( cid.getModel() );
+ SerialNumber sn = new SerialNumber();
+ sn.setId( sid );
+ sn.setValue( "REZREZ23424" );
+ c.setSerial( sn );
+ s.persist( c );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ c = (Computer) s.get( Computer.class, cid );
+ assertNotNull( c );
+ assertNotNull( c.getSerial() );
+ assertEquals( sn.getValue(), c.getSerial().getValue() );
+ tx.commit();
+ s.close();
+ }
+
+ public void testBidirectionalTrueOneToOne() throws Exception {
+ Session s = openSession();
+ s.getTransaction().begin();
+ Party party = new Party();
+ PartyAffiliate affiliate = new PartyAffiliate();
+ affiliate.partyId = "id";
+ party.partyId = "id";
+ party.partyAffiliate = affiliate;
+ affiliate.party = party;
+ s.persist( party );
+ s.persist( affiliate );
+ s.getTransaction().commit();
+
+ s.clear();
+
+ Transaction tx = s.beginTransaction();
+ affiliate = (PartyAffiliate) s.get( PartyAffiliate.class, "id" );
+ assertNotNull( affiliate.party );
+ assertEquals( affiliate.partyId, affiliate.party.partyId );
+
+ s.clear();
+
+ party = (Party) s.get( Party.class, "id" );
+ assertNotNull( party.partyAffiliate );
+ assertEquals( party.partyId, party.partyAffiliate.partyId );
+
+ s.delete( party );
+ s.delete( party.partyAffiliate );
+ tx.commit();
+ s.close();
+ }
+
+ public void testBidirectionalFkOneToOne() throws Exception {
+ Session s = openSession();
+ s.getTransaction().begin();
+ Trousers trousers = new Trousers();
+ TrousersZip zip = new TrousersZip();
+ trousers.id = new Integer( 1 );
+ zip.id = new Integer( 2 );
+ trousers.zip = zip;
+ zip.trousers = trousers;
+ s.persist( trousers );
+ s.persist( zip );
+ s.getTransaction().commit();
+
+ s.clear();
+
+ Transaction tx = s.beginTransaction();
+ trousers = (Trousers) s.get( Trousers.class, trousers.id );
+ assertNotNull( trousers.zip );
+ assertEquals( zip.id, trousers.zip.id );
+
+ s.clear();
+
+ zip = (TrousersZip) s.get( TrousersZip.class, zip.id );
+ assertNotNull( zip.trousers );
+ assertEquals( trousers.id, zip.trousers.id );
+
+ s.delete( zip );
+ s.delete( zip.trousers );
+ tx.commit();
+ s.close();
+ }
+
+ public void testForeignGenerator() {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Owner owner = new Owner();
+ OwnerAddress address = new OwnerAddress();
+ owner.setAddress( address );
+ address.setOwner( owner );
+ s.persist( owner );
+ s.flush();
+ s.clear();
+ owner = (Owner) s.get( Owner.class, owner.getId() );
+ assertNotNull( owner );
+ assertNotNull( owner.getAddress() );
+ assertEquals( owner.getId(), owner.getAddress().getId() );
+ tx.rollback();
+ s.close();
+ }
+
+ /**
+ * @see org.hibernate.test.annotations.TestCase#getMappings()
+ */
+ protected Class[] getMappings() {
+ return new Class[]{
+ PartyAffiliate.class,
+ Party.class,
+ Trousers.class,
+ TrousersZip.class,
+ Customer.class,
+ Ticket.class,
+ Discount.class,
+ Passport.class,
+ Client.class,
+ Address.class,
+ Computer.class,
+ SerialNumber.class,
+ Body.class,
+ Heart.class,
+ Owner.class,
+ OwnerAddress.class
+ };
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/Owner.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/Owner.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/Owner.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,35 @@
+//$Id: Owner.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetoone;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.GeneratedValue;
+import javax.persistence.OneToOne;
+import javax.persistence.PrimaryKeyJoinColumn;
+import javax.persistence.CascadeType;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Owner {
+ @Id @GeneratedValue private Integer id;
+
+ @OneToOne(cascade = CascadeType.ALL) @PrimaryKeyJoinColumn private OwnerAddress address;
+
+ public OwnerAddress getAddress() {
+ return address;
+ }
+
+ public void setAddress(OwnerAddress address) {
+ this.address = address;
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/OwnerAddress.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/OwnerAddress.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/OwnerAddress.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,39 @@
+//$Id: OwnerAddress.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetoone;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.GeneratedValue;
+import javax.persistence.OneToOne;
+
+import org.hibernate.annotations.GenericGenerator;
+import org.hibernate.annotations.Parameter;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class OwnerAddress {
+ @Id @GeneratedValue(generator = "fk")
+ @GenericGenerator(strategy = "foreign", name = "fk", parameters = @Parameter(name="property", value="owner"))
+ private Integer id;
+
+ @OneToOne(mappedBy="address", optional = false)
+ private Owner owner;
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public Owner getOwner() {
+ return owner;
+ }
+
+ public void setOwner(Owner owner) {
+ this.owner = owner;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/Party.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/Party.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/Party.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,20 @@
+//$Id: Party.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetoone;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.OneToOne;
+import javax.persistence.PrimaryKeyJoinColumn;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Party {
+ @Id
+ String partyId;
+
+ @OneToOne
+ @PrimaryKeyJoinColumn
+ PartyAffiliate partyAffiliate;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/PartyAffiliate.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/PartyAffiliate.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/PartyAffiliate.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,21 @@
+//$Id: PartyAffiliate.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetoone;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.OneToOne;
+import javax.persistence.PrimaryKeyJoinColumn;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class PartyAffiliate {
+ @Id
+ String partyId;
+
+ @OneToOne(mappedBy="partyAffiliate")
+ Party party;
+
+ String affiliateName;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/SerialNumber.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/SerialNumber.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/SerialNumber.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,46 @@
+//$Id: SerialNumber.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetoone;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class SerialNumber {
+ private SerialNumberPk id;
+ private String value;
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( !( o instanceof SerialNumber ) ) return false;
+
+ final SerialNumber serialNumber = (SerialNumber) o;
+
+ if ( !id.equals( serialNumber.id ) ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ return id.hashCode();
+ }
+
+ @Id
+ public SerialNumberPk getId() {
+ return id;
+ }
+
+ public void setId(SerialNumberPk id) {
+ this.id = id;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ public void setValue(String value) {
+ this.value = value;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/SerialNumberPk.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/SerialNumberPk.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/SerialNumberPk.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,49 @@
+//$Id: SerialNumberPk.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetoone;
+
+import java.io.Serializable;
+import javax.persistence.Embeddable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Embeddable
+public class SerialNumberPk implements Serializable {
+ private String brand;
+ private String model;
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( !( o instanceof SerialNumberPk ) ) return false;
+
+ final SerialNumberPk serialNumberPk = (SerialNumberPk) o;
+
+ if ( !brand.equals( serialNumberPk.brand ) ) return false;
+ if ( !model.equals( serialNumberPk.model ) ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ int result;
+ result = brand.hashCode();
+ result = 13 * result + model.hashCode();
+ return result;
+ }
+
+ public String getBrand() {
+ return brand;
+ }
+
+ public void setBrand(String brand) {
+ this.brand = brand;
+ }
+
+ public String getModel() {
+ return model;
+ }
+
+ public void setModel(String model) {
+ this.model = model;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/Show.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/Show.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/Show.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,33 @@
+//$Id: Show.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetoone;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.OneToOne;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Show {
+ @Id
+ private Integer id;
+ @OneToOne() private ShowDescription description;
+
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public ShowDescription getDescription() {
+ return description;
+ }
+
+ public void setDescription(ShowDescription description) {
+ this.description = description;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/ShowDescription.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/ShowDescription.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/ShowDescription.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,34 @@
+//$Id: ShowDescription.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetoone;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.OneToOne;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class ShowDescription {
+ @Id
+ private Integer id;
+ @OneToOne(mappedBy = "wrongProperty")
+ private Show show;
+
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public Show getShow() {
+ return show;
+ }
+
+ public void setShow(Show show) {
+ this.show = show;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/Trousers.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/Trousers.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/Trousers.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,21 @@
+//$Id: Trousers.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetoone;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.OneToOne;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Trousers {
+ @Id
+ public Integer id;
+
+ @OneToOne
+ @JoinColumn(name = "zip_id")
+ public TrousersZip zip;
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/TrousersZip.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/TrousersZip.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/TrousersZip.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,17 @@
+//$Id: TrousersZip.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetoone;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.OneToOne;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class TrousersZip {
+ @Id
+ public Integer id;
+ @OneToOne(mappedBy = "zip")
+ public Trousers trousers;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/primarykey/Address.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/primarykey/Address.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/primarykey/Address.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,33 @@
+//$Id: A320.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetoone.primarykey;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.OneToOne;
+
+@Entity
+public class Address {
+
+ @Id
+ private long id;
+
+ @OneToOne(mappedBy = "address")
+ private Person person;
+
+ public long getId() {
+ return id;
+ }
+
+ public void setId(long id) {
+ this.id = id;
+ }
+
+ public Person getPerson() {
+ return person;
+ }
+
+ public void setPerson(Person person) {
+ this.person = person;
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/primarykey/NullablePrimaryKeyTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/primarykey/NullablePrimaryKeyTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/primarykey/NullablePrimaryKeyTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,39 @@
+//$Id: A320.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetoone.primarykey;
+
+import junit.framework.TestCase;
+
+import org.hibernate.cfg.AnnotationConfiguration;
+import org.hibernate.dialect.SQLServerDialect;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Test harness for ANN-742.
+ *
+ * @author Hardy Ferentschik
+ *
+ */
+public class NullablePrimaryKeyTest extends TestCase {
+
+ private Logger log = LoggerFactory.getLogger(NullablePrimaryKeyTest.class);
+
+ public void testGeneratedSql() {
+ try {
+ AnnotationConfiguration config = new AnnotationConfiguration();
+ config.addAnnotatedClass(Address.class);
+ config.addAnnotatedClass(Person.class);
+ config.buildSessionFactory();
+ String[] schema = config
+ .generateSchemaCreationScript(new SQLServerDialect());
+ for (String s : schema) {
+ log.debug(s);
+ }
+ String expectedMappingTableSql = "create table personAddress (address_id numeric(19,0) null, " +
+ "person_id numeric(19,0) not null, primary key (person_id))";
+ assertEquals("Wrong SQL", expectedMappingTableSql, schema[2]);
+ } catch (Exception e) {
+ fail(e.getMessage());
+ }
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/primarykey/Person.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/primarykey/Person.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/onetoone/primarykey/Person.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,39 @@
+//$Id: A320.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.onetoone.primarykey;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinTable;
+import javax.persistence.OneToOne;
+
+@Entity
+public class Person {
+
+ @Id
+ private long id;
+
+ @OneToOne
+ @JoinTable(
+ name = "personAddress",
+ joinColumns = @JoinColumn(name = "person_id"),
+ inverseJoinColumns = @JoinColumn(name = "address_id")
+ )
+ private Address address;
+
+ public long getId() {
+ return id;
+ }
+
+ public void setId(long id) {
+ this.id = id;
+ }
+
+ public Address getAddress() {
+ return address;
+ }
+
+ public void setAddress(Address address) {
+ this.address = address;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/orm.xml
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/orm.xml (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/orm.xml 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ version="1.0"
+ >
+ <sequence-generator name="SEQ_GEN" sequence-name="my_sequence"/>
+ <table-generator name="EMP_GEN" table="GENERATOR_TABLE"
+ pk-column-name="pkey" pk-column-value="EMP"
+ value-column-name="hi" allocation-size="20"/>
+</entity-mappings>
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/override/AssociationOverrideTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/override/AssociationOverrideTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/override/AssociationOverrideTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,47 @@
+//$Id: AssociationOverrideTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.override;
+
+import org.hibernate.HibernateException;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class AssociationOverrideTest extends TestCase {
+
+ public void testOverriding() throws Exception {
+ Location paris = new Location();
+ paris.setName( "Paris" );
+ Location atlanta = new Location();
+ atlanta.setName( "Atlanta" );
+ Trip trip = new Trip();
+ trip.setFrom( paris );
+ //trip.setTo( atlanta );
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ s.persist( paris );
+ s.persist( atlanta );
+ try {
+ s.persist( trip );
+ s.flush();
+ fail( "Should be non nullable" );
+ }
+ catch (HibernateException e) {
+ //success
+ }
+ finally {
+ tx.rollback();
+ s.close();
+ }
+ }
+
+ protected Class[] getMappings() {
+ return new Class[]{
+ Location.class,
+ Move.class,
+ Trip.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/override/Location.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/override/Location.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/override/Location.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,22 @@
+//$Id: Location.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.override;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Location {
+ private String name;
+
+ @Id
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/override/Move.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/override/Move.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/override/Move.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,47 @@
+//$Id: Move.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.override;
+
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+import javax.persistence.MappedSuperclass;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@MappedSuperclass
+public class Move {
+ private int id;
+ private Location from;
+ private Location to;
+
+ @ManyToOne
+ public Location getFrom() {
+ return from;
+ }
+
+ public void setFrom(Location from) {
+ this.from = from;
+ }
+
+ @Id
+ @GeneratedValue
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ @ManyToOne
+ @JoinColumn(name = "to", nullable = true)
+ public Location getTo() {
+ return to;
+ }
+
+ public void setTo(Location to) {
+ this.to = to;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/override/Trip.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/override/Trip.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/override/Trip.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,18 @@
+//$Id: Trip.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.override;
+
+import javax.persistence.AssociationOverride;
+import javax.persistence.AssociationOverrides;
+import javax.persistence.Entity;
+import javax.persistence.JoinColumn;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@AssociationOverrides({
+@AssociationOverride(name = "from", joinColumns = @JoinColumn(name = "from2", nullable = false)),
+@AssociationOverride(name = "to", joinColumns = @JoinColumn(name = "to2", nullable = false))
+ })
+public class Trip extends Move {
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/persister/Card.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/persister/Card.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/persister/Card.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,21 @@
+package org.hibernate.test.annotations.persister;
+
+import java.io.Serializable;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+
+/**
+ * @author Shawn Clowater
+ */
+@Entity
+(a)org.hibernate.annotations.Entity( persister = "org.hibernate.persister.entity.SingleTableEntityPersister" )
+public class Card implements Serializable {
+ @Id
+ public Integer id;
+
+ @ManyToOne()
+ @JoinColumn()
+ public Deck deck;
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/persister/CollectionPersister.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/persister/CollectionPersister.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/persister/CollectionPersister.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,19 @@
+package org.hibernate.test.annotations.persister;
+
+import org.hibernate.MappingException;
+import org.hibernate.cache.CacheException;
+import org.hibernate.cache.access.CollectionRegionAccessStrategy;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.engine.SessionFactoryImplementor;
+import org.hibernate.mapping.Collection;
+import org.hibernate.persister.collection.OneToManyPersister;
+
+/**
+ * @author Shawn Clowater
+ */
+public class CollectionPersister extends OneToManyPersister {
+ public CollectionPersister(Collection collection, CollectionRegionAccessStrategy cache, Configuration cfg,
+ SessionFactoryImplementor factory) throws MappingException, CacheException {
+ super( collection, cache, cfg, factory );
+ }
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/persister/Deck.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/persister/Deck.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/persister/Deck.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,25 @@
+package org.hibernate.test.annotations.persister;
+
+import java.io.Serializable;
+import java.util.Set;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.OneToMany;
+
+import org.hibernate.annotations.Persister;
+
+
+/**
+ * @author Shawn Clowater
+ */
+@Entity
+(a)org.hibernate.annotations.Entity( persister = "org.hibernate.persister.entity.SingleTableEntityPersister" )
+@Persister( impl = org.hibernate.test.annotations.persister.EntityPersister.class )
+public class Deck implements Serializable {
+ @Id
+ public Integer id;
+
+ @OneToMany( mappedBy = "deck" )
+ @Persister( impl = org.hibernate.test.annotations.persister.CollectionPersister.class )
+ public Set<Card> cards;
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/persister/EntityPersister.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/persister/EntityPersister.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/persister/EntityPersister.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,19 @@
+package org.hibernate.test.annotations.persister;
+
+import org.hibernate.HibernateException;
+import org.hibernate.cache.CacheConcurrencyStrategy;
+import org.hibernate.cache.access.EntityRegionAccessStrategy;
+import org.hibernate.engine.Mapping;
+import org.hibernate.engine.SessionFactoryImplementor;
+import org.hibernate.mapping.PersistentClass;
+import org.hibernate.persister.entity.SingleTableEntityPersister;
+
+/**
+ * @author Shawn Clowater
+ */
+public class EntityPersister extends SingleTableEntityPersister {
+ public EntityPersister(PersistentClass persistentClass, EntityRegionAccessStrategy cache,
+ SessionFactoryImplementor factory, Mapping cfg) throws HibernateException {
+ super( persistentClass, cache, factory, cfg );
+ }
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/persister/PersisterTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/persister/PersisterTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/persister/PersisterTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,47 @@
+package org.hibernate.test.annotations.persister;
+
+import org.hibernate.mapping.Collection;
+import org.hibernate.mapping.PersistentClass;
+import org.hibernate.persister.entity.SingleTableEntityPersister;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * @author Shawn Clowater
+ */
+public class PersisterTest extends TestCase {
+ public PersisterTest(String x) {
+ super( x );
+ }
+
+ public void testEntityEntityPersisterAndPersisterSpecified() throws Exception {
+ //checks to see that the persister specified with the @Persister annotation takes precedence if a @Entity.persister() is also specified
+ PersistentClass persistentClass = (PersistentClass) getCfg().getClassMapping( Deck.class.getName() );
+ assertEquals( "Incorrect Persister class for " + persistentClass.getMappedClass(), EntityPersister.class,
+ persistentClass.getEntityPersisterClass() );
+ }
+
+ public void testEntityEntityPersisterSpecified() throws Exception {
+ //tests the persister specified with an @Entity.persister()
+ PersistentClass persistentClass = (PersistentClass) getCfg().getClassMapping( Card.class.getName() );
+ assertEquals( "Incorrect Persister class for " + persistentClass.getMappedClass(),
+ SingleTableEntityPersister.class, persistentClass.getEntityPersisterClass() );
+ }
+
+ public void testCollectionPersisterSpecified() throws Exception {
+ //tests the persister specified by the @Persister annotation on a collection
+ Collection collection = (Collection) getCfg().getCollectionMapping( Deck.class.getName() + ".cards" );
+ assertEquals( "Incorrect Persister class for collection " + collection.getRole(), CollectionPersister.class,
+ collection.getCollectionPersisterClass() );
+ }
+
+ /**
+ * @see org.hibernate.test.annotations.TestCase#getMappings()
+ */
+ protected Class[] getMappings() {
+ return new Class[]{
+ Card.class,
+ Deck.class
+ };
+ }
+
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/polymorphism/Car.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/polymorphism/Car.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/polymorphism/Car.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,39 @@
+//$Id: Car.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.polymorphism;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+
+import org.hibernate.annotations.PolymorphismType;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Inheritance(strategy= InheritanceType.TABLE_PER_CLASS)
+(a)org.hibernate.annotations.Entity(polymorphism = PolymorphismType.EXPLICIT)
+public class Car extends MovingThing {
+ private Integer id;
+ private String model;
+
+ public String getModel() {
+ return model;
+ }
+
+ public void setModel(String model) {
+ this.model = model;
+ }
+
+ @Id @GeneratedValue(strategy = GenerationType.TABLE )
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/polymorphism/MovingThing.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/polymorphism/MovingThing.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/polymorphism/MovingThing.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,8 @@
+//$Id: MovingThing.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.polymorphism;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class MovingThing {
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/polymorphism/PolymorphismTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/polymorphism/PolymorphismTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/polymorphism/PolymorphismTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,37 @@
+//$Id: PolymorphismTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.polymorphism;
+
+import org.hibernate.test.annotations.TestCase;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class PolymorphismTest extends TestCase {
+
+ public void testPolymorphism() throws Exception {
+ Car car = new Car();
+ car.setModel( "SUV" );
+ SportCar car2 = new SportCar();
+ car2.setModel( "350Z" );
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ tx.begin();
+ s.persist( car );
+ s.persist( car2 );
+ s.flush();
+ assertEquals( 2, s.createQuery( "select car from Car car").list().size() );
+ assertEquals( 0, s.createQuery( "select count(m) from " + MovingThing.class.getName() + " m").list().size() );
+ tx.rollback();
+ s.close();
+
+ }
+
+ protected Class[] getMappings() {
+ return new Class[] {
+ Car.class,
+ SportCar.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/polymorphism/SportCar.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/polymorphism/SportCar.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/polymorphism/SportCar.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,16 @@
+//$Id: SportCar.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.polymorphism;
+
+import javax.persistence.Entity;
+import javax.persistence.Table;
+
+import org.hibernate.annotations.PolymorphismType;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Table(name = "sport_car")
+(a)org.hibernate.annotations.Entity(polymorphism = PolymorphismType.EXPLICIT) //raise a warn
+public class SportCar extends Car {
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/Area.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/Area.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/Area.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,73 @@
+//$Id: Area.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.query;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.EntityResult;
+import javax.persistence.FieldResult;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.NamedNativeQueries;
+import javax.persistence.NamedNativeQuery;
+import javax.persistence.SqlResultSetMapping;
+import javax.persistence.SqlResultSetMappings;
+import javax.persistence.Table;
+
+/**
+ * Example of a entity load incl a join fetching of an associated *ToOne entity
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity
+@NamedNativeQueries({
+@NamedNativeQuery(
+ name = "night&area", query = "select night.id as nid, night.night_duration, night.night_date, area.id as aid, "
+ + "night.area_id, area.name from Night night, tbl_area area where night.area_id = area.id",
+ resultSetMapping = "joinMapping")
+ })
+(a)org.hibernate.annotations.NamedNativeQueries({
+(a)org.hibernate.annotations.NamedNativeQuery(
+ name = "night&areaCached",
+ query = "select night.id as nid, night.night_duration, night.night_date, area.id as aid, "
+ + "night.area_id, area.name from Night night, tbl_area area where night.area_id = area.id",
+ resultSetMapping = "joinMapping")
+ })
+@SqlResultSetMappings(
+ @SqlResultSetMapping(name = "joinMapping", entities = {
+ @EntityResult(entityClass = org.hibernate.test.annotations.query.Night.class, fields = {
+ @FieldResult(name = "id", column = "nid"),
+ @FieldResult(name = "duration", column = "night_duration"),
+ @FieldResult(name = "date", column = "night_date"),
+ @FieldResult(name = "area", column = "area_id")
+ }),
+ @EntityResult(entityClass = org.hibernate.test.annotations.query.Area.class, fields = {
+ @FieldResult(name = "id", column = "aid"),
+ @FieldResult(name = "name", column = "name")
+ })
+ }
+ )
+)
+@Table(name = "tbl_area")
+public class Area {
+ private Integer id;
+ private String name;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ @Column(unique = true)
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/Captain.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/Captain.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/Captain.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,52 @@
+//$Id: Captain.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.query;
+
+import java.io.Serializable;
+import javax.persistence.ColumnResult;
+import javax.persistence.Entity;
+import javax.persistence.EntityResult;
+import javax.persistence.FieldResult;
+import javax.persistence.Id;
+import javax.persistence.IdClass;
+import javax.persistence.SqlResultSetMapping;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+(a)IdClass(Identity.class)
+@SqlResultSetMapping(name = "compositekey",
+ entities = @EntityResult(entityClass = org.hibernate.test.annotations.query.SpaceShip.class,
+ fields = {
+ @FieldResult(name = "name", column = "name"),
+ @FieldResult(name = "model", column = "model"),
+ @FieldResult(name = "speed", column = "speed"),
+ @FieldResult(name = "dimensions.width", column = "width"),
+ @FieldResult(name = "captain.lastname", column = "lastn"),
+ @FieldResult(name = "dimensions.length", column = "length"),
+ @FieldResult(name = "captain.firstname", column = "firstn")
+ }),
+ columns = {@ColumnResult(name = "surface"),
+ @ColumnResult(name = "volume")})
+public class Captain implements Serializable {
+ private String firstname;
+ private String lastname;
+
+ @Id
+ public String getFirstname() {
+ return firstname;
+ }
+
+ public void setFirstname(String firstname) {
+ this.firstname = firstname;
+ }
+
+ @Id
+ public String getLastname() {
+ return lastname;
+ }
+
+ public void setLastname(String lastname) {
+ this.lastname = lastname;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/CasimirParticle.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/CasimirParticle.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/CasimirParticle.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,25 @@
+//$Id: CasimirParticle.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.query;
+
+import javax.persistence.Entity;
+import javax.persistence.Table;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Table(name="CASIMIR_PARTICULE")
+public class CasimirParticle {
+ @Id
+ private Long id;
+
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/Chaos.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/Chaos.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/Chaos.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,86 @@
+//$Id: Chaos.java 16293 2009-04-10 19:17:45Z gbadner $
+package org.hibernate.test.annotations.query;
+
+import java.util.Set;
+import java.util.HashSet;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.Table;
+import javax.persistence.NamedQuery;
+import javax.persistence.NamedNativeQuery;
+import javax.persistence.OneToMany;
+import javax.persistence.JoinColumn;
+import javax.persistence.Column;
+
+import org.hibernate.annotations.SQLInsert;
+import org.hibernate.annotations.SQLUpdate;
+import org.hibernate.annotations.SQLDelete;
+import org.hibernate.annotations.SQLDeleteAll;
+import org.hibernate.annotations.Loader;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Table(name="CHAOS")
+@SQLInsert( sql="INSERT INTO CHAOS(name, nick_name, chaos_size, id) VALUES(upper(?),?,?,?)")
+@SQLUpdate( sql="UPDATE CHAOS SET name = upper(?), nick_name = ?, chaos_size = ? WHERE id = ?")
+@SQLDelete( sql="DELETE CHAOS WHERE id = ?")
+@SQLDeleteAll( sql="DELETE CHAOS")
+@Loader(namedQuery = "chaos")
+@NamedNativeQuery(name="chaos", query="select id, chaos_size, name, lower( nick_name ) as nick_name from CHAOS where id= ?", resultClass = Chaos.class)
+public class Chaos {
+ @Id
+ private Long id;
+ @Column(name="chaos_size")
+ private Long size;
+ private String name;
+ @Column(name="nick_name")
+ private String nickname;
+
+ @OneToMany
+ @JoinColumn(name="chaos_fk")
+ @SQLInsert( sql="UPDATE CASIMIR_PARTICULE SET chaos_fk = ? where id = ?")
+ @SQLDelete( sql="UPDATE CASIMIR_PARTICULE SET chaos_fk = null where id = ?")
+ private Set<CasimirParticle> particles = new HashSet<CasimirParticle>();
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public Long getSize() {
+ return size;
+ }
+
+ public void setSize(Long size) {
+ this.size = size;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getNickname() {
+ return nickname;
+ }
+
+ public void setNickname(String nickname) {
+ this.nickname = nickname;
+ }
+
+ public Set<CasimirParticle> getParticles() {
+ return particles;
+ }
+
+ public void setParticles(Set<CasimirParticle> particles) {
+ this.particles = particles;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/Dictionary.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/Dictionary.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/Dictionary.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,66 @@
+//$Id: Dictionary.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.query;
+
+import javax.persistence.DiscriminatorColumn;
+import javax.persistence.DiscriminatorValue;
+import javax.persistence.Entity;
+import javax.persistence.EntityResult;
+import javax.persistence.FieldResult;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.NamedNativeQuery;
+import javax.persistence.SqlResultSetMapping;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@DiscriminatorColumn(name = "disc")
+@DiscriminatorValue("Dic")
+@SqlResultSetMapping(
+ name = "dictionary", entities = {
+@EntityResult(
+ entityClass = org.hibernate.test.annotations.query.Dictionary.class,
+ fields = {
+ @FieldResult(name = "id", column = "id"),
+ @FieldResult(name = "name", column = "name"),
+ @FieldResult(name = "editor", column = "editor")
+ },
+ discriminatorColumn = "type"
+)
+ }
+)
+@NamedNativeQuery(name = "all.dictionaries",
+ query = "select id, name, editor, disc as type from Dictionary",
+ resultSetMapping = "dictionary")
+public class Dictionary {
+ private Integer id;
+ private String name;
+ private String editor;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getEditor() {
+ return editor;
+ }
+
+ public void setEditor(String editor) {
+ this.editor = editor;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/Dimensions.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/Dimensions.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/Dimensions.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,31 @@
+//$Id: Dimensions.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.query;
+
+import javax.persistence.Embeddable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Embeddable
+public class Dimensions {
+
+
+ private int length;
+ private int width;
+
+ public int getLength() {
+ return length;
+ }
+
+ public void setLength(int length) {
+ this.length = length;
+ }
+
+ public int getWidth() {
+ return width;
+ }
+
+ public void setWidth(int width) {
+ this.width = width;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/Identity.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/Identity.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/Identity.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,47 @@
+//$Id: Identity.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.query;
+
+import java.io.Serializable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class Identity implements Serializable {
+ private String firstname;
+ private String lastname;
+
+ public String getFirstname() {
+ return firstname;
+ }
+
+ public void setFirstname(String firstname) {
+ this.firstname = firstname;
+ }
+
+ public String getLastname() {
+ return lastname;
+ }
+
+ public void setLastname(String lastname) {
+ this.lastname = lastname;
+ }
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( o == null || getClass() != o.getClass() ) return false;
+
+ final Identity identity = (Identity) o;
+
+ if ( !firstname.equals( identity.firstname ) ) return false;
+ if ( !lastname.equals( identity.lastname ) ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ int result;
+ result = firstname.hashCode();
+ result = 29 * result + lastname.hashCode();
+ return result;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/Mark.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/Mark.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/Mark.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,27 @@
+//$Id: Mark.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.query;
+
+import javax.persistence.ColumnResult;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.NamedNativeQuery;
+import javax.persistence.SqlResultSetMapping;
+
+/**
+ * Example of scalar result (not working right now)
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity
+@NamedNativeQuery(name = "average", query = "select avg(m.value) from Mark m", resultSetMapping = "columnmapping")
+@SqlResultSetMapping(
+ name = "columnmapping",
+ columns = @ColumnResult(name = "aver")
+)
+public class Mark {
+ @Id
+ @GeneratedValue
+ public int id;
+ public int value;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/Night.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/Night.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/Night.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,66 @@
+//$Id: Night.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.query;
+
+import java.util.Date;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.ManyToOne;
+import javax.persistence.NamedQuery;
+
+/**
+ * Entity declaring a named query
+ *
+ * @author Emmanuel Bernard
+ */
+@Entity
+@NamedQuery(name = "night.moreRecentThan", query = "select n from Night n where n.date >= :date")
+(a)org.hibernate.annotations.NamedQuery(
+ name = "night.duration",
+ query = "select n from Night n where n.duration = :duration",
+ cacheable = true, cacheRegion = "nightQuery"
+)
+public class Night {
+ private Integer id;
+ private long duration;
+ private Date date;
+ private Area area;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ @Column(name = "night_duration")
+ public long getDuration() {
+ return duration;
+ }
+
+ public void setDuration(long duration) {
+ this.duration = duration;
+ }
+
+ @Column(name = "night_date")
+ public Date getDate() {
+ return date;
+ }
+
+ public void setDate(Date date) {
+ this.date = date;
+ }
+
+ @ManyToOne
+ public Area getArea() {
+ return area;
+ }
+
+ public void setArea(Area area) {
+ this.area = area;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/QueryAndSQLTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/QueryAndSQLTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/QueryAndSQLTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,380 @@
+//$Id: QueryAndSQLTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.query;
+
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.List;
+
+import org.hibernate.Query;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.stat.Statistics;
+import org.hibernate.test.annotations.A320;
+import org.hibernate.test.annotations.A320b;
+import org.hibernate.test.annotations.Plane;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * Test named queries
+ *
+ * @author Emmanuel Bernard
+ */
+public class QueryAndSQLTest extends TestCase {
+ public QueryAndSQLTest(String x) {
+ super( x );
+ }
+
+ public void testPackageQueries() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Plane p = new Plane();
+ s.persist( p );
+ Query q = s.getNamedQuery( "plane.getAll" );
+ assertEquals( 1, q.list().size() );
+ tx.commit();
+ s.close();
+ }
+
+ public void testClassQueries() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Night n = new Night();
+ Calendar c = new GregorianCalendar();
+ c.set( 2000, 2, 2 );
+ Date now = c.getTime();
+ c.add( Calendar.MONTH, -1 );
+ Date aMonthAgo = c.getTime();
+ c.add( Calendar.MONTH, 2 );
+ Date inAMonth = c.getTime();
+ n.setDate( now );
+ n.setDuration( 14 );
+ s.persist( n );
+ tx.commit();
+ s.close();
+ s = openSession();
+ tx = s.beginTransaction();
+ Query q = s.getNamedQuery( "night.moreRecentThan" );
+ q.setDate( "date", aMonthAgo );
+ assertEquals( 1, q.list().size() );
+ q = s.getNamedQuery( "night.moreRecentThan" );
+ q.setDate( "date", inAMonth );
+ assertEquals( 0, q.list().size() );
+ Statistics stats = getSessions().getStatistics();
+ stats.setStatisticsEnabled( true );
+ stats.clear();
+ q = s.getNamedQuery( "night.duration" );
+ q.setParameter( "duration", 14l );
+ assertEquals( 1, q.list().size() );
+ assertEquals( 1, stats.getQueryCachePutCount() );
+ q = s.getNamedQuery( "night.duration" );
+ q.setParameter( "duration", 14l );
+ s.delete( q.list().get( 0 ) );
+ assertEquals( 1, stats.getQueryCacheHitCount() );
+ tx.commit();
+ s.close();
+ }
+
+ public void testSQLQuery() {
+ Night n = new Night();
+ Calendar c = new GregorianCalendar();
+ c.set( 2000, 2, 2 );
+ Date now = c.getTime();
+ c.add( Calendar.MONTH, -1 );
+ Date aMonthAgo = c.getTime();
+ c.add( Calendar.MONTH, 2 );
+ Date inAMonth = c.getTime();
+ n.setDate( now );
+ n.setDuration( 9999 );
+ Area area = new Area();
+ area.setName( "Monceau" );
+
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ s.persist( n );
+ s.persist( area );
+ tx.commit();
+ s.clear();
+ tx = s.beginTransaction();
+ Query q = s.getNamedQuery( "night.getAll.bySQL" );
+ q.setParameter( 0, 9990 );
+ List result = q.list();
+ assertEquals( 1, result.size() );
+ Night n2 = (Night) result.get( 0 );
+ assertEquals( n2.getDuration(), n.getDuration() );
+ List areas = s.getNamedQuery( "getAreaByNative" ).list();
+ assertTrue( 1 == areas.size() );
+ assertEquals( area.getName(), ( (Area) areas.get( 0 ) ).getName() );
+ tx.commit();
+ s.close();
+ }
+
+ public void testSQLQueryWithManyToOne() {
+ Night n = new Night();
+ Calendar c = new GregorianCalendar();
+ c.set( 2000, 2, 2 );
+ Date now = c.getTime();
+ c.add( Calendar.MONTH, -1 );
+ Date aMonthAgo = c.getTime();
+ c.add( Calendar.MONTH, 2 );
+ Date inAMonth = c.getTime();
+ n.setDate( now );
+ n.setDuration( 9999 );
+ Area a = new Area();
+ a.setName( "Paris" );
+ n.setArea( a );
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ s.persist( a );
+ s.persist( n );
+ tx.commit();
+ s.close();
+ s = openSession();
+ tx = s.beginTransaction();
+ Statistics stats = getSessions().getStatistics();
+ stats.setStatisticsEnabled( true );
+ Query q = s.getNamedQuery( "night&areaCached" );
+ List result = q.list();
+ assertEquals( 1, result.size() );
+ assertEquals( 1, stats.getQueryCachePutCount() );
+ q.list();
+ assertEquals( 1, stats.getQueryCacheHitCount() );
+ Night n2 = (Night) ( (Object[]) result.get( 0 ) )[0];
+ assertEquals( n2.getDuration(), n.getDuration() );
+ tx.commit();
+ s.close();
+ }
+
+ public void testImplicitNativeQuery() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ SpaceShip ship = new SpaceShip();
+ ship.setModel( "X-Wing" );
+ ship.setName( "YuBlue" );
+ ship.setSpeed( 2000 );
+ ship.setDimensions( new Dimensions() );
+ s.persist( ship );
+ tx.commit();
+ s.clear();
+ tx = s.beginTransaction();
+ Query q = s.getNamedQuery( "implicitSample" );
+ List result = q.list();
+ assertEquals( 1, result.size() );
+ assertEquals( ship.getModel(), ( (SpaceShip) result.get( 0 ) ).getModel() );
+ s.delete( result.get( 0 ) );
+ tx.commit();
+ s.close();
+ }
+
+ public void testNativeQueryAndCompositePKAndComponents() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ SpaceShip ship = new SpaceShip();
+ ship.setModel( "X-Wing" );
+ ship.setName( "YuBlue" );
+ ship.setSpeed( 2000 );
+ ship.setDimensions( new Dimensions() );
+ ship.getDimensions().setLength( 10 );
+ ship.getDimensions().setWidth( 5 );
+ Captain captain = new Captain();
+ captain.setFirstname( "Luke" );
+ captain.setLastname( "Skywalker" );
+ ship.setCaptain( captain );
+ s.persist( captain );
+ s.persist( ship );
+ tx.commit();
+ s.clear();
+ tx = s.beginTransaction();
+ Query q = s.getNamedQuery( "compositekey" );
+ List result = q.list();
+ assertEquals( 1, result.size() );
+ Object[] row = (Object[]) result.get( 0 );
+ SpaceShip spaceShip = (SpaceShip) row[0];
+ assertEquals( ship.getModel(), spaceShip.getModel() );
+ assertNotNull( spaceShip.getDimensions() );
+ assertEquals( ship.getDimensions().getWidth(), spaceShip.getDimensions().getWidth() );
+ assertEquals( ship.getDimensions().getLength(), spaceShip.getDimensions().getLength() );
+ assertEquals( ship.getCaptain().getFirstname(), ship.getCaptain().getFirstname() );
+ assertEquals( ship.getCaptain().getLastname(), ship.getCaptain().getLastname() );
+ //FIXME vary depending on databases
+ assertTrue( row[1].toString().startsWith( "50" ) );
+ assertTrue( row[2].toString().startsWith( "500" ) );
+ s.delete( spaceShip.getCaptain() );
+ s.delete( spaceShip );
+ tx.commit();
+ s.close();
+ }
+
+ public void testDiscriminator() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Dictionary dic = new Dictionary();
+ dic.setName( "Anglais-Francais" );
+ dic.setEditor( "Harrap's" );
+ SynonymousDictionary syn = new SynonymousDictionary();
+ syn.setName( "Synonymes de tous les temps" );
+ syn.setEditor( "Imagination edition" );
+ s.persist( dic );
+ s.persist( syn );
+ tx.commit();
+ s.clear();
+ tx = s.beginTransaction();
+ List results = s.getNamedQuery( "all.dictionaries" ).list();
+ assertEquals( 2, results.size() );
+ assertTrue(
+ results.get( 0 ) instanceof SynonymousDictionary
+ || results.get( 1 ) instanceof SynonymousDictionary
+ );
+ tx.commit();
+ s.close();
+ }
+
+// public void testScalarQuery() throws Exception {
+// Session s = openSession();
+// Transaction tx;
+// tx = s.beginTransaction();
+// Mark bad = new Mark();
+// bad.value = 5;
+// Mark good = new Mark();
+// good.value = 15;
+// s.persist(bad);
+// s.persist(good);
+// tx.commit();
+// s.clear();
+// tx = s.beginTransaction();
+// List result = s.getNamedQuery("average").list();
+// assertEquals( 1, result.size() );
+// tx.commit();
+// s.close();
+//
+// }
+
+ public void testCache() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Plane plane = new Plane();
+ plane.setNbrOfSeats( 5 );
+ s.persist( plane );
+ tx.commit();
+ s.close();
+ getSessions().getStatistics().clear();
+ getSessions().getStatistics().setStatisticsEnabled( true );
+ s = openSession();
+ tx = s.beginTransaction();
+ Query query = s.getNamedQuery( "plane.byId" ).setParameter( "id", plane.getId() );
+ plane = (Plane) query.uniqueResult();
+ assertEquals( 1, getSessions().getStatistics().getQueryCachePutCount() );
+ plane = (Plane) s.getNamedQuery( "plane.byId" ).setParameter( "id", plane.getId() ).uniqueResult();
+ assertEquals( 1, getSessions().getStatistics().getQueryCacheHitCount() );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ s.delete( s.get( Plane.class, plane.getId() ) );
+ tx.commit();
+ s.close();
+ }
+
+ public void testEntitySQLOverriding() {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Chaos chaos = new Chaos();
+ chaos.setSize( 123l );
+ chaos.setId( 1l );
+
+ String lowerName = "hello";
+ String upperName = lowerName.toUpperCase();
+ assertFalse( lowerName.equals( upperName ) );
+
+ chaos.setName( "hello" );
+ chaos.setNickname( "NickName" );
+ s.persist( chaos );
+ s.flush();
+ s.clear();
+ s.getSessionFactory().evict( Chaos.class );
+
+ Chaos resultChaos = (Chaos) s.load( Chaos.class, chaos.getId() );
+ assertEquals( upperName, resultChaos.getName() );
+ assertEquals( "nickname", resultChaos.getNickname() );
+
+ tx.rollback();
+ s.close();
+ }
+
+ public void testCollectionSQLOverriding() {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Chaos chaos = new Chaos();
+ chaos.setSize( 123l );
+ chaos.setId( 1l );
+
+ chaos.setName( "hello" );
+ s.persist( chaos );
+ CasimirParticle p = new CasimirParticle();
+ p.setId( 1l );
+ s.persist( p );
+ chaos.getParticles().add(p);
+ p = new CasimirParticle();
+ p.setId( 2l );
+ s.persist( p );
+ chaos.getParticles().add(p);
+ s.flush();
+ s.clear();
+ s.getSessionFactory().evict( Chaos.class );
+
+ Chaos resultChaos = (Chaos) s.load( Chaos.class, chaos.getId() );
+ assertEquals( 2, resultChaos.getParticles().size() );
+ resultChaos.getParticles().remove( resultChaos.getParticles().iterator().next() );
+ resultChaos.getParticles().remove( resultChaos.getParticles().iterator().next() );
+ s.flush();
+
+ s.clear();
+ resultChaos = (Chaos) s.load( Chaos.class, chaos.getId() );
+ assertEquals( 0, resultChaos.getParticles().size() );
+
+ tx.rollback();
+ s.close();
+ }
+
+ protected Class[] getMappings() {
+ return new Class[]{
+ Plane.class,
+ A320.class,
+ A320b.class,
+ Night.class,
+ Area.class,
+ SpaceShip.class,
+ Dictionary.class,
+ SynonymousDictionary.class,
+ Captain.class,
+ Chaos.class,
+ CasimirParticle.class
+ };
+ }
+
+ protected String[] getAnnotatedPackages() {
+ return new String[]{
+ "org.hibernate.test.annotations.query"
+ };
+ }
+
+ @Override
+ protected String[] getXmlFiles() {
+ return new String[]{
+ "org/hibernate/test/annotations/query/orm.xml"
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/SpaceShip.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/SpaceShip.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/SpaceShip.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,80 @@
+//$Id: SpaceShip.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.query;
+
+import javax.persistence.Entity;
+import javax.persistence.EntityResult;
+import javax.persistence.FetchType;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinColumns;
+import javax.persistence.ManyToOne;
+import javax.persistence.NamedNativeQueries;
+import javax.persistence.NamedNativeQuery;
+import javax.persistence.SqlResultSetMapping;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@SqlResultSetMapping(name = "implicit",
+ entities = @EntityResult(entityClass = org.hibernate.test.annotations.query.SpaceShip.class))
+@NamedNativeQueries({
+@NamedNativeQuery(name = "implicitSample", query = "select * from SpaceShip", resultSetMapping = "implicit"),
+@NamedNativeQuery(name = "compositekey",
+ query = "select name, model, speed, lname as lastn, fname as firstn, length, width, length * width as surface, length * width *10 as volume from SpaceShip",
+ resultSetMapping = "compositekey")
+ })
+//we're missins @SqlREsultSetMappings so look at Captain
+public class SpaceShip {
+ private String name;
+ private String model;
+ private double speed;
+ private Captain captain;
+ private Dimensions dimensions;
+
+ @Id
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @ManyToOne(fetch = FetchType.LAZY)
+ @JoinColumns({
+ @JoinColumn(name = "fname", referencedColumnName = "firstname"),
+ @JoinColumn(name = "lname", referencedColumnName = "lastname")
+ })
+ public Captain getCaptain() {
+ return captain;
+ }
+
+ public void setCaptain(Captain captain) {
+ this.captain = captain;
+ }
+
+ public String getModel() {
+ return model;
+ }
+
+ public void setModel(String model) {
+ this.model = model;
+ }
+
+ public double getSpeed() {
+ return speed;
+ }
+
+ public void setSpeed(double speed) {
+ this.speed = speed;
+ }
+
+ public Dimensions getDimensions() {
+ return dimensions;
+ }
+
+ public void setDimensions(Dimensions dimensions) {
+ this.dimensions = dimensions;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/SynonymousDictionary.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/SynonymousDictionary.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/SynonymousDictionary.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,13 @@
+//$Id: SynonymousDictionary.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.query;
+
+import javax.persistence.DiscriminatorValue;
+import javax.persistence.Entity;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@DiscriminatorValue("Syn")
+public class SynonymousDictionary extends Dictionary {
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/orm.xml
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/orm.xml (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/query/orm.xml 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ version="1.0"
+ >
+ <named-query name="plane.getAll">
+ <query>select p from Plane p</query>
+ </named-query>
+ <named-native-query name="night.getAll.bySQL" result-set-mapping="sqlmapping">
+ <query>select id, night_duration, night_date as dte, area_id from Night where night_duration > ?</query>
+ </named-native-query>
+ <named-native-query name="getAreaByNative" result-class="org.hibernate.test.annotations.query.Area">
+ <query>select * from tbl_area</query>
+ </named-native-query>
+ <sql-result-set-mapping name="sqlmapping">
+ <entity-result entity-class="org.hibernate.test.annotations.query.Night">
+ <field-result name="id" column="id"/>
+ <field-result name="duration" column="night_duration"/>
+ <field-result name="date" column="dte"/>
+ <field-result name="area" column="area_id"/>
+ </entity-result>
+ </sql-result-set-mapping>
+</entity-mappings>
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/quote/QuoteTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/quote/QuoteTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/quote/QuoteTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,35 @@
+//$Id: QuoteTest.java 14735 2008-06-04 14:05:50Z hardy.ferentschik $
+package org.hibernate.test.annotations.quote;
+
+import org.hibernate.test.annotations.TestCase;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class QuoteTest extends TestCase {
+ public void testQuoteManytoMany() {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ User u = new User();
+ s.persist( u );
+ Role r = new Role();
+ s.persist( r );
+ u.getRoles().add( r );
+ s.flush();
+ s.clear();
+ u = (User) s.get( User.class, u.getId() );
+ assertEquals( 1, u.getRoles().size() );
+ tx.rollback();
+ String role = User.class.getName() + ".roles";
+ assertEquals( "User_Role", getCfg().getCollectionMapping( role ).getCollectionTable().getName() );
+ s.close();
+ }
+ protected Class[] getMappings() {
+ return new Class[] {
+ User.class,
+ Role.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/quote/Role.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/quote/Role.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/quote/Role.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,22 @@
+//$Id: Role.java 14735 2008-06-04 14:05:50Z hardy.ferentschik $
+package org.hibernate.test.annotations.quote;
+
+import java.io.Serializable;
+import javax.persistence.Id;
+import javax.persistence.Entity;
+import javax.persistence.GenerationType;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Table;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Table(name = "`Role`")
+public class Role implements Serializable {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ private long id;
+
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/quote/User.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/quote/User.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/quote/User.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,44 @@
+//$Id: User.java 14735 2008-06-04 14:05:50Z hardy.ferentschik $
+package org.hibernate.test.annotations.quote;
+
+import java.io.Serializable;
+import java.util.Set;
+import java.util.HashSet;
+import javax.persistence.ManyToMany;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Table;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Table(name = "`User`")
+public class User implements Serializable {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ private long id;
+
+ @ManyToMany
+ private Set<Role> roles = new HashSet<Role>();
+
+
+ public long getId() {
+ return id;
+ }
+
+ public void setId(long id) {
+ this.id = id;
+ }
+
+ public Set<Role> getRoles() {
+ return roles;
+ }
+
+ public void setRoles(Set<Role> roles) {
+ this.roles = roles;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/Bag.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/Bag.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/Bag.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,56 @@
+//$Id: Bag.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.referencedcolumnname;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Bag {
+ private Integer id;
+ private String serial;
+ private Rambler owner;
+
+ public Bag() {
+ }
+
+ public Bag(String serial, Rambler owner) {
+ this.serial = serial;
+ this.owner = owner;
+ }
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ @Column(unique = true)
+ public String getSerial() {
+ return serial;
+ }
+
+ public void setSerial(String serial) {
+ this.serial = serial;
+ }
+
+ @ManyToOne
+ @JoinColumn(referencedColumnName = "fld_name")
+ public Rambler getOwner() {
+ return owner;
+ }
+
+ public void setOwner(Rambler owner) {
+ this.owner = owner;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/Clothes.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/Clothes.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/Clothes.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,69 @@
+//$Id: Clothes.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.referencedcolumnname;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Clothes {
+ private Integer id;
+ private String type;
+ private String flavor;
+
+ public Clothes() {
+ }
+
+ public Clothes(String type, String flavor) {
+ this.type = type;
+ this.flavor = flavor;
+ }
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public String getFlavor() {
+ return flavor;
+ }
+
+ public void setFlavor(String flavor) {
+ this.flavor = flavor;
+ }
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( !( o instanceof Clothes ) ) return false;
+
+ final Clothes clothes = (Clothes) o;
+
+ if ( !flavor.equals( clothes.flavor ) ) return false;
+ if ( !type.equals( clothes.type ) ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ int result;
+ result = type.hashCode();
+ result = 29 * result + flavor.hashCode();
+ return result;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/House.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/House.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/House.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,80 @@
+//$Id: House.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.referencedcolumnname;
+
+import java.io.Serializable;
+import java.util.HashSet;
+import java.util.Set;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinTable;
+import javax.persistence.ManyToMany;
+import javax.persistence.ManyToOne;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class House implements Serializable {
+ private Integer id;
+ private String address;
+ private Postman postman;
+ private Set<Inhabitant> hasInhabitants = new HashSet<Inhabitant>();
+
+ @ManyToOne
+ @JoinColumn(referencedColumnName = "name")
+ public Postman getPostman() {
+ return postman;
+ }
+
+ public void setPostman(Postman postman) {
+ this.postman = postman;
+ }
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getAddress() {
+ return address;
+ }
+
+ public void setAddress(String address) {
+ this.address = address;
+ }
+
+ @ManyToMany
+ @JoinTable(joinColumns = @JoinColumn(referencedColumnName = "address"),
+ inverseJoinColumns = @JoinColumn(referencedColumnName = "name")
+ )
+ public Set<Inhabitant> getHasInhabitants() {
+ return hasInhabitants;
+ }
+
+ public void setHasInhabitants(Set<Inhabitant> hasInhabitants) {
+ this.hasInhabitants = hasInhabitants;
+ }
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( !( o instanceof House ) ) return false;
+
+ final House house = (House) o;
+
+ if ( address != null ? !address.equals( house.address ) : house.address != null ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ return ( address != null ? address.hashCode() : 0 );
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/Inhabitant.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/Inhabitant.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/Inhabitant.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,62 @@
+//$Id: Inhabitant.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.referencedcolumnname;
+
+import java.io.Serializable;
+import java.util.HashSet;
+import java.util.Set;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.ManyToMany;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Inhabitant implements Serializable {
+ private Integer id;
+ private String name;
+ private Set<House> livesIn = new HashSet<House>();
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @ManyToMany(mappedBy = "hasInhabitants")
+ public Set<House> getLivesIn() {
+ return livesIn;
+ }
+
+ public void setLivesIn(Set<House> livesIn) {
+ this.livesIn = livesIn;
+ }
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( !( o instanceof Inhabitant ) ) return false;
+
+ final Inhabitant inhabitant = (Inhabitant) o;
+
+ if ( name != null ? !name.equals( inhabitant.name ) : inhabitant.name != null ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ return ( name != null ? name.hashCode() : 0 );
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/Item.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/Item.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/Item.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,23 @@
+//$Id: Item.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.referencedcolumnname;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Item {
+ int id;
+
+ @Id
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/ItemCost.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/ItemCost.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/ItemCost.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,55 @@
+//$Id: ItemCost.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.referencedcolumnname;
+
+import java.math.BigDecimal;
+import java.io.Serializable;
+import javax.persistence.Id;
+import javax.persistence.Entity;
+import javax.persistence.ManyToOne;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class ItemCost implements Serializable {
+ int id;
+ Item item;
+ Vendor vendor;
+ BigDecimal cost;
+
+
+ @Id
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ @ManyToOne
+ public Item getItem() {
+ return item;
+ }
+
+ public void setItem(Item item) {
+ this.item = item;
+ }
+
+ @ManyToOne
+ public Vendor getVendor() {
+ return vendor;
+ }
+
+ public void setVendor(Vendor vendor) {
+ this.vendor = vendor;
+ }
+
+ public BigDecimal getCost() {
+ return cost;
+ }
+
+ public void setCost(BigDecimal cost) {
+ this.cost = cost;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/Luggage.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/Luggage.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/Luggage.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,90 @@
+//$Id: Luggage.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.referencedcolumnname;
+
+import java.io.Serializable;
+import java.util.HashSet;
+import java.util.Set;
+import javax.persistence.CascadeType;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinColumns;
+import javax.persistence.OneToMany;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Luggage implements Serializable {
+ private Integer id;
+ private String owner;
+ private String type;
+ private Set<Clothes> hasInside = new HashSet<Clothes>();
+
+ public Luggage() {
+ }
+
+ public Luggage(String owner, String type) {
+ this.owner = owner;
+ this.type = type;
+ }
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getOwner() {
+ return owner;
+ }
+
+ public void setOwner(String owner) {
+ this.owner = owner;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ @OneToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
+ @JoinColumns({
+ @JoinColumn(name = "lug_type", referencedColumnName = "type"),
+ @JoinColumn(name = "lug_owner", referencedColumnName = "owner")
+ })
+ public Set<Clothes> getHasInside() {
+ return hasInside;
+ }
+
+ public void setHasInside(Set<Clothes> hasInside) {
+ this.hasInside = hasInside;
+ }
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( !( o instanceof Luggage ) ) return false;
+
+ final Luggage luggage = (Luggage) o;
+
+ if ( !owner.equals( luggage.owner ) ) return false;
+ if ( !type.equals( luggage.type ) ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ int result;
+ result = owner.hashCode();
+ result = 29 * result + type.hashCode();
+ return result;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/Postman.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/Postman.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/Postman.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,40 @@
+//$Id: Postman.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.referencedcolumnname;
+
+import java.io.Serializable;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Postman implements Serializable {
+ private String name;
+ private String id;
+
+ public Postman() {
+ }
+
+ @Id
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public Postman(String name, String id) {
+ this.name = name;
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/Rambler.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/Rambler.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/Rambler.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,57 @@
+//$Id: Rambler.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.referencedcolumnname;
+
+import java.io.Serializable;
+import java.util.HashSet;
+import java.util.Set;
+import javax.persistence.CascadeType;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.OneToMany;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Rambler implements Serializable {
+ private Integer id;
+ private String name;
+ private Set<Bag> bags = new HashSet<Bag>();
+
+ public Rambler() {
+ }
+
+ public Rambler(String name) {
+ this.name = name;
+ }
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ @Column(name = "fld_name")
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @OneToMany(mappedBy = "owner", cascade = {CascadeType.PERSIST, CascadeType.MERGE})
+ public Set<Bag> getBags() {
+ return bags;
+ }
+
+ public void setBags(Set<Bag> bags) {
+ this.bags = bags;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/ReferencedColumnNameTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/ReferencedColumnNameTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/ReferencedColumnNameTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,196 @@
+//$Id: ReferencedColumnNameTest.java 16289 2009-04-09 22:09:50Z gbadner $
+package org.hibernate.test.annotations.referencedcolumnname;
+
+import java.util.Iterator;
+import java.math.BigDecimal;
+
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class ReferencedColumnNameTest extends TestCase {
+ public void testManyToOne() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Postman pm = new Postman( "Bob", "A01" );
+ House house = new House();
+ house.setPostman( pm );
+ house.setAddress( "Rue des pres" );
+ s.persist( pm );
+ s.persist( house );
+ tx.commit();
+ s.close();
+ s = openSession();
+ tx = s.beginTransaction();
+ house = (House) s.get( House.class, house.getId() );
+ assertNotNull( house.getPostman() );
+ assertEquals( "Bob", house.getPostman().getName() );
+ pm = house.getPostman();
+ s.delete( house );
+ s.delete( pm );
+ tx.commit();
+ s.close();
+ }
+
+ public void testOneToMany() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+
+ Rambler rambler = new Rambler( "Emmanuel" );
+ Bag bag = new Bag( "0001", rambler );
+ rambler.getBags().add( bag );
+ s.persist( rambler );
+
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+
+ bag = (Bag) s.createQuery( "select b from Bag b left join fetch b.owner" ).uniqueResult();
+ assertNotNull( bag );
+ assertNotNull( bag.getOwner() );
+
+ rambler = (Rambler) s.createQuery( "select r from Rambler r left join fetch r.bags" ).uniqueResult();
+ assertNotNull( rambler );
+ assertNotNull( rambler.getBags() );
+ assertEquals( 1, rambler.getBags().size() );
+ s.delete( rambler.getBags().iterator().next() );
+ s.delete( rambler );
+
+ tx.commit();
+ s.close();
+ }
+
+ public void testUnidirectionalOneToMany() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+
+ Clothes clothes = new Clothes( "underwear", "interesting" );
+ Luggage luggage = new Luggage( "Emmanuel", "Cabin Luggage" );
+ luggage.getHasInside().add( clothes );
+ s.persist( luggage );
+
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+
+ luggage = (Luggage) s.createQuery( "select l from Luggage l left join fetch l.hasInside" ).uniqueResult();
+ assertNotNull( luggage );
+ assertNotNull( luggage.getHasInside() );
+ assertEquals( 1, luggage.getHasInside().size() );
+
+ s.delete( luggage.getHasInside().iterator().next() );
+ s.delete( luggage );
+
+ tx.commit();
+ s.close();
+ }
+
+ public void testManyToMany() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+
+ House whiteHouse = new House();
+ whiteHouse.setAddress( "1600 Pennsylvania Avenue, Washington" );
+ Inhabitant bill = new Inhabitant();
+ bill.setName( "Bill Clinton" );
+ Inhabitant george = new Inhabitant();
+ george.setName( "George W Bush" );
+ s.persist( george );
+ s.persist( bill );
+ whiteHouse.getHasInhabitants().add( bill );
+ whiteHouse.getHasInhabitants().add( george );
+ //bill.getLivesIn().add( whiteHouse );
+ //george.getLivesIn().add( whiteHouse );
+
+ s.persist( whiteHouse );
+ tx.commit();
+ s = openSession();
+ tx = s.beginTransaction();
+
+ whiteHouse = (House) s.get( House.class, whiteHouse.getId() );
+ assertNotNull( whiteHouse );
+ assertEquals( 2, whiteHouse.getHasInhabitants().size() );
+
+ tx.commit();
+ s.clear();
+ tx = s.beginTransaction();
+ bill = (Inhabitant) s.get( Inhabitant.class, bill.getId() );
+ assertNotNull( bill );
+ assertEquals( 1, bill.getLivesIn().size() );
+ assertEquals( whiteHouse.getAddress(), bill.getLivesIn().iterator().next().getAddress() );
+
+ whiteHouse = bill.getLivesIn().iterator().next();
+ s.delete( whiteHouse );
+ Iterator it = whiteHouse.getHasInhabitants().iterator();
+ while ( it.hasNext() ) {
+ s.delete( it.next() );
+ }
+ tx.commit();
+ s.close();
+ }
+
+ public void testManyToOneReferenceManyToOne() throws Exception {
+ Item item = new Item();
+ item.setId( 1 );
+ Vendor vendor = new Vendor();
+ vendor.setId( 1 );
+ ItemCost cost = new ItemCost();
+ cost.setCost( new BigDecimal(1) );
+ cost.setId( 1 );
+ cost.setItem( item );
+ cost.setVendor( vendor );
+ WarehouseItem wItem = new WarehouseItem();
+ wItem.setDefaultCost( cost );
+ wItem.setId( 1 );
+ wItem.setItem( item );
+ wItem.setQtyInStock( new BigDecimal(1) );
+ wItem.setVendor( vendor );
+ Session s = openSession( );
+ s.getTransaction().begin();
+ s.persist( item );
+ s.persist( vendor );
+ s.persist( cost );
+ s.persist( wItem );
+ s.flush();
+ s.clear();
+ wItem = (WarehouseItem) s.get(WarehouseItem.class, wItem.getId() );
+ assertNotNull( wItem.getDefaultCost().getItem() );
+ s.getTransaction().rollback();
+ s.close();
+ }
+
+ public ReferencedColumnNameTest(String x) {
+ super( x );
+ }
+
+ protected Class[] getMappings() {
+ return new Class[]{
+ House.class,
+ Postman.class,
+ Bag.class,
+ Rambler.class,
+ Luggage.class,
+ Clothes.class,
+ Inhabitant.class,
+ Item.class,
+ ItemCost.class,
+ Vendor.class,
+ WarehouseItem.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/Vendor.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/Vendor.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/Vendor.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,24 @@
+//$Id: Vendor.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.referencedcolumnname;
+
+import javax.persistence.Id;
+import javax.persistence.Entity;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Vendor {
+ int id;
+
+ @Id
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+}
+
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/WarehouseItem.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/WarehouseItem.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/referencedcolumnname/WarehouseItem.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,71 @@
+//$Id: WarehouseItem.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.referencedcolumnname;
+
+import java.math.BigDecimal;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.JoinColumns;
+import javax.persistence.ManyToOne;
+import javax.persistence.JoinColumn;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class WarehouseItem {
+
+ int id;
+ Item item;
+ Vendor vendor;
+ ItemCost defaultCost;
+ BigDecimal qtyInStock;
+
+ @Id
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ public BigDecimal getQtyInStock() {
+ return qtyInStock;
+ }
+
+ public void setQtyInStock(BigDecimal qtyInStock) {
+ this.qtyInStock = qtyInStock;
+ }
+
+ @ManyToOne
+ public Item getItem() {
+ return item;
+ }
+
+ public void setItem(Item item) {
+ this.item = item;
+ }
+
+ @ManyToOne
+ public Vendor getVendor() {
+ return vendor;
+ }
+
+ public void setVendor(Vendor vendor) {
+ this.vendor = vendor;
+ }
+
+ @ManyToOne
+ @JoinColumns({
+ @JoinColumn(name="vendor_id", referencedColumnName="vendor_id", insertable=false, updatable=false),
+ @JoinColumn(name="item_id", referencedColumnName="item_id", insertable=false, updatable=false)
+ })
+ public ItemCost getDefaultCost() {
+ return defaultCost;
+ }
+
+ public void setDefaultCost(ItemCost defaultCost) {
+ this.defaultCost = defaultCost;
+ }
+}
+
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/Administration.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/Administration.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/Administration.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,77 @@
+//$Id: Administration.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.reflection;
+
+import javax.persistence.Basic;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinColumns;
+import javax.persistence.OneToOne;
+import javax.persistence.PostLoad;
+import javax.persistence.SecondaryTable;
+import javax.persistence.Table;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity(name = "JavaAdministration")
+@Table(name = "JavaAdministration")
+@SecondaryTable(name = "Extend")
+public class Administration extends Organization {
+ @Id
+ private Integer id;
+ private String firstname;
+ private String lastname;
+ private String address;
+ private Integer version;
+ @Basic
+ private String transientField;
+ @OneToOne
+ @JoinColumns({@JoinColumn(name = "busNumber_fk"), @JoinColumn(name = "busDriver_fk")})
+ private BusTrip defaultBusTrip;
+
+ public String getAddress() {
+ return address;
+ }
+
+ public void setAddress(String address) {
+ this.address = address;
+ }
+
+ public Integer getVersion() {
+ return version;
+ }
+
+ public void setVersion(Integer version) {
+ this.version = version;
+ }
+
+ public String getFirstname() {
+ return firstname;
+ }
+
+ public void setFirstname(String firstname) {
+ this.firstname = firstname;
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getLastname() {
+ return lastname;
+ }
+
+ public void setLastname(String lastname) {
+ this.lastname = lastname;
+ }
+
+ @PostLoad
+ public void calculate() {
+ //...
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/Availability.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/Availability.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/Availability.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,10 @@
+//$Id: Availability.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.reflection;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public enum Availability {
+ ON_DUTY,
+ NO_SERVICE
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/BusTrip.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/BusTrip.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/BusTrip.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,54 @@
+//$Id: BusTrip.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.reflection;
+
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+import javax.persistence.EmbeddedId;
+import javax.persistence.Entity;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class BusTrip {
+ private BusTripPk id;
+ private Availability status;
+ private byte[] serial;
+ private Date terminusTime;
+ private Map<String, SocialSecurityPhysicalAccount> players;
+ private List roads;
+
+ @EmbeddedId
+ public BusTripPk getId() {
+ return id;
+ }
+
+ public void setId(BusTripPk id) {
+ this.id = id;
+ }
+
+ public Availability getStatus() {
+ return status;
+ }
+
+ public void setStatus(Availability status) {
+ this.status = status;
+ }
+
+ public byte[] getSerial() {
+ return serial;
+ }
+
+ public void setSerial(byte[] serial) {
+ this.serial = serial;
+ }
+
+ public Date getTerminusTime() {
+ return terminusTime;
+ }
+
+ public void setTerminusTime(Date terminusTime) {
+ this.terminusTime = terminusTime;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/BusTripPk.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/BusTripPk.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/BusTripPk.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,26 @@
+//$Id: BusTripPk.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.reflection;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class BusTripPk {
+ private String busNumber;
+ private String busDriver;
+
+ public String getBusDriver() {
+ return busDriver;
+ }
+
+ public void setBusDriver(String busDriver) {
+ this.busDriver = busDriver;
+ }
+
+ public String getBusNumber() {
+ return busNumber;
+ }
+
+ public void setBusNumber(String busNumber) {
+ this.busNumber = busNumber;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/Competition.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/Competition.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/Competition.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,11 @@
+//$Id: Competition.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.reflection;
+
+import javax.persistence.MappedSuperclass;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@MappedSuperclass
+public class Competition {
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/EJB3OverridenAnnotationReaderTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/EJB3OverridenAnnotationReaderTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/EJB3OverridenAnnotationReaderTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,434 @@
+//$Id: EJB3OverridenAnnotationReaderTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.reflection;
+
+import java.io.BufferedInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.List;
+import javax.persistence.AssociationOverrides;
+import javax.persistence.AttributeOverrides;
+import javax.persistence.Basic;
+import javax.persistence.Column;
+import javax.persistence.DiscriminatorColumn;
+import javax.persistence.DiscriminatorValue;
+import javax.persistence.Embedded;
+import javax.persistence.EmbeddedId;
+import javax.persistence.Entity;
+import javax.persistence.EnumType;
+import javax.persistence.Enumerated;
+import javax.persistence.ExcludeDefaultListeners;
+import javax.persistence.ExcludeSuperclassListeners;
+import javax.persistence.FetchType;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.IdClass;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+import javax.persistence.JoinColumns;
+import javax.persistence.JoinTable;
+import javax.persistence.Lob;
+import javax.persistence.ManyToMany;
+import javax.persistence.MapKey;
+import javax.persistence.MappedSuperclass;
+import javax.persistence.NamedNativeQueries;
+import javax.persistence.NamedQueries;
+import javax.persistence.OneToMany;
+import javax.persistence.OneToOne;
+import javax.persistence.OrderBy;
+import javax.persistence.PrimaryKeyJoinColumn;
+import javax.persistence.PrimaryKeyJoinColumns;
+import javax.persistence.SecondaryTable;
+import javax.persistence.SecondaryTables;
+import javax.persistence.SequenceGenerator;
+import javax.persistence.SqlResultSetMappings;
+import javax.persistence.Table;
+import javax.persistence.TableGenerator;
+import javax.persistence.Temporal;
+import javax.persistence.TemporalType;
+import javax.persistence.Transient;
+import javax.persistence.Version;
+import javax.persistence.PrePersist;
+import javax.persistence.EntityListeners;
+import javax.persistence.PostLoad;
+import javax.persistence.PostPersist;
+
+import junit.framework.TestCase;
+import org.dom4j.DocumentException;
+import org.dom4j.io.SAXReader;
+import org.hibernate.annotations.Columns;
+import org.hibernate.cfg.EJB3DTDEntityResolver;
+import org.hibernate.cfg.annotations.reflection.EJB3OverridenAnnotationReader;
+import org.hibernate.cfg.annotations.reflection.XMLContext;
+import org.hibernate.util.XMLHelper;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+import org.xml.sax.SAXNotSupportedException;
+
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class EJB3OverridenAnnotationReaderTest extends TestCase {
+ public void testMappedSuperclassAnnotations() throws Exception {
+ XMLContext context = buildContext(
+ "org/hibernate/test/annotations/reflection/metadata-complete.xml" );
+ EJB3OverridenAnnotationReader reader = new EJB3OverridenAnnotationReader( Organization.class, context );
+ assertTrue( reader.isAnnotationPresent( MappedSuperclass.class ) );
+ }
+
+ public void testEntityRelatedAnnotations() throws Exception {
+ XMLContext context = buildContext( "org/hibernate/test/annotations/reflection/orm.xml" );
+ EJB3OverridenAnnotationReader reader = new EJB3OverridenAnnotationReader( Administration.class, context );
+ assertNotNull( reader.getAnnotation( Entity.class ) );
+ assertEquals(
+ "Default value in xml entity should not override @Entity.name", "JavaAdministration",
+ reader.getAnnotation( Entity.class ).name()
+ );
+ assertNotNull( reader.getAnnotation( Table.class ) );
+ assertEquals( "@Table not overriden", "tbl_admin", reader.getAnnotation( Table.class ).name() );
+ assertEquals( "Default schema not overriden", "myschema", reader.getAnnotation( Table.class ).schema() );
+ assertEquals(
+ "Proper @Table.uniqueConstraints", 2,
+ reader.getAnnotation( Table.class ).uniqueConstraints()[0].columnNames().length
+ );
+ String columnName = reader.getAnnotation( Table.class ).uniqueConstraints()[0].columnNames()[0];
+ assertTrue(
+ "Proper @Table.uniqueConstraints", "firstname".equals( columnName ) || "lastname".equals( columnName )
+ );
+ assertNull( "Both Java and XML used", reader.getAnnotation( SecondaryTable.class ) );
+ assertNotNull( "XML does not work", reader.getAnnotation( SecondaryTables.class ) );
+ SecondaryTable[] tables = reader.getAnnotation( SecondaryTables.class ).value();
+ assertEquals( 1, tables.length );
+ assertEquals( "admin2", tables[0].name() );
+ assertEquals( "unique constraints ignored", 1, tables[0].uniqueConstraints().length );
+ assertEquals( "pk join column ignored", 1, tables[0].pkJoinColumns().length );
+ assertEquals( "pk join column ignored", "admin_id", tables[0].pkJoinColumns()[0].name() );
+ assertNotNull( "Sequence Overriding not working", reader.getAnnotation( SequenceGenerator.class ) );
+ assertEquals(
+ "wrong sequence name", "seqhilo", reader.getAnnotation( SequenceGenerator.class ).sequenceName()
+ );
+ assertEquals( "default fails", 50, reader.getAnnotation( SequenceGenerator.class ).allocationSize() );
+ assertNotNull( "TableOverriding not working", reader.getAnnotation( TableGenerator.class ) );
+ assertEquals( "wrong tble name", "tablehilo", reader.getAnnotation( TableGenerator.class ).table() );
+ assertEquals( "no schema overriding", "myschema", reader.getAnnotation( TableGenerator.class ).schema() );
+
+ reader = new EJB3OverridenAnnotationReader( Match.class, context );
+ assertNotNull( reader.getAnnotation( Table.class ) );
+ assertEquals(
+ "Java annotation not taken into account", "matchtable", reader.getAnnotation( Table.class ).name()
+ );
+ assertEquals(
+ "Java annotation not taken into account", "matchschema", reader.getAnnotation( Table.class ).schema()
+ );
+ assertEquals( "Overriding not taken into account", "mycatalog", reader.getAnnotation( Table.class ).catalog() );
+ assertNotNull( "SecondaryTable swallowed", reader.getAnnotation( SecondaryTables.class ) );
+ assertEquals(
+ "Default schema not taken into account", "myschema",
+ reader.getAnnotation( SecondaryTables.class ).value()[0].schema()
+ );
+ assertNotNull( reader.getAnnotation( Inheritance.class ) );
+ assertEquals(
+ "inheritance strategy not overriden", InheritanceType.JOINED,
+ reader.getAnnotation( Inheritance.class ).strategy()
+ );
+ assertNotNull( "NamedQuery not overriden", reader.getAnnotation( NamedQueries.class ) );
+ assertEquals( "No deduplication", 3, reader.getAnnotation( NamedQueries.class ).value().length );
+ assertEquals(
+ "deduplication kept the Java version", 1,
+ reader.getAnnotation( NamedQueries.class ).value()[1].hints().length
+ );
+ assertEquals(
+ "org.hibernate.timeout", reader.getAnnotation( NamedQueries.class ).value()[1].hints()[0].name()
+ );
+ assertNotNull( "NamedNativeQuery not overriden", reader.getAnnotation( NamedNativeQueries.class ) );
+ assertEquals( "No deduplication", 3, reader.getAnnotation( NamedNativeQueries.class ).value().length );
+ assertEquals(
+ "deduplication kept the Java version", 1,
+ reader.getAnnotation( NamedNativeQueries.class ).value()[1].hints().length
+ );
+ assertEquals(
+ "org.hibernate.timeout", reader.getAnnotation( NamedNativeQueries.class ).value()[1].hints()[0].name()
+ );
+ assertNotNull( reader.getAnnotation( SqlResultSetMappings.class ) );
+ assertEquals(
+ "competitor1Point", reader.getAnnotation( SqlResultSetMappings.class ).value()[0].columns()[0].name()
+ );
+ assertEquals(
+ "competitor1Point",
+ reader.getAnnotation( SqlResultSetMappings.class ).value()[0].entities()[0].fields()[0].column()
+ );
+ assertNotNull( reader.getAnnotation( ExcludeSuperclassListeners.class ) );
+ assertNotNull( reader.getAnnotation( ExcludeDefaultListeners.class ) );
+
+ reader = new EJB3OverridenAnnotationReader( Competition.class, context );
+ assertNotNull( reader.getAnnotation( MappedSuperclass.class ) );
+
+ reader = new EJB3OverridenAnnotationReader( TennisMatch.class, context );
+ assertNull( "Mutualize PKJC into PKJCs", reader.getAnnotation( PrimaryKeyJoinColumn.class ) );
+ assertNotNull( reader.getAnnotation( PrimaryKeyJoinColumns.class ) );
+ assertEquals(
+ "PrimaryKeyJoinColumn overrden", "id",
+ reader.getAnnotation( PrimaryKeyJoinColumns.class ).value()[0].name()
+ );
+ assertNotNull( reader.getAnnotation( AttributeOverrides.class ) );
+ assertEquals( "Wrong deduplication", 3, reader.getAnnotation( AttributeOverrides.class ).value().length );
+ assertEquals(
+ "Wrong priority (XML vs java annotations)", "fld_net",
+ reader.getAnnotation( AttributeOverrides.class ).value()[0].column().name()
+ );
+ assertEquals(
+ "Column mapping", 2, reader.getAnnotation( AttributeOverrides.class ).value()[1].column().scale()
+ );
+ assertEquals(
+ "Column mapping", true, reader.getAnnotation( AttributeOverrides.class ).value()[1].column().unique()
+ );
+ assertNotNull( reader.getAnnotation( AssociationOverrides.class ) );
+ assertEquals( "no XML processing", 1, reader.getAnnotation( AssociationOverrides.class ).value().length );
+ assertEquals(
+ "wrong xml processing", "id",
+ reader.getAnnotation( AssociationOverrides.class ).value()[0].joinColumns()[0].referencedColumnName()
+ );
+
+
+ reader = new EJB3OverridenAnnotationReader( SocialSecurityPhysicalAccount.class, context );
+ assertNotNull( reader.getAnnotation( IdClass.class ) );
+ assertEquals( "id-class not used", SocialSecurityNumber.class, reader.getAnnotation( IdClass.class ).value() );
+ assertEquals(
+ "discriminator-value not used", "Physical", reader.getAnnotation( DiscriminatorValue.class ).value()
+ );
+ assertNotNull( "discriminator-column not used", reader.getAnnotation( DiscriminatorColumn.class ) );
+ assertEquals(
+ "discriminator-column.name default value broken", "DTYPE",
+ reader.getAnnotation( DiscriminatorColumn.class ).name()
+ );
+ assertEquals(
+ "discriminator-column.length broken", 34, reader.getAnnotation( DiscriminatorColumn.class ).length()
+ );
+ }
+
+ public void testEntityRelatedAnnotationsMetadataComplete() throws Exception {
+ XMLContext context = buildContext(
+ "org/hibernate/test/annotations/reflection/metadata-complete.xml" );
+ EJB3OverridenAnnotationReader reader = new EJB3OverridenAnnotationReader( Administration.class, context );
+ assertNotNull( reader.getAnnotation( Entity.class ) );
+ assertEquals(
+ "Metadata complete should ignore java annotations", "", reader.getAnnotation( Entity.class ).name()
+ );
+ assertNotNull( reader.getAnnotation( Table.class ) );
+ assertEquals( "@Table should not be used", "", reader.getAnnotation( Table.class ).name() );
+ assertEquals( "Default schema not overriden", "myschema", reader.getAnnotation( Table.class ).schema() );
+
+ reader = new EJB3OverridenAnnotationReader( Match.class, context );
+ assertNotNull( reader.getAnnotation( Table.class ) );
+ assertEquals( "@Table should not be used", "", reader.getAnnotation( Table.class ).name() );
+ assertEquals( "Overriding not taken into account", "myschema", reader.getAnnotation( Table.class ).schema() );
+ assertEquals( "Overriding not taken into account", "mycatalog", reader.getAnnotation( Table.class ).catalog() );
+ assertNull( "Ignore Java annotation", reader.getAnnotation( SecondaryTable.class ) );
+ assertNull( "Ignore Java annotation", reader.getAnnotation( SecondaryTables.class ) );
+ assertNull( "Ignore Java annotation", reader.getAnnotation( Inheritance.class ) );
+ assertNull( reader.getAnnotation( NamedQueries.class ) );
+ assertNull( reader.getAnnotation( NamedNativeQueries.class ) );
+
+ reader = new EJB3OverridenAnnotationReader( TennisMatch.class, context );
+ assertNull( reader.getAnnotation( PrimaryKeyJoinColumn.class ) );
+ assertNull( reader.getAnnotation( PrimaryKeyJoinColumns.class ) );
+
+ reader = new EJB3OverridenAnnotationReader( Competition.class, context );
+ assertNull( reader.getAnnotation( MappedSuperclass.class ) );
+
+ reader = new EJB3OverridenAnnotationReader( SocialSecurityMoralAccount.class, context );
+ assertNull( reader.getAnnotation( IdClass.class ) );
+ assertNull( reader.getAnnotation( DiscriminatorValue.class ) );
+ assertNull( reader.getAnnotation( DiscriminatorColumn.class ) );
+ assertNull( reader.getAnnotation( SequenceGenerator.class ) );
+ assertNull( reader.getAnnotation( TableGenerator.class ) );
+ }
+
+ public void testIdRelatedAnnotations() throws Exception {
+ XMLContext context = buildContext( "org/hibernate/test/annotations/reflection/orm.xml" );
+ Method method = Administration.class.getDeclaredMethod( "getId" );
+ EJB3OverridenAnnotationReader reader = new EJB3OverridenAnnotationReader( method, context );
+ assertNull( reader.getAnnotation( Id.class ) );
+ assertNull( reader.getAnnotation( Column.class ) );
+ Field field = Administration.class.getDeclaredField( "id" );
+ reader = new EJB3OverridenAnnotationReader( field, context );
+ assertNotNull( reader.getAnnotation( Id.class ) );
+ assertNotNull( reader.getAnnotation( GeneratedValue.class ) );
+ assertEquals( GenerationType.SEQUENCE, reader.getAnnotation( GeneratedValue.class ).strategy() );
+ assertEquals( "generator", reader.getAnnotation( GeneratedValue.class ).generator() );
+ assertNotNull( reader.getAnnotation( SequenceGenerator.class ) );
+ assertEquals( "seq", reader.getAnnotation( SequenceGenerator.class ).sequenceName() );
+ assertNotNull( reader.getAnnotation( Columns.class ) );
+ assertEquals( 1, reader.getAnnotation( Columns.class ).columns().length );
+ assertEquals( "fld_id", reader.getAnnotation( Columns.class ).columns()[0].name() );
+ assertNotNull( reader.getAnnotation( Temporal.class ) );
+ assertEquals( TemporalType.DATE, reader.getAnnotation( Temporal.class ).value() );
+
+ context = buildContext(
+ "org/hibernate/test/annotations/reflection/metadata-complete.xml" );
+ method = Administration.class.getDeclaredMethod( "getId" );
+ reader = new EJB3OverridenAnnotationReader( method, context );
+ assertNotNull(
+ "Default access type when not defined in metadata complete should be property",
+ reader.getAnnotation( Id.class )
+ );
+ field = Administration.class.getDeclaredField( "id" );
+ reader = new EJB3OverridenAnnotationReader( field, context );
+ assertNull(
+ "Default access type when not defined in metadata complete should be property",
+ reader.getAnnotation( Id.class )
+ );
+
+ method = BusTrip.class.getDeclaredMethod( "getId" );
+ reader = new EJB3OverridenAnnotationReader( method, context );
+ assertNull( reader.getAnnotation( EmbeddedId.class ) );
+ field = BusTrip.class.getDeclaredField( "id" );
+ reader = new EJB3OverridenAnnotationReader( field, context );
+ assertNotNull( reader.getAnnotation( EmbeddedId.class ) );
+ assertNotNull( reader.getAnnotation( AttributeOverrides.class ) );
+ assertEquals( 1, reader.getAnnotation( AttributeOverrides.class ).value().length );
+ }
+
+ public void testBasicRelatedAnnotations() throws Exception {
+ XMLContext context = buildContext(
+ "org/hibernate/test/annotations/reflection/metadata-complete.xml" );
+ Field field = BusTrip.class.getDeclaredField( "status" );
+ EJB3OverridenAnnotationReader reader = new EJB3OverridenAnnotationReader( field, context );
+ assertNotNull( reader.getAnnotation( Enumerated.class ) );
+ assertEquals( EnumType.STRING, reader.getAnnotation( Enumerated.class ).value() );
+ assertEquals( false, reader.getAnnotation( Basic.class ).optional() );
+ field = BusTrip.class.getDeclaredField( "serial" );
+ reader = new EJB3OverridenAnnotationReader( field, context );
+ assertNotNull( reader.getAnnotation( Lob.class ) );
+ assertEquals( "serialbytes", reader.getAnnotation( Columns.class ).columns()[0].name() );
+ field = BusTrip.class.getDeclaredField( "terminusTime" );
+ reader = new EJB3OverridenAnnotationReader( field, context );
+ assertNotNull( reader.getAnnotation( Temporal.class ) );
+ assertEquals( TemporalType.TIMESTAMP, reader.getAnnotation( Temporal.class ).value() );
+ assertEquals( FetchType.LAZY, reader.getAnnotation( Basic.class ).fetch() );
+
+ field = BusTripPk.class.getDeclaredField( "busDriver" );
+ reader = new EJB3OverridenAnnotationReader( field, context );
+ assertNotNull( reader.isAnnotationPresent( Basic.class ) );
+ }
+
+ public void testVersionRelatedAnnotations() throws Exception {
+ XMLContext context = buildContext( "org/hibernate/test/annotations/reflection/orm.xml" );
+ Method method = Administration.class.getDeclaredMethod( "getVersion" );
+ EJB3OverridenAnnotationReader reader = new EJB3OverridenAnnotationReader( method, context );
+ assertNotNull( reader.getAnnotation( Version.class ) );
+
+ Field field = Match.class.getDeclaredField( "version" );
+ reader = new EJB3OverridenAnnotationReader( field, context );
+ assertNotNull( reader.getAnnotation( Version.class ) );
+ }
+
+ public void testTransientAndEmbeddedRelatedAnnotations() throws Exception {
+ XMLContext context = buildContext( "org/hibernate/test/annotations/reflection/orm.xml" );
+
+ Field field = Administration.class.getDeclaredField( "transientField" );
+ EJB3OverridenAnnotationReader reader = new EJB3OverridenAnnotationReader( field, context );
+ assertNotNull( reader.getAnnotation( Transient.class ) );
+ assertNull( reader.getAnnotation( Basic.class ) );
+
+ field = Match.class.getDeclaredField( "playerASSN" );
+ reader = new EJB3OverridenAnnotationReader( field, context );
+ assertNotNull( reader.getAnnotation( Embedded.class ) );
+ }
+
+ public void testAssociationRelatedAnnotations() throws Exception {
+ XMLContext context = buildContext( "org/hibernate/test/annotations/reflection/orm.xml" );
+
+ Field field = Administration.class.getDeclaredField( "defaultBusTrip" );
+ EJB3OverridenAnnotationReader reader = new EJB3OverridenAnnotationReader( field, context );
+ assertNotNull( reader.getAnnotation( OneToOne.class ) );
+ assertNull( reader.getAnnotation( JoinColumns.class ) );
+ assertNotNull( reader.getAnnotation( PrimaryKeyJoinColumns.class ) );
+ assertEquals( "pk", reader.getAnnotation( PrimaryKeyJoinColumns.class ).value()[0].name() );
+ assertEquals( 5, reader.getAnnotation( OneToOne.class ).cascade().length );
+ assertEquals( FetchType.LAZY, reader.getAnnotation( OneToOne.class ).fetch() );
+ assertEquals( "test", reader.getAnnotation( OneToOne.class ).mappedBy() );
+
+ context = buildContext(
+ "org/hibernate/test/annotations/reflection/metadata-complete.xml" );
+ field = BusTrip.class.getDeclaredField( "players" );
+ reader = new EJB3OverridenAnnotationReader( field, context );
+ assertNotNull( reader.getAnnotation( OneToMany.class ) );
+ assertNotNull( reader.getAnnotation( JoinColumns.class ) );
+ assertEquals( 2, reader.getAnnotation( JoinColumns.class ).value().length );
+ assertEquals( "driver", reader.getAnnotation( JoinColumns.class ).value()[0].name() );
+ assertNotNull( reader.getAnnotation( MapKey.class ) );
+ assertEquals( "name", reader.getAnnotation( MapKey.class ).name() );
+
+ field = BusTrip.class.getDeclaredField( "roads" );
+ reader = new EJB3OverridenAnnotationReader( field, context );
+ assertNotNull( reader.getAnnotation( ManyToMany.class ) );
+ assertNotNull( reader.getAnnotation( JoinTable.class ) );
+ assertEquals( "bus_road", reader.getAnnotation( JoinTable.class ).name() );
+ assertEquals( 2, reader.getAnnotation( JoinTable.class ).joinColumns().length );
+ assertEquals( 1, reader.getAnnotation( JoinTable.class ).inverseJoinColumns().length );
+ assertEquals( 2, reader.getAnnotation( JoinTable.class ).uniqueConstraints()[0].columnNames().length );
+ assertNotNull( reader.getAnnotation( OrderBy.class ) );
+ assertEquals( "maxSpeed", reader.getAnnotation( OrderBy.class ).value() );
+ }
+
+ public void testEntityListeners() throws Exception {
+ XMLContext context = buildContext( "org/hibernate/test/annotations/reflection/orm.xml" );
+
+ Method method = Administration.class.getDeclaredMethod( "calculate" );
+ EJB3OverridenAnnotationReader reader = new EJB3OverridenAnnotationReader( method, context );
+ assertTrue( reader.isAnnotationPresent( PrePersist.class ) );
+
+ reader = new EJB3OverridenAnnotationReader( Administration.class, context );
+ assertTrue( reader.isAnnotationPresent( EntityListeners.class ) );
+ assertEquals( 1, reader.getAnnotation( EntityListeners.class ).value().length );
+ assertEquals( LogListener.class, reader.getAnnotation( EntityListeners.class ).value()[0] );
+
+ method = LogListener.class.getDeclaredMethod( "noLog", Object.class );
+ reader = new EJB3OverridenAnnotationReader( method, context );
+ assertTrue( reader.isAnnotationPresent( PostLoad.class ) );
+
+ method = LogListener.class.getDeclaredMethod( "log", Object.class );
+ reader = new EJB3OverridenAnnotationReader( method, context );
+ assertTrue( reader.isAnnotationPresent( PrePersist.class ) );
+ assertFalse( reader.isAnnotationPresent( PostPersist.class ) );
+
+ assertEquals( 1, context.getDefaultEntityListeners().size() );
+ assertEquals( OtherLogListener.class.getName(), context.getDefaultEntityListeners().get(0) );
+ }
+
+ private XMLContext buildContext(String ormfile) throws SAXException, DocumentException, IOException {
+ XMLHelper xmlHelper = new XMLHelper();
+ ClassLoader cl = Thread.currentThread().getContextClassLoader();
+ InputStream is = cl.getResourceAsStream( ormfile );
+ assertNotNull( "ORM.xml not found: " + ormfile, is );
+ XMLContext context = new XMLContext();
+ List errors = new ArrayList();
+ SAXReader saxReader = xmlHelper.createSAXReader( "XML InputStream", errors, EJB3DTDEntityResolver.INSTANCE );
+ //saxReader.setValidation( false );
+ try {
+ saxReader.setFeature( "http://apache.org/xml/features/validation/schema", true );
+ }
+ catch (SAXNotSupportedException e) {
+ saxReader.setValidation( false );
+ }
+ org.dom4j.Document doc;
+ try {
+ doc = saxReader
+ .read( new InputSource( new BufferedInputStream( is ) ) );
+ }
+ finally {
+ is.close();
+ }
+ if (errors.size() > 0) {
+ System.out.println( errors.get( 0 ) );
+ }
+ assertEquals( 0, errors.size() );
+ context.addDocument( doc );
+ return context;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/LogListener.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/LogListener.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/LogListener.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,27 @@
+//$Id: LogListener.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.reflection;
+
+import javax.persistence.PrePersist;
+import javax.persistence.PostPersist;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class LogListener {
+ private final Logger log = LoggerFactory.getLogger( LogListener.class );
+
+ @PrePersist
+ @PostPersist
+ public void log(Object entity) {
+ log.debug( "Logging entity {} with hashCode: {}", entity.getClass().getName(), entity.hashCode() );
+ }
+
+
+ public void noLog(Object entity) {
+ log.debug( "NoLogging entity {} with hashCode: {}", entity.getClass().getName(), entity.hashCode() );
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/Match.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/Match.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/Match.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,35 @@
+//$Id: Match.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.reflection;
+
+import javax.persistence.Entity;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+import javax.persistence.NamedNativeQueries;
+import javax.persistence.NamedNativeQuery;
+import javax.persistence.NamedQueries;
+import javax.persistence.NamedQuery;
+import javax.persistence.SecondaryTable;
+import javax.persistence.Table;
+import javax.persistence.Version;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Table(name = "matchtable", schema = "matchschema")
+@SecondaryTable(name = "extendedMatch")
+@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
+@NamedQueries({
+@NamedQuery(name = "matchbyid", query = "select m from Match m where m.id = :id"),
+@NamedQuery(name = "getAllMatches2", query = "select m from Match m")
+ })
+@NamedNativeQueries({
+@NamedNativeQuery(name = "matchbyid", query = "select m from Match m where m.id = :id", resultSetMapping = "matchrs"),
+@NamedNativeQuery(name = "getAllMatches2", query = "select m from Match m", resultSetMapping = "matchrs")
+ })
+public class Match extends Competition {
+ public String competitor1Point;
+ @Version
+ public Integer version;
+ public SocialSecurityNumber playerASSN;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/Organization.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/Organization.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/Organization.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,17 @@
+//$Id: Organization.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.reflection;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class Organization {
+ private String organizationId;
+
+ public String getOrganizationId() {
+ return organizationId;
+ }
+
+ public void setOrganizationId(String organizationId) {
+ this.organizationId = organizationId;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/OtherLogListener.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/OtherLogListener.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/OtherLogListener.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,27 @@
+//$Id: OtherLogListener.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.reflection;
+
+import javax.persistence.PrePersist;
+import javax.persistence.PostPersist;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class OtherLogListener {
+ private final Logger log = LoggerFactory.getLogger( OtherLogListener.class );
+
+ @PrePersist
+ @PostPersist
+ public void log(Object entity) {
+ log.debug( "Logging entity {} with hashCode: {}", entity.getClass().getName(), entity.hashCode() );
+ }
+
+
+ public void noLog(Object entity) {
+ log.debug( "NoLogging entity {} with hashCode: {}", entity.getClass().getName(), entity.hashCode() );
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/SocialSecurityMoralAccount.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/SocialSecurityMoralAccount.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/SocialSecurityMoralAccount.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,21 @@
+//$Id: SocialSecurityMoralAccount.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.reflection;
+
+import javax.persistence.DiscriminatorValue;
+import javax.persistence.Entity;
+import javax.persistence.IdClass;
+import javax.persistence.SequenceGenerator;
+import javax.persistence.TableGenerator;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+(a)IdClass(SocialSecurityNumber.class)
+@DiscriminatorValue("Moral")
+@SequenceGenerator(name = "seq")
+@TableGenerator(name = "table")
+public class SocialSecurityMoralAccount {
+ public String number;
+ public String countryCode;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/SocialSecurityNumber.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/SocialSecurityNumber.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/SocialSecurityNumber.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,33 @@
+//$Id: SocialSecurityNumber.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.reflection;
+
+import java.io.Serializable;
+import javax.persistence.Embeddable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Embeddable
+public class SocialSecurityNumber implements Serializable {
+ public String number;
+ public String countryCode;
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( o == null || getClass() != o.getClass() ) return false;
+
+ final SocialSecurityNumber that = (SocialSecurityNumber) o;
+
+ if ( !countryCode.equals( that.countryCode ) ) return false;
+ if ( !number.equals( that.number ) ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ int result;
+ result = number.hashCode();
+ result = 29 * result + countryCode.hashCode();
+ return result;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/SocialSecurityPhysicalAccount.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/SocialSecurityPhysicalAccount.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/SocialSecurityPhysicalAccount.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,13 @@
+//$Id: SocialSecurityPhysicalAccount.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.reflection;
+
+import javax.persistence.Entity;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class SocialSecurityPhysicalAccount {
+ public String number;
+ public String countryCode;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/TennisMatch.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/TennisMatch.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/TennisMatch.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,21 @@
+//$Id: TennisMatch.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.reflection;
+
+import javax.persistence.AttributeOverride;
+import javax.persistence.AttributeOverrides;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.PrimaryKeyJoinColumn;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@PrimaryKeyJoinColumn(name = "match_id")
+@AttributeOverrides(
+ {@AttributeOverride(name = "net", column = @Column(name = "net")),
+ @AttributeOverride(name = "line", column = @Column(name = "line"))
+ })
+public class TennisMatch {
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/XMLContextTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/XMLContextTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/XMLContextTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,54 @@
+//$Id: XMLContextTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.reflection;
+
+import java.io.BufferedInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.List;
+
+import junit.framework.TestCase;
+import org.dom4j.io.SAXReader;
+import org.hibernate.cfg.EJB3DTDEntityResolver;
+import org.hibernate.cfg.annotations.reflection.XMLContext;
+import org.hibernate.util.XMLHelper;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXNotSupportedException;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class XMLContextTest extends TestCase {
+ public void testAll() throws Exception {
+ XMLHelper xmlHelper = new XMLHelper();
+ ClassLoader cl = Thread.currentThread().getContextClassLoader();
+ InputStream is = cl.getResourceAsStream(
+ "org/hibernate/test/annotations/reflection/orm.xml" );
+ assertNotNull( "ORM.xml not found", is );
+ XMLContext context = new XMLContext();
+ List errors = new ArrayList();
+ SAXReader saxReader = xmlHelper.createSAXReader( "XML InputStream", errors, EJB3DTDEntityResolver.INSTANCE );
+ //saxReader.setValidation( false );
+ try {
+ saxReader.setFeature( "http://apache.org/xml/features/validation/schema", true );
+ }
+ catch (SAXNotSupportedException e) {
+ saxReader.setValidation( false );
+ }
+ org.dom4j.Document doc;
+ try {
+ doc = saxReader
+ .read( new InputSource( new BufferedInputStream( is ) ) );
+ }
+ finally {
+ try {
+ is.close();
+ }
+ catch (IOException ioe) {
+ //log.warn( "Could not close input stream", ioe );
+ }
+ }
+ assertEquals( 0, errors.size() );
+ context.addDocument( doc );
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/metadata-complete.xml
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/metadata-complete.xml (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/metadata-complete.xml 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,76 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_1_0.xsd"
+ version="1.0"
+ >
+ <persistence-unit-metadata>
+ <xml-mapping-metadata-complete/>
+ <persistence-unit-defaults>
+ <schema>myschema</schema>
+ <catalog>mycatalog</catalog>
+ <cascade-persist/>
+ </persistence-unit-defaults>
+ </persistence-unit-metadata>
+ <package>org.hibernate.test.annotations.reflection</package>
+ <mapped-superclass class="Organization">
+ <attributes>
+ <basic name="organizationId"/>
+ </attributes>
+ </mapped-superclass>
+ <entity class="Administration">
+ <attributes>
+ <id name="id"/>
+ </attributes>
+ </entity>
+ <entity class="Match">
+ </entity>
+ <entity class="SocialSecurityMoralAccount"/>
+ <entity class="BusTrip" access="FIELD">
+ <attributes>
+ <embedded-id name="id">
+ <attribute-override name="busDriver">
+ <column name="fld_busdriver"/>
+ </attribute-override>
+ </embedded-id>
+ <basic name="status" optional="false">
+ <enumerated>STRING</enumerated>
+ </basic>
+ <basic name="serial" optional="true">
+ <column name="serialbytes"/>
+ <lob/>
+ </basic>
+ <basic name="terminusTime" fetch="LAZY">
+ <temporal>TIMESTAMP</temporal>
+ </basic>
+ <one-to-many name="players">
+ <map-key name="name"/>
+ <join-column name="driver"/>
+ <join-column name="number"/>
+ </one-to-many>
+ <many-to-many name="roads" target-entity="Administration">
+ <order-by>maxSpeed</order-by>
+ <join-table name="bus_road">
+ <join-column name="driver"/>
+ <join-column name="number"/>
+ <inverse-join-column name="road_id"/>
+ <unique-constraint>
+ <column-name>driver</column-name>
+ <column-name>number</column-name>
+ </unique-constraint>
+ </join-table>
+ </many-to-many>
+ </attributes>
+ </entity>
+ <embeddable class="BusTripPk" access="FIELD">
+ <attributes>
+ <basic name="busDriver">
+ <column name="busdriver"/>
+ </basic>
+ <basic name="busNumber">
+ <column name="busnumber"/>
+ </basic>
+ </attributes>
+ </embeddable>
+</entity-mappings>
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/orm.xml
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/orm.xml (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/reflection/orm.xml 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,117 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_1_0.xsd"
+ version="1.0"
+ >
+ <persistence-unit-metadata>
+ <persistence-unit-defaults>
+ <schema>myschema</schema>
+ <catalog>mycatalog</catalog>
+ <cascade-persist/>
+ <entity-listeners>
+ <entity-listener class="org.hibernate.test.annotations.reflection.OtherLogListener">
+ <post-update method-name="log"/>
+ </entity-listener>
+ </entity-listeners>
+ </persistence-unit-defaults>
+ </persistence-unit-metadata>
+ <package>org.hibernate.test.annotations.reflection</package>
+ <entity class="Administration">
+ <table name="tbl_admin">
+ <unique-constraint>
+ <column-name>firstname</column-name>
+ <column-name>lastname</column-name>
+ </unique-constraint>
+ </table>
+ <secondary-table name="admin2">
+ <primary-key-join-column name="admin_id" referenced-column-name="id"/>
+ <unique-constraint>
+ <column-name>address</column-name>
+ </unique-constraint>
+ </secondary-table>
+ <sequence-generator name="seqhilo" sequence-name="seqhilo"/>
+ <table-generator name="table" table="tablehilo"/>
+ <entity-listeners>
+ <entity-listener class="LogListener">
+ <pre-persist method-name="log"/>
+ <post-load method-name="noLog"/>
+ </entity-listener>
+ </entity-listeners>
+ <pre-persist method-name="calculate"/>
+ <attributes>
+ <id name="id">
+ <column name="fld_id"/>
+ <generated-value generator="generator" strategy="SEQUENCE"/>
+ <temporal>DATE</temporal>
+ <sequence-generator name="generator" sequence-name="seq"/>
+ </id>
+ <version name="version"/>
+ <one-to-one name="defaultBusTrip" fetch="LAZY" mapped-by="test">
+ <primary-key-join-column name="pk"/>
+ <cascade>
+ <cascade-all/>
+ <cascade-persist/>
+ <cascade-merge/>
+ <cascade-remove/>
+ <cascade-refresh/>
+ </cascade>
+ </one-to-one>
+ <transient name="transientField"/>
+ </attributes>
+ </entity>
+ <entity class="Match">
+ <inheritance strategy="JOINED"/>
+ <named-query name="allmatches">
+ <query>select m from Match m</query>
+ <hint name="org.hibernate.timeout" value="200"/>
+ </named-query>
+ <named-query name="matchbyid">
+ <query>select m from Match m where m.id = :id</query>
+ <hint name="org.hibernate.timeout" value="200"/>
+ </named-query>
+ <named-native-query name="allmatches" result-set-mapping="matchrs">
+ <query>select m from Match m</query>
+ <hint name="org.hibernate.timeout" value="200"/>
+ </named-native-query>
+ <named-native-query name="matchbyid" result-set-mapping="matchrs">
+ <query>select m from Match m where m.id = :id</query>
+ <hint name="org.hibernate.timeout" value="200"/>
+ </named-native-query>
+ <sql-result-set-mapping name="matchrs">
+ <entity-result entity-class="org.hibernate.test.annotations.reflection.Match">
+ <field-result name="competitor1Point" column="competitor1Point"/>
+ </entity-result>
+ <column-result name="competitor1Point"/>
+ </sql-result-set-mapping>
+ <exclude-default-listeners/>
+ <exclude-superclass-listeners/>
+ <entity-listeners>
+ <entity-listener class="LogListener">
+ <pre-persist method-name="log"/>
+ <post-load method-name="noLog"/>
+ </entity-listener>
+ </entity-listeners>
+ <attributes>
+ <embedded name="playerASSN"/>
+ </attributes>
+ </entity>
+ <entity class="TennisMatch">
+ <primary-key-join-column name="id"/>
+ <attribute-override name="net">
+ <column name="fld_net"/>
+ </attribute-override>
+ <attribute-override name="ground">
+ <column name="fld_ground" unique="true" scale="2"/>
+ </attribute-override>
+ <association-override name="referer">
+ <join-column name="referer_id" referenced-column-name="id"/>
+ </association-override>
+ </entity>
+ <entity class="SocialSecurityPhysicalAccount">
+ <id-class class="org.hibernate.test.annotations.reflection.SocialSecurityNumber"/>
+ <discriminator-value>Physical</discriminator-value>
+ <discriminator-column length="34"/>
+ </entity>
+</entity-mappings>
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/strategy/Location.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/strategy/Location.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/strategy/Location.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,26 @@
+//$Id: Location.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.strategy;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class Location {
+ private String city;
+ private String country;
+
+ public String getCity() {
+ return city;
+ }
+
+ public void setCity(String city) {
+ this.city = city;
+ }
+
+ public String getCountry() {
+ return country;
+ }
+
+ public void setCountry(String country) {
+ this.country = country;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/strategy/Storm.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/strategy/Storm.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/strategy/Storm.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,62 @@
+//$Id: Storm.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.strategy;
+
+import javax.persistence.Column;
+import javax.persistence.Embedded;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.UniqueConstraint;
+import javax.persistence.Table;
+
+import org.hibernate.annotations.Index;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Table(uniqueConstraints = {@UniqueConstraint(columnNames = {"start.country", "start.city"})})
+public class Storm {
+ private Integer id;
+ private Location start;
+ private Location end;
+ private String stormName;
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ @Embedded
+ public Location getStart() {
+ return start;
+ }
+
+ public void setStart(Location start) {
+ this.start = start;
+ }
+
+ @Embedded
+ public Location getEnd() {
+ return end;
+ }
+
+ public void setEnd(Location end) {
+ this.end = end;
+ }
+
+ @Index(name="storm_name_idx")
+ @Column(unique = true)
+ public String getStormName() {
+ return stormName;
+ }
+
+ public void setStormName(String name) {
+ this.stormName = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/strategy/StrategyTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/strategy/StrategyTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/strategy/StrategyTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,44 @@
+//$Id: StrategyTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.strategy;
+
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.cfg.DefaultComponentSafeNamingStrategy;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class StrategyTest extends TestCase {
+
+ public void testComponentSafeStrategy() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Location start = new Location();
+ start.setCity( "Paris" );
+ start.setCountry( "France" );
+ Location end = new Location();
+ end.setCity( "London" );
+ end.setCountry( "UK" );
+ Storm storm = new Storm();
+ storm.setEnd( end );
+ storm.setStart( start );
+ s.persist( storm );
+ s.flush();
+ tx.rollback();
+ s.close();
+ }
+
+ protected void configure(Configuration cfg) {
+ cfg.setNamingStrategy( DefaultComponentSafeNamingStrategy.INSTANCE );
+ //cfg.getSessionEventListenerConfig().setFlushEventListener( new EJB3FlushEventListener() );
+ //cfg.getSessionEventListenerConfig().setAutoFlushEventListener( new EJB3AutoFlushEventListener() );
+ }
+
+ protected Class[] getMappings() {
+ return new Class[]{
+ Storm.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tableperclass/Component.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tableperclass/Component.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tableperclass/Component.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,53 @@
+//$Id: Component.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.tableperclass;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+
+import org.hibernate.annotations.Index;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity(name = "xpmComponent")
+@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
+public abstract class Component {
+ private String manufacturerPartNumber;
+ private Long manufacturerId;
+ private Long id;
+
+
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+
+ @Id
+ public Long getId() {
+ return id;
+ }
+
+ @Column(nullable = false)
+ @Index(name = "manufacturerPartNumber")
+ public String getManufacturerPartNumber() {
+ return manufacturerPartNumber;
+ }
+
+ @Column(nullable = false)
+ public Long getManufacturerId() {
+ return manufacturerId;
+ }
+
+ public void setManufacturerId(Long manufacturerId) {
+ this.manufacturerId = manufacturerId;
+ }
+
+
+ public void setManufacturerPartNumber(String manufacturerPartNumber) {
+ this.manufacturerPartNumber = manufacturerPartNumber;
+ }
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tableperclass/Machine.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tableperclass/Machine.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tableperclass/Machine.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,37 @@
+//$Id: Machine.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.tableperclass;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
+public class Machine {
+ private Integer id;
+ private Double weight;
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.TABLE)
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public Double getWeight() {
+ return weight;
+ }
+
+ public void setWeight(Double weight) {
+ this.weight = weight;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tableperclass/Product.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tableperclass/Product.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tableperclass/Product.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,15 @@
+//$Id: Product.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.tableperclass;
+
+import javax.persistence.Entity;
+import javax.persistence.Table;
+import javax.persistence.UniqueConstraint;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Table( name = "xPM_Product", uniqueConstraints = {@UniqueConstraint( columnNames = {
+ "manufacturerPartNumber", "manufacturerId"} )} )
+public class Product extends Component {
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tableperclass/Robot.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tableperclass/Robot.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tableperclass/Robot.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,20 @@
+//$Id: Robot.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.tableperclass;
+
+import javax.persistence.Entity;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Robot extends Machine {
+ private String name;
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tableperclass/T800.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tableperclass/T800.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tableperclass/T800.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,20 @@
+//$Id: T800.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.tableperclass;
+
+import javax.persistence.Entity;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class T800 extends Robot {
+ public String getTargetName() {
+ return targetName;
+ }
+
+ public void setTargetName(String targetName) {
+ this.targetName = targetName;
+ }
+
+ private String targetName;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tableperclass/TablePerClassTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tableperclass/TablePerClassTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tableperclass/TablePerClassTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,90 @@
+//$Id: TablePerClassTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.tableperclass;
+
+import java.util.List;
+import java.sql.SQLException;
+
+import org.hibernate.Query;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.JDBCException;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class TablePerClassTest extends TestCase {
+ public void testUnionSubClass() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Machine computer = new Machine();
+ computer.setWeight( new Double( 4 ) );
+ Robot asimov = new Robot();
+ asimov.setWeight( new Double( 120 ) );
+ asimov.setName( "Asimov" );
+ T800 terminator = new T800();
+ terminator.setName( "Terminator" );
+ terminator.setWeight( new Double( 300 ) );
+ terminator.setTargetName( "Sarah Connor" );
+ s.persist( computer );
+ s.persist( asimov );
+ s.persist( terminator );
+ tx.commit();
+ s.close();
+ s = openSession();
+ tx = s.beginTransaction();
+ Query q = s.createQuery( "from Machine m where m.weight >= :weight" );
+ q.setDouble( "weight", new Double( 10 ) );
+ List result = q.list();
+ assertEquals( 2, result.size() );
+ tx.commit();
+ s.close();
+ s = openSession();
+ tx = s.beginTransaction();
+ tx.commit();
+ s.close();
+ }
+
+ public void testConstraintsOnSuperclassProperties() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Product product1 = new Product();
+ product1.setId( 1l );
+ product1.setManufacturerId( 1l );
+ product1.setManufacturerPartNumber( "AAFR");
+ s.persist( product1 );
+ s.flush();
+ Product product2 = new Product();
+ product2.setId( 2l );
+ product2.setManufacturerId( 1l );
+ product2.setManufacturerPartNumber( "AAFR");
+ s.persist( product2 );
+ try {
+ s.flush();
+ fail("Database Exception not handled");
+ }
+ catch( JDBCException e ) {
+ //success
+ }
+ tx.rollback();
+ s.close();
+ }
+
+
+
+ public TablePerClassTest(String x) {
+ super( x ); //To change body of overridden methods use File | Settings | File Templates.
+ }
+
+ protected Class[] getMappings() {
+ return new Class[]{
+ Robot.class,
+ T800.class,
+ Machine.class,
+ Component.class,
+ Product.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/target/Brand.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/target/Brand.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/target/Brand.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,56 @@
+//$Id: Brand.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.target;
+
+import java.util.Map;
+import java.util.HashMap;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.GeneratedValue;
+import javax.persistence.ManyToMany;
+
+import org.hibernate.annotations.MapKey;
+import org.hibernate.annotations.CollectionOfElements;
+import org.hibernate.annotations.MapKeyManyToMany;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Brand {
+ @Id
+ @GeneratedValue
+ private Long id;
+
+ @ManyToMany(targetEntity = LuggageImpl.class)
+ @MapKey(targetElement = SizeImpl.class)
+ private Map<Size, Luggage> luggagesBySize = new HashMap<Size, Luggage>();
+
+ @CollectionOfElements(targetElement = SizeImpl.class)
+ @MapKeyManyToMany(targetEntity = LuggageImpl.class)
+ private Map<Luggage, Size> sizePerLuggage = new HashMap<Luggage, Size>();
+
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public Map<Size, Luggage> getLuggagesBySize() {
+ return luggagesBySize;
+ }
+
+ public void setLuggagesBySize(Map<Size, Luggage> luggagesBySize) {
+ this.luggagesBySize = luggagesBySize;
+ }
+
+ public Map<Luggage, Size> getSizePerLuggage() {
+ return sizePerLuggage;
+ }
+
+ public void setSizePerLuggage(Map<Luggage, Size> sizePerLuggage) {
+ this.sizePerLuggage = sizePerLuggage;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/target/Luggage.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/target/Luggage.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/target/Luggage.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,17 @@
+//$Id: Luggage.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.target;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public interface Luggage {
+ double getHeight();
+ double getWidth();
+
+ void setHeight(double height);
+ void setWidth(double width);
+
+ Owner getOwner();
+
+ void setOwner(Owner owner);
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/target/LuggageImpl.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/target/LuggageImpl.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/target/LuggageImpl.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,57 @@
+//$Id: LuggageImpl.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.target;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.GeneratedValue;
+import javax.persistence.ManyToOne;
+import javax.persistence.Embedded;
+
+import org.hibernate.annotations.Target;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class LuggageImpl implements Luggage {
+ private Long id;
+ private double height;
+ private double width;
+ private Owner owner;
+
+ @Embedded
+ @Target(OwnerImpl.class)
+ public Owner getOwner() {
+ return owner;
+ }
+
+ public void setOwner(Owner owner) {
+ this.owner = owner;
+ }
+
+ @Id
+ @GeneratedValue
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public double getHeight() {
+ return height;
+ }
+
+ public void setHeight(double height) {
+ this.height = height;
+ }
+
+ public double getWidth() {
+ return width;
+ }
+
+ public void setWidth(double width) {
+ this.width = width;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/target/Owner.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/target/Owner.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/target/Owner.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,12 @@
+//$Id: Owner.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.target;
+
+import java.util.Map;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public interface Owner {
+ String getName();
+ void setName(String name);
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/target/OwnerImpl.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/target/OwnerImpl.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/target/OwnerImpl.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,24 @@
+//$Id: OwnerImpl.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.target;
+
+import java.util.Map;
+import java.util.HashMap;
+import javax.persistence.Embeddable;
+import org.hibernate.annotations.MapKey;
+import javax.persistence.ManyToMany;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Embeddable
+public class OwnerImpl implements Owner {
+ private String name;
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/target/Size.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/target/Size.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/target/Size.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,10 @@
+//$Id: Size.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.target;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public interface Size {
+ String getName();
+ void setName(String name);
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/target/SizeImpl.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/target/SizeImpl.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/target/SizeImpl.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,20 @@
+//$Id: SizeImpl.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.target;
+
+import javax.persistence.Embeddable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Embeddable
+public class SizeImpl implements Size {
+ private String name;
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/target/TargetTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/target/TargetTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/target/TargetTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,82 @@
+//$Id: TargetTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.target;
+
+import org.hibernate.test.annotations.TestCase;
+import org.hibernate.Session;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class TargetTest extends TestCase {
+
+ public void testTargetOnEmbedded() throws Exception {
+ Session s = openSession();
+ s.getTransaction().begin();
+ Luggage l = new LuggageImpl();
+ l.setHeight( 12 );
+ l.setWidth( 12 );
+ Owner o = new OwnerImpl();
+ o.setName( "Emmanuel" );
+ l.setOwner( o );
+ s.persist( l );
+ s.flush();
+ s.clear();
+ l = (Luggage) s.get(LuggageImpl.class, ( (LuggageImpl) l).getId() );
+ assertEquals( "Emmanuel", l.getOwner().getName() );
+ s.getTransaction().rollback();
+ s.close();
+ }
+
+ public void testTargetOnMapKey() throws Exception {
+ Session s = openSession();
+ s.getTransaction().begin();
+ Luggage l = new LuggageImpl();
+ l.setHeight( 12 );
+ l.setWidth( 12 );
+ Size size = new SizeImpl();
+ size.setName( "S" );
+ Owner o = new OwnerImpl();
+ o.setName( "Emmanuel" );
+ l.setOwner( o );
+ s.persist( l );
+ Brand b = new Brand();
+ s.persist( b );
+ b.getLuggagesBySize().put( size, l );
+ s.flush();
+ s.clear();
+ b = (Brand) s.get(Brand.class, b.getId() );
+ assertEquals( "S", b.getLuggagesBySize().keySet().iterator().next().getName() );
+ s.getTransaction().rollback();
+ s.close();
+ }
+
+ public void testTargetOnMapKeyManyToMany() throws Exception {
+ Session s = openSession();
+ s.getTransaction().begin();
+ Luggage l = new LuggageImpl();
+ l.setHeight( 12 );
+ l.setWidth( 12 );
+ Size size = new SizeImpl();
+ size.setName( "S" );
+ Owner o = new OwnerImpl();
+ o.setName( "Emmanuel" );
+ l.setOwner( o );
+ s.persist( l );
+ Brand b = new Brand();
+ s.persist( b );
+ b.getSizePerLuggage().put( l, size );
+ s.flush();
+ s.clear();
+ b = (Brand) s.get(Brand.class, b.getId() );
+ assertEquals( 12d, b.getSizePerLuggage().keySet().iterator().next().getWidth() );
+ s.getTransaction().rollback();
+ s.close();
+ }
+
+ protected Class[] getMappings() {
+ return new Class[] {
+ LuggageImpl.class,
+ Brand.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/Country.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/Country.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/Country.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,15 @@
+//$Id: Country.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.tuplizer;
+
+import javax.persistence.Embeddable;
+import javax.persistence.Column;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Embeddable
+public interface Country {
+ @Column(name = "CountryName")
+ public String getName();
+ public void setName(String name);
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/Cuisine.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/Cuisine.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/Cuisine.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,29 @@
+//$Id: Cuisine.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.tuplizer;
+
+import javax.persistence.Id;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Entity;
+
+import org.hibernate.annotations.Tuplizer;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Tuplizer(impl = DynamicEntityTuplizer.class)
+public interface Cuisine {
+ @Id
+ @GeneratedValue
+ public Long getId();
+ public void setId(Long id);
+
+ public String getName();
+ public void setName(String name);
+
+ @Tuplizer(impl = DynamicComponentTuplizer.class)
+ public Country getCountry();
+ public void setCountry(Country country);
+
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/DataProxyHandler.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/DataProxyHandler.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/DataProxyHandler.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,53 @@
+//$Id: DataProxyHandler.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.tuplizer;
+
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.util.HashMap;
+import java.io.Serializable;
+
+/**
+ * A simple {@link java.lang.reflect.InvocationHandler} to act as the handler for our generated
+ * {@link java.lang.reflect.Proxy}-based entity instances.
+ * <p/>
+ * This is a trivial impl which simply keeps the property values into
+ * a Map.
+ *
+ * @author <a href="mailto:steve@hibernate.org">Steve Ebersole </a>
+ */
+public final class DataProxyHandler implements InvocationHandler {
+ private String entityName;
+ private HashMap data = new HashMap();
+
+ public DataProxyHandler(String entityName, Serializable id) {
+ this.entityName = entityName;
+ data.put( "Id", id );
+ }
+
+ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
+ String methodName = method.getName();
+ if ( methodName.startsWith( "set" ) ) {
+ String propertyName = methodName.substring( 3 );
+ data.put( propertyName, args[0] );
+ }
+ else if ( methodName.startsWith( "get" ) ) {
+ String propertyName = methodName.substring( 3 );
+ return data.get( propertyName );
+ }
+ else if ( "toString".equals( methodName ) ) {
+ return entityName + "#" + data.get( "Id" );
+ }
+ else if ( "hashCode".equals( methodName ) ) {
+ return new Integer( this.hashCode() );
+ }
+ return null;
+ }
+
+ public String getEntityName() {
+ return entityName;
+ }
+
+ public HashMap getData() {
+ return data;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/DynamicComponentTuplizer.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/DynamicComponentTuplizer.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/DynamicComponentTuplizer.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,29 @@
+//$Id: DynamicComponentTuplizer.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.tuplizer;
+
+import org.hibernate.tuple.entity.PojoEntityTuplizer;
+import org.hibernate.tuple.entity.EntityMetamodel;
+import org.hibernate.tuple.Instantiator;
+import org.hibernate.tuple.component.PojoComponentTuplizer;
+import org.hibernate.mapping.PersistentClass;
+import org.hibernate.mapping.Component;
+import org.hibernate.proxy.ProxyFactory;
+import org.hibernate.property.Getter;
+import org.hibernate.property.Setter;
+import org.hibernate.HibernateException;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class DynamicComponentTuplizer extends PojoComponentTuplizer {
+
+ public DynamicComponentTuplizer(Component component) {
+ super( component );
+ }
+
+
+ protected Instantiator buildInstantiator(Component component) {
+ return new DynamicInstantiator( component.getComponentClassName() ); //To change body of overridden methods use File | Settings | File Templates.
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/DynamicEntityTuplizer.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/DynamicEntityTuplizer.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/DynamicEntityTuplizer.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,32 @@
+//$Id: DynamicEntityTuplizer.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.tuplizer;
+
+import org.hibernate.tuple.entity.PojoEntityTuplizer;
+import org.hibernate.tuple.entity.EntityMetamodel;
+import org.hibernate.tuple.Instantiator;
+import org.hibernate.mapping.PersistentClass;
+import org.hibernate.proxy.ProxyFactory;
+import org.hibernate.property.Getter;
+import org.hibernate.property.Setter;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class DynamicEntityTuplizer extends PojoEntityTuplizer {
+
+ public DynamicEntityTuplizer(EntityMetamodel entityMetamodel, PersistentClass mappedEntity) {
+ super( entityMetamodel, mappedEntity );
+ }
+
+ protected Instantiator buildInstantiator(PersistentClass persistentClass) {
+ return new DynamicInstantiator( persistentClass.getEntityName() );
+ }
+
+ protected ProxyFactory buildProxyFactory(PersistentClass persistentClass, Getter idGetter, Setter idSetter) {
+ // allows defining a custom proxy factory, which is responsible for
+ // generating lazy proxies for a given entity.
+ //
+ // Here we simply use the default...
+ return super.buildProxyFactory( persistentClass, idGetter, idSetter );
+ }
+ }
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/DynamicInstantiator.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/DynamicInstantiator.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/DynamicInstantiator.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,56 @@
+//$Id: DynamicInstantiator.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.tuplizer;
+
+import java.io.Serializable;
+import java.lang.reflect.Proxy;
+import java.lang.reflect.InvocationHandler;
+
+import org.hibernate.tuple.Instantiator;
+import org.hibernate.util.ReflectHelper;
+import org.hibernate.HibernateException;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class DynamicInstantiator implements Instantiator {
+ private final String entityName;
+
+ public DynamicInstantiator(String entityName) {
+ this.entityName = entityName;
+ }
+
+ public Object instantiate(Serializable id) {
+ if ( Cuisine.class.getName().equals( entityName ) ) {
+ return ProxyHelper.newCuisineProxy( id );
+ }
+ if ( Country.class.getName().equals( entityName ) ) {
+ return ProxyHelper.newCountryProxy( id );
+ }
+ else {
+ throw new IllegalArgumentException( "unknown entity for instantiation [" + entityName + "]" );
+ }
+ }
+
+ public Object instantiate() {
+ return instantiate( null );
+ }
+
+ public boolean isInstance(Object object) {
+ String resolvedEntityName = null;
+ if ( Proxy.isProxyClass( object.getClass() ) ) {
+ InvocationHandler handler = Proxy.getInvocationHandler( object );
+ if ( DataProxyHandler.class.isAssignableFrom( handler.getClass() ) ) {
+ DataProxyHandler myHandler = ( DataProxyHandler ) handler;
+ resolvedEntityName = myHandler.getEntityName();
+ }
+ }
+ try {
+ return ReflectHelper.classForName( entityName ).isInstance( object );
+ }
+ catch( Throwable t ) {
+ throw new HibernateException( "could not get handle to entity-name as interface : " + t );
+ }
+
+// return entityName.equals( resolvedEntityName );
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/EntityNameInterceptor.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/EntityNameInterceptor.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/EntityNameInterceptor.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,25 @@
+//$Id: EntityNameInterceptor.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.tuplizer;
+
+import org.hibernate.EmptyInterceptor;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class EntityNameInterceptor extends EmptyInterceptor {
+ /**
+ * The callback from Hibernate to determine the entity name given
+ * a presumed entity instance.
+ *
+ * @param object The presumed entity instance.
+ * @return The entity name (pointing to the proper entity mapping).
+ */
+ public String getEntityName(Object object) {
+ String entityName = ProxyHelper.extractEntityName( object );
+ if ( entityName == null ) {
+ entityName = super.getEntityName( object );
+ }
+ return entityName;
+ }
+}
+
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/ProxyHelper.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/ProxyHelper.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/ProxyHelper.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,50 @@
+//$Id: ProxyHelper.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.tuplizer;
+
+import java.io.Serializable;
+import java.lang.reflect.Proxy;
+import java.lang.reflect.InvocationHandler;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class ProxyHelper {
+
+ public static Country newPersonProxy() {
+ return newCountryProxy( null );
+ }
+
+ public static Country newCountryProxy(Serializable id) {
+ return ( Country ) Proxy.newProxyInstance(
+ Country.class.getClassLoader(),
+ new Class[] {Country.class},
+ new DataProxyHandler( Country.class.getName(), id )
+ );
+ }
+
+ public static Cuisine newCustomerProxy() {
+ return newCuisineProxy( null );
+ }
+
+ public static Cuisine newCuisineProxy(Serializable id) {
+ return ( Cuisine ) Proxy.newProxyInstance(
+ Cuisine.class.getClassLoader(),
+ new Class[] {Cuisine.class},
+ new DataProxyHandler( Cuisine.class.getName(), id )
+ );
+ }
+
+ public static String extractEntityName(Object object) {
+ // Our custom java.lang.reflect.Proxy instances actually bundle
+ // their appropriate entity name, so we simply extract it from there
+ // if this represents one of our proxies; otherwise, we return null
+ if ( Proxy.isProxyClass( object.getClass() ) ) {
+ InvocationHandler handler = Proxy.getInvocationHandler( object );
+ if ( DataProxyHandler.class.isAssignableFrom( handler.getClass() ) ) {
+ DataProxyHandler myHandler = ( DataProxyHandler ) handler;
+ return myHandler.getEntityName();
+ }
+ }
+ return null;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/TuplizerTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/TuplizerTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/tuplizer/TuplizerTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,34 @@
+//$Id: TuplizerTest.java 16289 2009-04-09 22:09:50Z gbadner $
+package org.hibernate.test.annotations.tuplizer;
+
+import org.hibernate.test.annotations.TestCase;
+import org.hibernate.Session;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class TuplizerTest extends TestCase {
+ public void testEntityTuplizer() throws Exception {
+ Cuisine cuisine = ProxyHelper.newCuisineProxy( null );
+ cuisine.setName( "Francaise" );
+ Country country = ProxyHelper.newCountryProxy( null );
+ country.setName( "France" );
+ cuisine.setCountry( country );
+ Session s = openSession( new EntityNameInterceptor() );
+ s.getTransaction().begin();
+ s.persist( cuisine );
+ s.flush();
+ s.clear();
+ cuisine = (Cuisine) s.get(Cuisine.class, cuisine.getId() );
+ assertNotNull( cuisine );
+ assertEquals( "Francaise", cuisine.getName() );
+ assertEquals( "France", country.getName() );
+ s.getTransaction().rollback();
+ s.close();
+ }
+ protected Class[] getMappings() {
+ return new Class[] {
+ Cuisine.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/type/Dvd.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/type/Dvd.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/type/Dvd.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,48 @@
+//$Id: Dvd.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.type;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+import org.hibernate.annotations.Columns;
+import org.hibernate.annotations.GenericGenerator;
+import org.hibernate.annotations.Type;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Dvd {
+ private MyOid id;
+ private String title;
+
+ @Id
+ @GeneratedValue(generator = "custom-id")
+ @GenericGenerator(name = "custom-id", strategy = "org.hibernate.test.annotations.type.MyOidGenerator")
+ @Type(type = "org.hibernate.test.annotations.type.MyOidType")
+ @Columns(
+ columns = {
+ @Column(name = "high"),
+ @Column(name = "middle"),
+ @Column(name = "low"),
+ @Column(name = "other")
+ }
+ )
+ public MyOid getId() {
+ return id;
+ }
+
+ public void setId(MyOid id) {
+ this.id = id;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/type/MyOid.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/type/MyOid.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/type/MyOid.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,79 @@
+//$Id: MyOid.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.type;
+
+import java.io.Serializable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class MyOid implements Serializable {
+ private int high;
+ private int middle;
+ private int low;
+ private int other;
+
+ protected MyOid() {
+ }
+
+ public MyOid(int aHigh, int aMiddle, int aLow, int aOther) {
+ high = aHigh;
+ middle = aMiddle;
+ low = aLow;
+ other = aOther;
+ }
+
+ public int getHigh() {
+ return high;
+ }
+
+ public void setHigh(int aHigh) {
+ high = aHigh;
+ }
+
+ public int getMiddle() {
+ return middle;
+ }
+
+ public void setMiddle(int aMiddle) {
+ middle = aMiddle;
+ }
+
+ public int getLow() {
+ return low;
+ }
+
+ public void setLow(int aLow) {
+ low = aLow;
+ }
+
+ public int getOther() {
+ return other;
+ }
+
+ public void setOther(int aOther) {
+ other = aOther;
+ }
+
+ public boolean equals(Object o) {
+ if ( this == o ) return true;
+ if ( o == null || getClass() != o.getClass() ) return false;
+
+ final MyOid myOid = (MyOid) o;
+
+ if ( high != myOid.high ) return false;
+ if ( low != myOid.low ) return false;
+ if ( middle != myOid.middle ) return false;
+ if ( other != myOid.other ) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ int result;
+ result = low;
+ result = 29 * result + middle;
+ result = 29 * result + high;
+ result = 29 * result + other;
+ return result;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/type/MyOidGenerator.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/type/MyOidGenerator.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/type/MyOidGenerator.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,22 @@
+//$Id: MyOidGenerator.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.type;
+
+import java.io.Serializable;
+
+import org.hibernate.HibernateException;
+import org.hibernate.engine.SessionImplementor;
+import org.hibernate.id.IdentifierGenerator;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class MyOidGenerator implements IdentifierGenerator {
+
+ private int counter;
+
+ public Serializable generate(SessionImplementor aSessionImplementor, Object aObject) throws HibernateException {
+ counter++;
+ return new MyOid( 0, 0, 0, counter );
+ }
+}
+
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/type/MyOidType.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/type/MyOidType.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/type/MyOidType.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,147 @@
+//$Id: MyOidType.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.type;
+
+import java.io.Serializable;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+
+import org.hibernate.Hibernate;
+import org.hibernate.HibernateException;
+import org.hibernate.engine.SessionImplementor;
+import org.hibernate.type.Type;
+import org.hibernate.usertype.CompositeUserType;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class MyOidType implements CompositeUserType {
+
+ public static final String[] PROPERTY_NAMES = new String[]{"high", "middle", "low", "other"};
+ public static final Type[] TYPES = new Type[]{Hibernate.INTEGER, Hibernate.INTEGER, Hibernate.INTEGER, Hibernate.INTEGER};
+
+
+ public String[] getPropertyNames() {
+ return PROPERTY_NAMES;
+ }
+
+ public Type[] getPropertyTypes() {
+ return TYPES;
+ }
+
+ public Object getPropertyValue(Object aObject, int i) throws HibernateException {
+ MyOid dbOid = (MyOid) aObject;
+ switch ( i ) {
+ case 0:
+ return dbOid.getHigh();
+ case 1:
+ return dbOid.getMiddle();
+ case 2:
+ return dbOid.getLow();
+ case 3:
+ return dbOid.getOther();
+ default:
+ throw new HibernateException( "Unsupported property index " + i );
+ }
+
+ }
+
+ public void setPropertyValue(Object aObject, int i, Object aObject1) throws HibernateException {
+ MyOid dbOid = (MyOid) aObject;
+ switch ( i ) {
+ case 0:
+ dbOid.setHigh( (Integer) aObject1 );
+ case 1:
+ dbOid.setMiddle( (Integer) aObject1 );
+ case 2:
+ dbOid.setLow( (Integer) aObject1 );
+ case 3:
+ dbOid.setOther( (Integer) aObject1 );
+ default:
+ throw new HibernateException( "Unsupported property index " + i );
+ }
+ }
+
+ public Class returnedClass() {
+ return MyOid.class;
+ }
+
+ public boolean equals(Object x, Object y) throws HibernateException {
+ if ( x == y ) return true;
+ if ( x == null || y == null ) return false;
+
+ MyOid oid1 = (MyOid) x;
+ MyOid oid2 = (MyOid) y;
+
+ if ( oid1.getHigh() != oid2.getHigh() ) {
+ return false;
+ }
+ if ( oid1.getMiddle() != oid2.getMiddle() ) {
+ return false;
+ }
+ if ( oid1.getLow() != oid2.getLow() ) {
+ return false;
+ }
+ return oid1.getOther() == oid2.getOther();
+
+ }
+
+ public int hashCode(Object aObject) throws HibernateException {
+ return aObject.hashCode();
+ }
+
+ public Object nullSafeGet(
+ ResultSet aResultSet, String[] names, SessionImplementor aSessionImplementor, Object aObject
+ ) throws HibernateException, SQLException {
+ Integer highval = (Integer) Hibernate.INTEGER.nullSafeGet( aResultSet, names[0] );
+ Integer midval = (Integer) Hibernate.INTEGER.nullSafeGet( aResultSet, names[1] );
+ Integer lowval = (Integer) Hibernate.INTEGER.nullSafeGet( aResultSet, names[2] );
+ Integer other = (Integer) Hibernate.INTEGER.nullSafeGet( aResultSet, names[3] );
+
+ return new MyOid( highval, midval, lowval, other );
+ }
+
+ public void nullSafeSet(
+ PreparedStatement aPreparedStatement, Object value, int index, SessionImplementor aSessionImplementor
+ ) throws HibernateException, SQLException {
+ MyOid c;
+ if ( value == null ) {
+ // todo is this correct?
+ throw new HibernateException( "Oid object may not be null" );
+ }
+ else {
+ c = (MyOid) value;
+ }
+
+ Hibernate.INTEGER.nullSafeSet( aPreparedStatement, c.getHigh(), index );
+ Hibernate.INTEGER.nullSafeSet( aPreparedStatement, c.getMiddle(), index + 1 );
+ Hibernate.INTEGER.nullSafeSet( aPreparedStatement, c.getLow(), index + 2 );
+ Hibernate.INTEGER.nullSafeSet( aPreparedStatement, c.getOther(), index + 3 );
+ }
+
+ public Object deepCopy(Object aObject) throws HibernateException {
+ MyOid oldOid = (MyOid) aObject;
+
+ return new MyOid( oldOid.getHigh(), oldOid.getMiddle(), oldOid.getLow(), oldOid.getOther() );
+ }
+
+ public boolean isMutable() {
+ return false;
+ }
+
+ public Serializable disassemble(Object value, SessionImplementor aSessionImplementor) throws HibernateException {
+ return (Serializable) deepCopy( value );
+ }
+
+ public Object assemble(Serializable cached, SessionImplementor aSessionImplementor, Object aObject)
+ throws HibernateException {
+ return deepCopy( cached );
+ }
+
+ public Object replace(Object original, Object target, SessionImplementor aSessionImplementor, Object aObject2)
+ throws HibernateException {
+ // we are immutable. return original
+ return original;
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/type/TypeTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/type/TypeTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/type/TypeTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,31 @@
+//$Id: TypeTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.type;
+
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class TypeTest extends TestCase {
+ public void testIdWithMulticolumns() throws Exception {
+ Session s;
+ Transaction tx;
+ s = openSession();
+ tx = s.beginTransaction();
+ Dvd lesOiseaux = new Dvd();
+ lesOiseaux.setTitle( "Les oiseaux" );
+ s.persist( lesOiseaux );
+ s.flush();
+ assertNotNull( lesOiseaux.getId() );
+ tx.rollback();
+ s.close();
+ }
+
+ protected Class[] getMappings() {
+ return new Class[]{
+ Dvd.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/various/Antenna.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/various/Antenna.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/various/Antenna.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,25 @@
+//$Id: Antenna.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.various;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.Column;
+
+import org.hibernate.annotations.Generated;
+import org.hibernate.annotations.GenerationTime;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Antenna {
+ @Id public Integer id;
+ @Generated(GenerationTime.ALWAYS) @Column()
+ public String longitude;
+
+ @Generated(GenerationTime.INSERT) @Column(insertable = false)
+ public String latitude;
+
+ @Generated(GenerationTime.NEVER)
+ public Double power;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/various/Conductor.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/various/Conductor.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/various/Conductor.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,54 @@
+//$Id: Conductor.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.various;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.Version;
+
+import org.hibernate.annotations.Index;
+import org.hibernate.annotations.OptimisticLock;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Conductor {
+ @Id
+ @GeneratedValue
+ private Integer id;
+
+ @Column(name = "cond_name")
+ @Index(name = "cond_name")
+ @OptimisticLock(excluded = true)
+ private String name;
+
+ @Version
+ private Long version;
+
+
+ public Long getVersion() {
+ return version;
+ }
+
+ public void setVersion(Long version) {
+ this.version = version;
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/various/GeneratedTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/various/GeneratedTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/various/GeneratedTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,30 @@
+//$Id: GeneratedTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.various;
+
+import org.hibernate.test.annotations.TestCase;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class GeneratedTest extends TestCase {
+
+ public void testGenerated() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Antenna antenna = new Antenna();
+ antenna.id = new Integer(1);
+ s.persist( antenna );
+ assertNull( antenna.latitude );
+ assertNull( antenna.longitude );
+ tx.rollback();
+ s.close();
+ }
+
+ protected Class[] getMappings() {
+ return new Class[] {
+ Antenna.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/various/IndexTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/various/IndexTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/various/IndexTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,63 @@
+//$Id: IndexTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.various;
+
+import java.util.Date;
+
+import org.hibernate.Session;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class IndexTest extends TestCase {
+ public void testIndexManyToOne() throws Exception {
+ //TODO find a way to test indexes???
+ Session s = openSession();
+ s.getTransaction().begin();
+ Conductor emmanuel = new Conductor();
+ emmanuel.setName( "Emmanuel" );
+ s.persist( emmanuel );
+ Vehicule tank = new Vehicule();
+ tank.setCurrentConductor( emmanuel );
+ tank.setRegistrationNumber( "324VX43" );
+ s.persist( tank );
+ s.flush();
+ s.delete( tank );
+ s.delete( emmanuel );
+ s.getTransaction().rollback();
+ s.close();
+ }
+
+ public void testIndexAndJoined() throws Exception {
+ Session s = openSession();
+ s.getTransaction().begin();
+ Conductor cond = new Conductor();
+ cond.setName( "Bob" );
+ s.persist( cond );
+ ProfessionalAgreement agreement = new ProfessionalAgreement();
+ agreement.setExpirationDate( new Date() );
+ s.persist( agreement );
+ Truck truck = new Truck();
+ truck.setAgreement( agreement );
+ truck.setWeight( 20 );
+ truck.setRegistrationNumber( "2003424" );
+ truck.setYear( 2005 );
+ truck.setCurrentConductor( cond );
+ s.persist( truck );
+ s.flush();
+ s.delete( truck );
+ s.delete( agreement );
+ s.delete( cond );
+ s.getTransaction().rollback();
+ s.close();
+ }
+
+ protected Class[] getMappings() {
+ return new Class[]{
+ Conductor.class,
+ Vehicule.class,
+ ProfessionalAgreement.class,
+ Truck.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/various/ProfessionalAgreement.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/various/ProfessionalAgreement.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/various/ProfessionalAgreement.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,34 @@
+//$Id: ProfessionalAgreement.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.various;
+
+import java.util.Date;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class ProfessionalAgreement {
+ @Id
+ @GeneratedValue
+ private Integer id;
+ private Date expirationDate;
+
+ public Date getExpirationDate() {
+ return expirationDate;
+ }
+
+ public void setExpirationDate(Date expirationDate) {
+ this.expirationDate = expirationDate;
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/various/Truck.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/various/Truck.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/various/Truck.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,39 @@
+//$Id: Truck.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.various;
+
+import javax.persistence.Entity;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+
+import org.hibernate.annotations.Index;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Truck extends Vehicule {
+ @Index(name = "weigth_idx")
+ private int weight;
+
+ @ManyToOne
+ @JoinColumn(name = "agreement_id")
+ @Index(name = "agreement_idx")
+ private ProfessionalAgreement agreement;
+
+ public int getWeight() {
+ return weight;
+ }
+
+ public void setWeight(int weight) {
+ this.weight = weight;
+ }
+
+ public ProfessionalAgreement getAgreement() {
+ return agreement;
+ }
+
+ public void setAgreement(ProfessionalAgreement agreement) {
+ this.agreement = agreement;
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/various/Vehicule.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/various/Vehicule.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/various/Vehicule.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,83 @@
+//$Id: Vehicule.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.various;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+
+import org.hibernate.annotations.GenericGenerator;
+import org.hibernate.annotations.Index;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@Inheritance(strategy = InheritanceType.JOINED)
+(a)org.hibernate.annotations.Table(appliesTo = "Vehicule",
+ indexes = {
+ @Index(name = "improbableindex", columnNames = {"registration", "Conductor_fk"}),
+ @Index(name = "secondone", columnNames = {"Conductor_fk"})
+ }
+)
+public class Vehicule {
+ @Id
+ @GeneratedValue(generator = "gen")
+ @GenericGenerator(name = "gen", strategy = "uuid")
+ private String id;
+ @Column(name = "registration")
+ private String registrationNumber;
+ @ManyToOne(optional = false)
+ @JoinColumn(name = "Conductor_fk")
+ @Index(name = "thirdone")
+ private Conductor currentConductor;
+ @Index(name = "year_idx")
+ private Integer year;
+ @ManyToOne(optional = true)
+ @Index(name = "forthone")
+ private Conductor previousConductor;
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public String getRegistrationNumber() {
+ return registrationNumber;
+ }
+
+ public void setRegistrationNumber(String registrationNumber) {
+ this.registrationNumber = registrationNumber;
+ }
+
+ public Conductor getCurrentConductor() {
+ return currentConductor;
+ }
+
+ public void setCurrentConductor(Conductor currentConductor) {
+ this.currentConductor = currentConductor;
+ }
+
+ public Integer getYear() {
+ return year;
+ }
+
+ public void setYear(Integer year) {
+ this.year = year;
+ }
+
+ public Conductor getPreviousConductor() {
+ return previousConductor;
+ }
+
+ public void setPreviousConductor(Conductor previousConductor) {
+ this.previousConductor = previousConductor;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/various/VersionTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/various/VersionTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/various/VersionTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,41 @@
+//$Id: VersionTest.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.various;
+
+import org.hibernate.Session;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class VersionTest extends TestCase {
+
+ public void testOptimisticLockDisabled() throws Exception {
+ Conductor c = new Conductor();
+ c.setName( "Bob" );
+ Session s = openSession( );
+ s.getTransaction().begin();
+ s.persist( c );
+ s.flush();
+
+ s.clear();
+
+ c = (Conductor) s.get( Conductor.class, c.getId() );
+ Long version = c.getVersion();
+ c.setName( "Don" );
+ s.flush();
+
+ s.clear();
+
+ c = (Conductor) s.get( Conductor.class, c.getId() );
+ assertEquals( version, c.getVersion() );
+
+ s.getTransaction().rollback();
+ s.close();
+ }
+
+ protected Class[] getMappings() {
+ return new Class[] {
+ Conductor.class
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/CarModel.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/CarModel.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/CarModel.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,19 @@
+//$Id: CarModel.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.xml.ejb3;
+
+import java.util.Date;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class CarModel extends Model {
+ private Date year;
+
+ public Date getYear() {
+ return year;
+ }
+
+ public void setYear(Date year) {
+ this.year = year;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/Ejb3XmlTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/Ejb3XmlTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/Ejb3XmlTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,86 @@
+//$Id: Ejb3XmlTest.java 16301 2009-04-10 23:26:04Z gbadner $
+package org.hibernate.test.annotations.xml.ejb3;
+
+import java.util.Date;
+import java.util.List;
+
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class Ejb3XmlTest extends TestCase {
+ public void testEjb3Xml() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ CarModel model = new CarModel();
+ model.setYear( new Date() );
+ Manufacturer manufacturer = new Manufacturer();
+ //s.persist( manufacturer );
+ model.setManufacturer( manufacturer );
+ manufacturer.getModels().add( model );
+ s.persist( model );
+ s.flush();
+ s.clear();
+
+ model.setYear( new Date() );
+ manufacturer = (Manufacturer) s.get( Manufacturer.class, manufacturer.getId() );
+ List<Model> cars = s.getNamedQuery( "allModelsPerManufacturer" )
+ .setParameter( "manufacturer", manufacturer )
+ .list();
+ assertEquals( 1, cars.size() );
+ for ( Model car : cars ) {
+ assertNotNull( car.getManufacturer() );
+ s.delete( manufacturer );
+ s.delete( car );
+ }
+ tx.rollback();
+ s.close();
+ }
+
+ public void testXMLEntityHandled() throws Exception {
+ Session s = openSession();
+ s.getTransaction().begin();
+ Lighter l = new Lighter();
+ l.name = "Blue";
+ l.power = "400F";
+ s.persist( l );
+ s.flush();
+ s.getTransaction().rollback();
+ s.close();
+ }
+
+ public void testXmlDefaultOverriding() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Manufacturer manufacturer = new Manufacturer();
+ s.persist( manufacturer );
+ s.flush();
+ s.clear();
+
+ assertEquals( 1, s.getNamedQuery( "manufacturer.findAll" ).list().size() );
+ tx.rollback();
+ s.close();
+ }
+
+ protected Class[] getMappings() {
+ return new Class[]{
+ CarModel.class,
+ Manufacturer.class,
+ Model.class,
+ Light.class
+ //Lighter.class xml only entuty
+ };
+ }
+
+ @Override
+ protected String[] getXmlFiles() {
+ return new String[]{
+ "org/hibernate/test/annotations/xml/ejb3/orm.xml",
+ "org/hibernate/test/annotations/xml/ejb3/orm2.xml",
+ "org/hibernate/test/annotations/xml/ejb3/orm3.xml"
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/Light.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/Light.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/Light.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,10 @@
+//$Id: Light.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.xml.ejb3;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class Light {
+ public String name;
+ public String power;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/Lighter.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/Lighter.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/Lighter.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,10 @@
+//$Id: Lighter.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.xml.ejb3;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class Lighter {
+ public String name;
+ public String power;
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/Manufacturer.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/Manufacturer.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/Manufacturer.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,39 @@
+//$Id: Manufacturer.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.xml.ejb3;
+
+import java.util.HashSet;
+import java.util.Set;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.OneToMany;
+import javax.persistence.NamedQuery;
+import javax.persistence.TableGenerator;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+@NamedQuery(name="manufacturer.findAll", query = "from Manufacturer where 1 = 2")
+@TableGenerator(name="generator", table = "this is a broken name with select from and other SQL keywords")
+public class Manufacturer {
+ private Integer id;
+ private Set<Model> models = new HashSet<Model>();
+
+ @Id
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ @OneToMany
+ public Set<Model> getModels() {
+ return models;
+ }
+
+ public void setModels(Set<Model> models) {
+ this.models = models;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/Model.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/Model.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/Model.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,26 @@
+//$Id: Model.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.xml.ejb3;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class Model {
+ private Integer id;
+ private Manufacturer manufacturer;
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public Manufacturer getManufacturer() {
+ return manufacturer;
+ }
+
+ public void setManufacturer(Manufacturer manufacturer) {
+ this.manufacturer = manufacturer;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/orm.xml
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/orm.xml (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/orm.xml 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,56 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ version="1.0"
+ >
+ <!-- no grammar specified should pass -->
+ <persistence-unit-metadata>
+ <persistence-unit-defaults>
+ <cascade-persist/>
+ </persistence-unit-defaults>
+ </persistence-unit-metadata>
+ <package>org.hibernate.test.annotations.xml.ejb3</package>
+ <table-generator name="generator" table="table_id"/>
+ <named-query name="manufacturer.findAll">
+ <query>select m from Manufacturer m</query>
+ </named-query>
+ <entity class="Model" access="PROPERTY" name="ModelZ" metadata-complete="true">
+ <table name="ModelZ">
+ </table>
+ <inheritance strategy="JOINED"/>
+ <attributes>
+ <id name="id">
+ <column name="fld_id"/>
+ <generated-value strategy="TABLE" generator="generator"/>
+ </id>
+ <basic name="unknownProperty"/>
+ <many-to-one name="manufacturer" fetch="LAZY">
+ <join-column name="manufacturer_pk"/>
+ </many-to-one>
+ </attributes>
+ </entity>
+ <entity class="CarModel" metadata-complete="true">
+ <primary-key-join-column name="model_id"/>
+ <inheritance strategy="JOINED"/>
+ <named-query name="allModelsPerManufacturer">
+ <query>from ModelZ m where m.manufacturer = :manufacturer</query>
+ <hint name="org.hibernate.timeout" value="200"/>
+ </named-query>
+ <exclude-default-listeners/>
+ <exclude-superclass-listeners/>
+ <attributes>
+ <basic name="year" optional="false">
+ <temporal>DATE</temporal>
+ </basic>
+ </attributes>
+ </entity>
+ <entity class="Manufacturer">
+ <attributes>
+ <id name="id">
+ <generated-value strategy="AUTO"/>
+ </id>
+ <one-to-many name="models" mapped-by="manufacturer"/>
+ </attributes>
+ </entity>
+</entity-mappings>
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/orm2.xml
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/orm2.xml (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/orm2.xml 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_1_0.xsd"
+ version="1.0"
+ >
+ <package>org.hibernate.test.annotations.xml.ejb3</package>
+ <entity class="Light" access="FIELD" metadata-complete="true">
+ <attributes>
+ <id name="name">
+ <column name="fld_id"/>
+ </id>
+ <basic name="power"></basic>
+ </attributes>
+ </entity>
+</entity-mappings>
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/orm3.xml
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/orm3.xml (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/ejb3/orm3.xml 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_1_0.xsd"
+ version="1.0"
+ >
+ <package>org.hibernate.test.annotations.xml.ejb3</package>
+ <entity class="Lighter" access="FIELD" metadata-complete="true">
+ <attributes>
+ <id name="name">
+ <column name="fld_id"/>
+ </id>
+ <basic name="power"></basic>
+ </attributes>
+ </entity>
+</entity-mappings>
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/A.hbm.xml
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/A.hbm.xml (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/A.hbm.xml 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,12 @@
+<?xml version="1.0"?>
+<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+ "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
+<!-- Generated Nov 9, 2006 6:27:53 PM by Hibernate Tools 3.2.0.beta7 -->
+<hibernate-mapping>
+ <class name="org.hibernate.test.annotations.xml.hbm.AImpl" table="A"
+ proxy="org.hibernate.test.annotations.xml.hbm.A">
+ <id name="AId" column="aID" type="java.lang.Integer">
+ <generator class="identity"/>
+ </id>
+ </class>
+</hibernate-mapping>
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/A.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/A.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/A.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,11 @@
+//$Id: A.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.xml.hbm;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public interface A extends java.io.Serializable {
+ public Integer getAId();
+
+ public void setAId(Integer aId);
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/AImpl.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/AImpl.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/AImpl.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,34 @@
+//$Id: AImpl.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.xml.hbm;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+import javax.persistence.Table;
+import javax.persistence.GeneratedValue;
+
+@Entity
+@Inheritance( strategy = InheritanceType.JOINED )
+(a)org.hibernate.annotations.Proxy( proxyClass = A.class )
+@Table( name = "A" )
+public class AImpl implements A {
+ private static final long serialVersionUID = 1L;
+
+ private Integer aId = 0;
+
+ public AImpl() {
+ }
+
+ @Id
+ @GeneratedValue
+ @Column( name = "aID" )
+ public Integer getAId() {
+ return this.aId;
+ }
+
+ public void setAId(Integer aId) {
+ this.aId = aId;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/B.hbm.xml
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/B.hbm.xml (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/B.hbm.xml 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,13 @@
+<?xml version="1.0"?>
+<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+ "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
+<!-- Generated Nov 9, 2006 6:27:53 PM by Hibernate Tools 3.2.0.beta7 -->
+<hibernate-mapping>
+ <joined-subclass name="org.hibernate.test.annotations.xml.hbm.BImpl" table="B"
+ proxy="org.hibernate.test.annotations.xml.hbm.B"
+ extends="org.hibernate.test.annotations.xml.hbm.AImpl">
+ <key column="aID"/>
+ <property name="BId" column="bID" type="java.lang.Integer"
+ not-null="true"/>
+ </joined-subclass>
+</hibernate-mapping>
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/B.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/B.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/B.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,11 @@
+//$Id: B.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.xml.hbm;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public interface B extends A {
+ public Integer getBId();
+
+ public void setBId(Integer bId);
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/BImpl.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/BImpl.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/BImpl.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,26 @@
+//$Id: BImpl.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.xml.hbm;
+
+import javax.persistence.Entity;
+import javax.persistence.Table;
+
+@Entity
+(a)org.hibernate.annotations.Proxy( proxyClass = B.class )
+@Table( name = "B" )
+public class BImpl extends AImpl implements B {
+ private static final long serialVersionUID = 1L;
+
+ private Integer bId = 0;
+
+ public BImpl() {
+ super();
+ }
+
+ public Integer getBId() {
+ return bId;
+ }
+
+ public void setBId(Integer bId) {
+ this.bId = bId;
+ }
+}
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/CloudType.hbm.xml
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/CloudType.hbm.xml (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/CloudType.hbm.xml 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,15 @@
+<?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.annotations.xml.hbm">
+
+ <class name="CloudType">
+ <id name="id">
+ <generator class="native"/>
+ </id>
+ <property name="name"/>
+ </class>
+
+</hibernate-mapping>
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/CloudType.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/CloudType.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/CloudType.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,26 @@
+//$Id: CloudType.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.xml.hbm;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class CloudType {
+ private Integer id;
+ private String name;
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/Government.hbm.xml
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/Government.hbm.xml (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/Government.hbm.xml 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,16 @@
+<?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.annotations.xml.hbm">
+
+ <class name="Government">
+ <id name="id">
+ <generator class="native"/>
+ </id>
+ <property name="name"/>
+ <many-to-one name="primeMinister" column="primeMinister_id"/>
+ </class>
+
+</hibernate-mapping>
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/Government.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/Government.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/Government.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,35 @@
+//$Id: Government.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.xml.hbm;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class Government {
+ private Integer id;
+ private String name;
+ private PrimeMinister primeMinister;
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public PrimeMinister getPrimeMinister() {
+ return primeMinister;
+ }
+
+ public void setPrimeMinister(PrimeMinister primeMinister) {
+ this.primeMinister = primeMinister;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/HbmTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/HbmTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/HbmTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,82 @@
+//$Id:HbmTest.java 9793 2006-04-26 02:20:18 -0400 (mer., 26 avr. 2006) epbernard $
+package org.hibernate.test.annotations.xml.hbm;
+
+import java.util.HashSet;
+
+import org.hibernate.Session;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class HbmTest extends TestCase {
+
+ public void testManyToOne() throws Exception {
+ Session s = openSession();
+ s.getTransaction().begin();
+ Government gov = new Government();
+ gov.setName( "Liberals" );
+ s.save( gov );
+ PrimeMinister pm = new PrimeMinister();
+ pm.setName( "Murray" );
+ pm.setCurrentGovernment( gov );
+ s.save( pm );
+ s.getTransaction().rollback();
+ s.close();
+ }
+
+ public void testOneToMany() throws Exception {
+ Session s = openSession();
+ s.getTransaction().begin();
+ Government gov = new Government();
+ gov.setName( "Liberals" );
+ Government gov2 = new Government();
+ gov2.setName( "Liberals2" );
+ s.save( gov );
+ s.save( gov2 );
+ PrimeMinister pm = new PrimeMinister();
+ pm.setName( "Murray" );
+ pm.setCurrentGovernment( gov );
+ pm.setGovernments( new HashSet() );
+ pm.getGovernments().add( gov2 );
+ pm.getGovernments().add( gov );
+ gov.setPrimeMinister( pm );
+ gov2.setPrimeMinister( pm );
+ s.save( pm );
+ s.flush();
+ s.getTransaction().rollback();
+ s.close();
+ }
+
+ public void testManyToMany() throws Exception {
+ Session s = openSession();
+ s.getTransaction().begin();
+ CloudType type = new CloudType();
+ type.setName( "Cumulus" );
+ Sky sky = new Sky();
+ s.persist( type );
+ sky.getCloudTypes().add(type);
+ s.persist( sky );
+ s.flush();
+ s.getTransaction().rollback();
+ s.close();
+ }
+
+
+ protected Class[] getMappings() {
+ return new Class[]{
+ PrimeMinister.class,
+ Sky.class,
+
+ };
+ }
+
+ @Override
+ protected String[] getXmlFiles() {
+ return new String[]{
+ "org/hibernate/test/annotations/xml/hbm/Government.hbm.xml",
+ "org/hibernate/test/annotations/xml/hbm/CloudType.hbm.xml",
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/HbmWithIdentityTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/HbmWithIdentityTest.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/HbmWithIdentityTest.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,51 @@
+//$Id:HbmTest.java 9793 2006-04-26 02:20:18 -0400 (mer., 26 avr. 2006) epbernard $
+package org.hibernate.test.annotations.xml.hbm;
+
+import java.util.HashSet;
+
+import org.hibernate.Session;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class HbmWithIdentityTest extends TestCase {
+
+ public void testManyToOneAndInterface() throws Exception {
+ Session s = openSession();
+ s.getTransaction().begin();
+ B b = new BImpl();
+ b.setBId( 1 );
+ s.persist( b );
+ Z z = new ZImpl();
+ z.setB( b );
+ s.persist( z );
+ s.flush();
+ s.getTransaction().rollback();
+ s.close();
+ }
+
+
+
+ @Override
+ protected boolean runForCurrentDialect() {
+ return super.runForCurrentDialect() && getDialect().supportsIdentityColumns();
+ }
+
+
+
+ protected Class[] getMappings() {
+ return new Class[]{
+ ZImpl.class
+ };
+ }
+
+ @Override
+ protected String[] getXmlFiles() {
+ return new String[]{
+ "org/hibernate/test/annotations/xml/hbm/A.hbm.xml",
+ "org/hibernate/test/annotations/xml/hbm/B.hbm.xml"
+ };
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/PrimeMinister.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/PrimeMinister.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/PrimeMinister.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,57 @@
+//$Id:PrimeMinister.java 9793 2006-04-26 02:20:18 -0400 (mer., 26 avr. 2006) epbernard $
+package org.hibernate.test.annotations.xml.hbm;
+
+import java.util.Set;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.ManyToOne;
+import javax.persistence.OneToMany;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class PrimeMinister {
+ private Integer id;
+ private String name;
+ private Government currentGovernment;
+ private Set<Government> governments;
+
+ @ManyToOne
+ public Government getCurrentGovernment() {
+ return currentGovernment;
+ }
+
+ public void setCurrentGovernment(Government currentGovernment) {
+ this.currentGovernment = currentGovernment;
+ }
+
+ @Id
+ @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @OneToMany(mappedBy = "primeMinister")
+ public Set<Government> getGovernments() {
+ return governments;
+ }
+
+ public void setGovernments(Set<Government> governments) {
+ this.governments = governments;
+ }
+
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/Sky.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/Sky.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/Sky.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,47 @@
+//$Id: Sky.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.xml.hbm;
+
+import java.util.HashSet;
+import java.util.Set;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.ManyToMany;
+import javax.persistence.ManyToOne;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity(name="EarthSky")
+public class Sky {
+ private Integer id;
+ private Set<CloudType> cloudTypes = new HashSet<CloudType>();
+ private CloudType mainCloud;
+
+ @ManyToMany
+ public Set<CloudType> getCloudTypes() {
+ return cloudTypes;
+ }
+
+ public void setCloudTypes(Set<CloudType> cloudTypes) {
+ this.cloudTypes = cloudTypes;
+ }
+
+ @Id @GeneratedValue
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ @ManyToOne
+ public CloudType getMainCloud() {
+ return mainCloud;
+ }
+
+ public void setMainCloud(CloudType mainCloud) {
+ this.mainCloud = mainCloud;
+ }
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/Z.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/Z.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/Z.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,15 @@
+//$Id: Z.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.xml.hbm;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public interface Z extends java.io.Serializable {
+ public Integer getZId();
+
+ public void setZId(Integer zId);
+
+ public B getB();
+
+ public void setB(B b);
+}
Added: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/ZImpl.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/ZImpl.java (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/xml/hbm/ZImpl.java 2009-11-24 21:03:15 UTC (rev 18049)
@@ -0,0 +1,45 @@
+//$Id: ZImpl.java 14736 2008-06-04 14:23:42Z hardy.ferentschik $
+package org.hibernate.test.annotations.xml.hbm;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.Id;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+import javax.persistence.Table;
+import javax.persistence.GeneratedValue;
+
+@Entity
+@Inheritance( strategy = InheritanceType.JOINED )
+(a)org.hibernate.annotations.Proxy( proxyClass = Z.class )
+@Table( name = "Z" )
+public class ZImpl implements Z {
+ private static final long serialVersionUID = 1L;
+
+ private Integer zId = null;
+ private B b = null;
+
+ @Id
+ @GeneratedValue
+ @Column( name = "zID" )
+ public Integer getZId() {
+ return zId;
+ }
+
+ public void setZId(Integer zId) {
+ this.zId = zId;
+ }
+
+ @ManyToOne( optional = false, targetEntity = BImpl.class, fetch = FetchType.LAZY )
+ @JoinColumn( name = "bID", referencedColumnName = "bID")
+ public B getB() {
+ return b;
+ }
+
+ public void setB(B b) {
+ this.b = b;
+ }
+}
15 years
Hibernate SVN: r18048 - annotations/branches/v3_4_0_GA_CP.
by hibernate-commits@lists.jboss.org
Author: stliu
Date: 2009-11-24 15:29:09 -0500 (Tue, 24 Nov 2009)
New Revision: 18048
Removed:
annotations/branches/v3_4_0_GA_CP/doc/
Log:
JBPAPP-3150 change the build tool of Hibernate Annotations(eap 5 cp branch)
15 years
Hibernate SVN: r18046 - in annotations/branches/v3_4_0_GA_CP/src: test and 1 other directories.
by hibernate-commits@lists.jboss.org
Author: stliu
Date: 2009-11-24 15:27:09 -0500 (Tue, 24 Nov 2009)
New Revision: 18046
Added:
annotations/branches/v3_4_0_GA_CP/src/test/java/
annotations/branches/v3_4_0_GA_CP/src/test/resources/
annotations/branches/v3_4_0_GA_CP/src/test/resources/ehcache.xml
annotations/branches/v3_4_0_GA_CP/src/test/resources/hibernate.properties
annotations/branches/v3_4_0_GA_CP/src/test/resources/log4j.properties
Removed:
annotations/branches/v3_4_0_GA_CP/src/test-resources/
Log:
JBPAPP-3150 change the build tool of Hibernate Annotations(eap 5 cp branch)
Added: annotations/branches/v3_4_0_GA_CP/src/test/resources/ehcache.xml
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/resources/ehcache.xml (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/resources/ehcache.xml 2009-11-24 20:27:09 UTC (rev 18046)
@@ -0,0 +1,80 @@
+<ehcache>
+ <!-- Sets the path to the directory where cache .data files are created.
+ If the path is a Java System Property it is replaced by
+ its value in the running VM.
+
+ The following properties are translated:
+ user.home - User's home directory
+ user.dir - User's current working directory
+ java.io.tmpdir - Default temp file path -->
+
+ <diskStore path="java.io.tmpdir"/>
+ <!--Default Cache configuration. These will applied to caches programmatically created through
+ the CacheManager.
+ The following attributes are required for defaultCache:
+ maxInMemory - Sets the maximum number of objects that will be created in memory
+ eternal - Sets whether elements are eternal. If eternal, timeouts are ignored and the element
+ is never expired.
+ timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
+ if the element is not eternal. Idle time is now - last accessed time
+ timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
+ if the element is not eternal. TTL is now - creation time
+ overflowToDisk - Sets whether elements can overflow to disk when the in-memory cache
+ has reached the maxInMemory limit.
+
+ -->
+
+ <defaultCache
+ maxElementsInMemory="10000"
+ eternal="false"
+ timeToIdleSeconds="120"
+ timeToLiveSeconds="120"
+ overflowToDisk="true"
+ />
+ <!--Predefined caches. Add your cache configuration settings here.
+ If you do not have a configuration for your cache a WARNING will be issued when the
+ CacheManager starts
+ The following attributes are required for defaultCache:
+ name - Sets the name of the cache. This is used to identify the cache. It must be unique.
+ maxInMemory - Sets the maximum number of objects that will be created in memory
+ eternal - Sets whether elements are eternal. If eternal, timeouts are ignored and the element
+ is never expired.
+ timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
+ if the element is not eternal. Idle time is now - last accessed time
+ timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
+ if the element is not eternal. TTL is now - creation time
+ overflowToDisk - Sets whether elements can overflow to disk when the in-memory cache
+ has reached the maxInMemory limit.
+ -->
+
+ <!-- Sample cache named sampleCache1
+ This cache contains a maximum in memory of 10000 elements, and will expire
+ an element if it is idle for more than 5 minutes and lives for more than
+ 10 minutes.
+
+ If there are more than 10000 elements it will overflow to the
+ disk cache, which in this configuration will go to wherever java.io.tmp is
+ defined on your system. On a standard Linux system this will be /tmp"
+ -->
+
+ <cache name="sampleCache1"
+ maxElementsInMemory="10000"
+ eternal="false"
+ timeToIdleSeconds="300"
+ timeToLiveSeconds="600"
+ overflowToDisk="true"
+ />
+
+ <!-- Sample cache named sampleCache2
+ This cache contains 1000 elements. Elements will always be held in memory.
+ They are not expired. -->
+ <cache name="sampleCache2"
+ maxElementsInMemory="1000"
+ eternal="true"
+ timeToIdleSeconds="0"
+ timeToLiveSeconds="0"
+ overflowToDisk="false"
+ />
+
+ <!-- Place configuration for your caches following -->
+</ehcache>
\ No newline at end of file
Added: annotations/branches/v3_4_0_GA_CP/src/test/resources/hibernate.properties
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/resources/hibernate.properties (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/resources/hibernate.properties 2009-11-24 20:27:09 UTC (rev 18046)
@@ -0,0 +1,303 @@
+######################
+### Query Language ###
+######################
+
+## define query language constants / function names
+
+hibernate.query.substitutions true 1, false 0, yes 'Y', no 'N'
+
+
+## select the classic query parser
+
+#hibernate.query.factory_class org.hibernate.hql.classic.ClassicQueryTranslatorFactory
+
+hibernate.format_sql true
+
+
+
+#################
+### Platforms ###
+#################
+
+hibernate.dialect ${db.dialect}
+hibernate.connection.driver_class ${jdbc.driver}
+hibernate.connection.url ${jdbc.url}
+hibernate.connection.username ${jdbc.user}
+hibernate.connection.password ${jdbc.pass}
+hibernate.connection.isolation ${jdbc.isolation}
+
+
+#################################
+### Hibernate Connection Pool ###
+#################################
+
+hibernate.connection.pool_size 1
+
+###########################
+### C3P0 Connection Pool###
+###########################
+
+#hibernate.c3p0.max_size 2
+#hibernate.c3p0.min_size 2
+#hibernate.c3p0.timeout 5000
+#hibernate.c3p0.max_statements 100
+#hibernate.c3p0.idle_test_period 3000
+#hibernate.c3p0.acquire_increment 2
+#hibernate.c3p0.validate false
+
+##############################
+### Proxool Connection Pool###
+##############################
+
+## Properties for external configuration of Proxool
+
+hibernate.proxool.pool_alias pool1
+
+## Only need one of the following
+
+#hibernate.proxool.existing_pool true
+#hibernate.proxool.xml proxool.xml
+#hibernate.proxool.properties proxool.properties
+
+
+
+#################################
+### Plugin ConnectionProvider ###
+#################################
+
+## use a custom ConnectionProvider (if not set, Hibernate will choose a built-in ConnectionProvider using hueristics)
+
+#hibernate.connection.provider_class org.hibernate.connection.DriverManagerConnectionProvider
+#hibernate.connection.provider_class org.hibernate.connection.DatasourceConnectionProvider
+#hibernate.connection.provider_class org.hibernate.connection.C3P0ConnectionProvider
+#hibernate.connection.provider_class org.hibernate.connection.DBCPConnectionProvider
+#hibernate.connection.provider_class org.hibernate.connection.ProxoolConnectionProvider
+
+
+
+#######################
+### Transaction API ###
+#######################
+
+## Enable automatic flush during the JTA beforeCompletion() callback
+## (This setting is relevant with or without the Transaction API)
+
+#hibernate.transaction.flush_before_completion
+
+
+## Enable automatic session close at the end of transaction
+## (This setting is relevant with or without the Transaction API)
+
+#hibernate.transaction.auto_close_session
+
+
+## the Transaction API abstracts application code from the underlying JTA or JDBC transactions
+
+#hibernate.transaction.factory_class org.hibernate.transaction.JTATransactionFactory
+#hibernate.transaction.factory_class org.hibernate.transaction.JDBCTransactionFactory
+
+
+## to use JTATransactionFactory, Hibernate must be able to locate the UserTransaction in JNDI
+## default is java:comp/UserTransaction
+## you do NOT need this setting if you specify hibernate.transaction.manager_lookup_class
+
+#jta.UserTransaction jta/usertransaction
+#jta.UserTransaction javax.transaction.UserTransaction
+#jta.UserTransaction UserTransaction
+
+
+## to use the second-level cache with JTA, Hibernate must be able to obtain the JTA TransactionManager
+
+#hibernate.transaction.manager_lookup_class org.hibernate.transaction.JBossTransactionManagerLookup
+#hibernate.transaction.manager_lookup_class org.hibernate.transaction.WeblogicTransactionManagerLookup
+#hibernate.transaction.manager_lookup_class org.hibernate.transaction.WebSphereTransactionManagerLookup
+#hibernate.transaction.manager_lookup_class org.hibernate.transaction.OrionTransactionManagerLookup
+#hibernate.transaction.manager_lookup_class org.hibernate.transaction.ResinTransactionManagerLookup
+
+
+
+##############################
+### Miscellaneous Settings ###
+##############################
+
+## print all generated SQL to the console
+
+#hibernate.show_sql true
+
+
+## add comments to the generated SQL
+
+#hibernate.use_sql_comments true
+
+
+## generate statistics
+
+#hibernate.generate_statistics true
+
+
+## auto schema export
+
+#hibernate.hbm2ddl.auto create-drop
+#hibernate.hbm2ddl.auto create
+#hibernate.hbm2ddl.auto update
+
+
+## specify a default schema and catalog for unqualified tablenames
+
+#hibernate.default_schema test
+#hibernate.default_catalog test
+
+
+## enable ordering of SQL UPDATEs by primary key
+
+hibernate.order_updates true
+
+
+## set the maximum depth of the outer join fetch tree
+
+hibernate.max_fetch_depth 1
+
+
+## set the default batch size for batch fetching
+
+hibernate.default_batch_fetch_size 100
+
+
+## rollback generated identifier values of deleted entities to default values
+
+#hibernate.use_identifer_rollback true
+
+
+## enable CGLIB reflection optimizer (enabled by default)
+
+#hibernate.cglib.use_reflection_optimizer false
+
+
+
+#####################
+### JDBC Settings ###
+#####################
+
+## specify a JDBC isolation level
+
+#hibernate.connection.isolation 4
+
+
+## enable JDBC autocommit (not recommended!)
+
+#hibernate.connection.autocommit true
+
+
+## set the JDBC fetch size
+
+#hibernate.jdbc.fetch_size 25
+
+
+## set the maximum JDBC 2 batch size (a nonzero value enables batching)
+
+#hibernate.jdbc.batch_size 0
+
+
+## enable batch updates even for versioned data
+
+hibernate.jdbc.batch_versioned_data true
+
+
+## enable use of JDBC 2 scrollable ResultSets (specifying a Dialect will cause Hibernate to use a sensible default)
+
+#hibernate.jdbc.use_scrollable_resultset true
+
+
+## use streams when writing binary types to / from JDBC
+
+hibernate.jdbc.use_streams_for_binary true
+
+
+## use JDBC 3 PreparedStatement.getGeneratedKeys() to get the identifier of an inserted row
+
+#hibernate.jdbc.use_get_generated_keys false
+
+
+## choose a custom JDBC batcher
+
+# hibernate.jdbc.factory_class
+
+
+## enable JDBC result set column alias caching
+## (minor performance enhancement for broken JDBC drivers)
+
+# hibernate.jdbc.wrap_result_sets
+
+
+## choose a custom SQL exception converter
+
+#hibernate.jdbc.sql_exception_converter
+
+
+
+##########################
+### Second-level Cache ###
+##########################
+
+## optimize chache for minimal "puts" instead of minimal "gets" (good for clustered cache)
+
+#hibernate.cache.use_minimal_puts true
+
+
+## set a prefix for cache region names
+
+hibernate.cache.region_prefix hibernate.test
+
+
+## disable the second-level cache
+
+#hibernate.cache.use_second_level_cache false
+
+
+## enable the query cache
+
+hibernate.cache.use_query_cache true
+
+
+## store the second-level cache entries in a more human-friendly format
+
+#hibernate.cache.use_structured_entries true
+
+
+## choose a cache implementation
+
+#hibernate.cache.provider_class org.hibernate.cache.EhCacheProvider
+#hibernate.cache.provider_class org.hibernate.cache.EmptyCacheProvider
+hibernate.cache.provider_class org.hibernate.cache.HashtableCacheProvider
+#hibernate.cache.provider_class org.hibernate.cache.TreeCacheProvider
+#hibernate.cache.provider_class org.hibernate.cache.OSCacheProvider
+#hibernate.cache.provider_class org.hibernate.cache.SwarmCacheProvider
+
+
+## choose a custom query cache implementation
+
+#hibernate.cache.query_cache_factory
+
+
+
+############
+### JNDI ###
+############
+
+## specify a JNDI name for the SessionFactory
+
+#hibernate.session_factory_name hibernate/session_factory
+
+
+## Hibernate uses JNDI to bind a name to a SessionFactory and to look up the JTA UserTransaction;
+## if hibernate.jndi.* are not specified, Hibernate will use the default InitialContext() which
+## is the best approach in an application server
+
+#file system
+#hibernate.jndi.class com.sun.jndi.fscontext.RefFSContextFactory
+#hibernate.jndi.url file:/
+
+#WebSphere
+#hibernate.jndi.class com.ibm.websphere.naming.WsnInitialContextFactory
+#hibernate.jndi.url iiop://localhost:900/
+
Added: annotations/branches/v3_4_0_GA_CP/src/test/resources/log4j.properties
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/resources/log4j.properties (rev 0)
+++ annotations/branches/v3_4_0_GA_CP/src/test/resources/log4j.properties 2009-11-24 20:27:09 UTC (rev 18046)
@@ -0,0 +1,51 @@
+### direct log messages to stdout ###
+log4j.appender.stdout=org.apache.log4j.ConsoleAppender
+log4j.appender.stdout.Target=System.out
+log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
+log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
+
+### direct messages to file hibernate.log ###
+log4j.appender.file=org.apache.log4j.FileAppender
+log4j.appender.file.File=hibernate.log
+log4j.appender.file.layout=org.apache.log4j.PatternLayout
+log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
+
+### direct messages to socket - chainsaw ###
+log4j.appender.socket=org.apache.log4j.net.SocketAppender
+log4j.appender.socket.remoteHost=localhost
+log4j.appender.socket.port=4560
+log4j.appender.socket.locationInfo=true
+
+
+### set log levels - for more verbose logging change 'info' to 'debug' ###
+
+log4j.rootLogger=warn, stdout
+
+log4j.logger.org.hibernate=debug
+
+
+### log just the SQL
+log4j.logger.org.hibernate.SQL=debug
+
+#log4j.logger.org.hibernate.engine.CascadingAction=debug
+
+### log JDBC bind parameters ###
+log4j.logger.org.hibernate.type=debug
+
+### log schema export/update ###
+log4j.logger.org.hibernate.tool.hbm2ddl=debug
+
+### log cache activity ###
+log4j.logger.org.hibernate.cache=debug
+
+### enable the following line if you want to track down connection ###
+### leakages when using DriverManagerConnectionProvider ###
+#log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace
+
+### annotation logs
+#log4j.logger.org.hibernate.annotation=info
+#log4j.logger.org.hibernate.cfg=info
+#log4j.logger.org.hibernate.cfg.SettingsFactory=info
+#log4j.logger.org.hibernate.cfg.AnnotationBinder=info
+#log4j.logger.org.hibernate.cfg.AnnotationConfiguration=info
+#log4j.logger.org.hibernate.cfg.Ejb3Column=info
\ No newline at end of file
15 years