Hibernate SVN: r18699 - in core/trunk: core/src/main/java/org/hibernate/event/def and 6 other directories.
by hibernate-commits@lists.jboss.org
Author: gbadner
Date: 2010-02-04 23:00:04 -0500 (Thu, 04 Feb 2010)
New Revision: 18699
Added:
core/trunk/core/src/main/java/org/hibernate/proxy/AbstractSerializableProxy.java
Modified:
core/trunk/core/src/main/java/org/hibernate/engine/StatefulPersistenceContext.java
core/trunk/core/src/main/java/org/hibernate/engine/TwoPhaseLoad.java
core/trunk/core/src/main/java/org/hibernate/event/def/DefaultLoadEventListener.java
core/trunk/core/src/main/java/org/hibernate/proxy/…
[View More]AbstractLazyInitializer.java
core/trunk/core/src/main/java/org/hibernate/proxy/LazyInitializer.java
core/trunk/core/src/main/java/org/hibernate/proxy/pojo/cglib/CGLIBLazyInitializer.java
core/trunk/core/src/main/java/org/hibernate/proxy/pojo/cglib/SerializableProxy.java
core/trunk/core/src/main/java/org/hibernate/proxy/pojo/javassist/JavassistLazyInitializer.java
core/trunk/core/src/main/java/org/hibernate/proxy/pojo/javassist/SerializableProxy.java
core/trunk/testsuite/src/test/java/org/hibernate/test/nonflushedchanges/GetLoadTest.java
core/trunk/testsuite/src/test/java/org/hibernate/test/proxy/ProxyTest.java
core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlyProxyTest.java
Log:
HHH-4841 : Read-only proxies in NonFlushedChanges are not read-only when applied to a new session
Modified: core/trunk/core/src/main/java/org/hibernate/engine/StatefulPersistenceContext.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/engine/StatefulPersistenceContext.java 2010-02-05 02:42:55 UTC (rev 18698)
+++ core/trunk/core/src/main/java/org/hibernate/engine/StatefulPersistenceContext.java 2010-02-05 04:00:04 UTC (rev 18699)
@@ -672,10 +672,19 @@
}
else {
proxy = persister.createProxy( key.getIdentifier(), session );
- proxiesByKey.put(key, proxy); //overwrite old proxy
+ Object proxyOrig = proxiesByKey.put(key, proxy); //overwrite old proxy
+ if ( proxyOrig != null ) {
+ if ( ! ( proxyOrig instanceof HibernateProxy ) ) {
+ throw new AssertionFailure(
+ "proxy not of type HibernateProxy; it is " + proxyOrig.getClass()
+ );
+ }
+ // set the read-only/modifiable mode in the new proxy to what it was in the original proxy
+ boolean readOnlyOrig = ( ( HibernateProxy ) proxyOrig ).getHibernateLazyInitializer().isReadOnly();
+ ( ( HibernateProxy ) proxy ).getHibernateLazyInitializer().setReadOnly( readOnlyOrig );
+ }
return proxy;
- }
-
+ }
}
else {
Modified: core/trunk/core/src/main/java/org/hibernate/engine/TwoPhaseLoad.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/engine/TwoPhaseLoad.java 2010-02-05 02:42:55 UTC (rev 18698)
+++ core/trunk/core/src/main/java/org/hibernate/engine/TwoPhaseLoad.java 2010-02-05 04:00:04 UTC (rev 18699)
@@ -190,13 +190,18 @@
}
}
- boolean isReallyReadOnly = readOnly || !persister.isMutable();
- Object proxy = persistenceContext.getProxy( entityEntry.getEntityKey() );
- if ( proxy != null ) {
- // there is already a proxy for this impl
- // only set the status to read-only if the proxy is read-only
- isReallyReadOnly = ( ( HibernateProxy ) proxy ).getHibernateLazyInitializer().isReadOnly();
+ boolean isReallyReadOnly = readOnly;
+ if ( !persister.isMutable() ) {
+ isReallyReadOnly = true;
}
+ else {
+ Object proxy = persistenceContext.getProxy( entityEntry.getEntityKey() );
+ if ( proxy != null ) {
+ // there is already a proxy for this impl
+ // only set the status to read-only if the proxy is read-only
+ isReallyReadOnly = ( ( HibernateProxy ) proxy ).getHibernateLazyInitializer().isReadOnly();
+ }
+ }
if ( isReallyReadOnly ) {
//no need to take a snapshot - this is a
//performance optimization, but not really
Modified: core/trunk/core/src/main/java/org/hibernate/event/def/DefaultLoadEventListener.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/event/def/DefaultLoadEventListener.java 2010-02-05 02:42:55 UTC (rev 18698)
+++ core/trunk/core/src/main/java/org/hibernate/event/def/DefaultLoadEventListener.java 2010-02-05 04:00:04 UTC (rev 18699)
@@ -360,9 +360,6 @@
Object proxy = persister.createProxy( event.getEntityId(), event.getSession() );
persistenceContext.getBatchFetchQueue().addBatchLoadableEntityKey(keyToLoad);
persistenceContext.addProxy(keyToLoad, proxy);
- ( ( HibernateProxy ) proxy )
- .getHibernateLazyInitializer()
- .setReadOnly( event.getSession().isDefaultReadOnly() || ! persister.isMutable() );
return proxy;
}
}
Modified: core/trunk/core/src/main/java/org/hibernate/proxy/AbstractLazyInitializer.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/proxy/AbstractLazyInitializer.java 2010-02-05 02:42:55 UTC (rev 18698)
+++ core/trunk/core/src/main/java/org/hibernate/proxy/AbstractLazyInitializer.java 2010-02-05 04:00:04 UTC (rev 18699)
@@ -26,12 +26,14 @@
import java.io.Serializable;
+import org.hibernate.AssertionFailure;
import org.hibernate.HibernateException;
import org.hibernate.LazyInitializationException;
import org.hibernate.TransientObjectException;
import org.hibernate.SessionException;
import org.hibernate.engine.EntityKey;
import org.hibernate.engine.SessionImplementor;
+import org.hibernate.persister.entity.EntityPersister;
/**
* Convenience base class for lazy initialization handlers. Centralizes the basic plumbing of doing lazy
@@ -48,6 +50,7 @@
private boolean readOnly;
private boolean unwrap;
private transient SessionImplementor session;
+ private Boolean readOnlyBeforeAttachedToSession;
/**
* For serialization from the non-pojo initializers (HHH-3309)
@@ -65,11 +68,9 @@
protected AbstractLazyInitializer(String entityName, Serializable id, SessionImplementor session) {
this.entityName = entityName;
this.id = id;
- this.readOnly = false;
// initialize other fields depending on session state
if ( session == null ) {
- // would be better to call unsetSession(), but it is not final...
- session = null;
+ unsetSession();
}
else {
setSession( session );
@@ -116,18 +117,27 @@
*/
public final void setSession(SessionImplementor s) throws HibernateException {
if ( s != session ) {
- readOnly = false;
// check for s == null first, since it is least expensive
if ( s == null ){
- // would be better to call unsetSession(), but it is not final...
- session = null;
+ unsetSession();
}
else if ( isConnectedToSession() ) {
//TODO: perhaps this should be some other RuntimeException...
throw new HibernateException("illegally attempted to associate a proxy with two open Sessions");
}
else {
+ // s != null
session = s;
+ if ( readOnlyBeforeAttachedToSession == null ) {
+ // use the default read-only/modifiable setting
+ final EntityPersister persister = s.getFactory().getEntityPersister( entityName );
+ setReadOnly( s.getPersistenceContext().isDefaultReadOnly() || ! persister.isMutable() );
+ }
+ else {
+ // use the read-only/modifiable setting indicated during deserialization
+ setReadOnly( readOnlyBeforeAttachedToSession.booleanValue() );
+ readOnlyBeforeAttachedToSession = null;
+ }
}
}
}
@@ -142,9 +152,10 @@
/**
* {@inheritDoc}
*/
- public void unsetSession() {
+ public final void unsetSession() {
session = null;
readOnly = false;
+ readOnlyBeforeAttachedToSession = null;
}
/**
@@ -236,43 +247,90 @@
/**
* {@inheritDoc}
*/
- public boolean isReadOnly() {
- errorIfReadOnlySettingNotAvailable();
- if ( !isConnectedToSession() ) {
+ public final boolean isReadOnlySettingAvailable() {
+ return ( session != null && ! session.isClosed() );
+ }
+
+ private void errorIfReadOnlySettingNotAvailable() {
+ if ( session == null ) {
throw new TransientObjectException(
- "The read-only/modifiable setting is only accessible when the proxy is associated with a session." );
+ "Proxy is detached (i.e, session is null). The read-only/modifiable setting is only accessible when the proxy is associated with an open session." );
}
+ if ( session.isClosed() ) {
+ throw new SessionException(
+ "Session is closed. The read-only/modifiable setting is only accessible when the proxy is associated with an open session." );
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public final boolean isReadOnly() {
+ errorIfReadOnlySettingNotAvailable();
return readOnly;
}
/**
* {@inheritDoc}
*/
- public void setReadOnly(boolean readOnly) {
+ public final void setReadOnly(boolean readOnly) {
errorIfReadOnlySettingNotAvailable();
// only update if readOnly is different from current setting
if ( this.readOnly != readOnly ) {
- Object proxy = getProxyOrNull();
- if ( proxy == null ) {
- throw new TransientObjectException(
- "Cannot set the read-only/modifiable mode unless the proxy is associated with a session." );
+ final EntityPersister persister = session.getFactory().getEntityPersister( entityName );
+ if ( ! persister.isMutable() && ! readOnly ) {
+ throw new IllegalStateException( "cannot make proxies for immutable entities modifiable");
}
this.readOnly = readOnly;
if ( initialized ) {
- session.getPersistenceContext().setReadOnly( target, readOnly );
+ EntityKey key = generateEntityKeyOrNull( getIdentifier(), session, getEntityName() );
+ if ( key != null && session.getPersistenceContext().containsEntity( key ) ) {
+ session.getPersistenceContext().setReadOnly( target, readOnly );
+ }
}
}
}
- private void errorIfReadOnlySettingNotAvailable() {
- if ( session == null ) {
- throw new TransientObjectException(
- "Proxy is detached (i.e, session is null). The read-only/modifiable setting is only accessible when the proxy is associated with an open session." );
+ /**
+ * Get the read-only/modifiable setting that should be put in affect when it is
+ * attached to a session.
+ *
+ * This method should only be called during serialization when read-only/modifiable setting
+ * is not available (i.e., isReadOnlySettingAvailable() == false)
+ *
+ * @returns, null, if the default setting should be used;
+ * true, for read-only;
+ * false, for modifiable
+ * @throws IllegalStateException if isReadOnlySettingAvailable() == true
+ */
+ protected final Boolean isReadOnlyBeforeAttachedToSession() {
+ if ( isReadOnlySettingAvailable() ) {
+ throw new IllegalStateException(
+ "Cannot call isReadOnlyBeforeAttachedToSession when isReadOnlySettingAvailable == true"
+ );
}
- if ( session.isClosed() ) {
- throw new SessionException(
- "Session is closed. The read-only/modifiable setting is only accessible when the proxy is associated with an open session." );
+ return readOnlyBeforeAttachedToSession;
+ }
+
+ /**
+ * Set the read-only/modifiable setting that should be put in affect when it is
+ * attached to a session.
+ *
+ * This method should only be called during deserialization, before associating
+ * the proxy with a session.
+ *
+ * @param readOnlyBeforeAttachedToSession, the read-only/modifiable setting to use when
+ * associated with a session; null indicates that the default should be used.
+ * @throws IllegalStateException if isReadOnlySettingAvailable() == true
+ */
+ /* package-private */
+ final void setReadOnlyBeforeAttachedToSession(Boolean readOnlyBeforeAttachedToSession) {
+ if ( isReadOnlySettingAvailable() ) {
+ throw new IllegalStateException(
+ "Cannot call setReadOnlyBeforeAttachedToSession when isReadOnlySettingAvailable == true"
+ );
}
+ this.readOnlyBeforeAttachedToSession = readOnlyBeforeAttachedToSession;
}
/**
Added: core/trunk/core/src/main/java/org/hibernate/proxy/AbstractSerializableProxy.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/proxy/AbstractSerializableProxy.java (rev 0)
+++ core/trunk/core/src/main/java/org/hibernate/proxy/AbstractSerializableProxy.java 2010-02-05 04:00:04 UTC (rev 18699)
@@ -0,0 +1,72 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2010, 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.proxy;
+
+import java.io.Serializable;
+
+/**
+ * Convenience base class for SerializableProxy.
+ *
+ * @author Gail Badner
+ */
+public abstract class AbstractSerializableProxy implements Serializable {
+ private String entityName;
+ private Serializable id;
+ private Boolean readOnly;
+
+ /**
+ * For serialization
+ */
+ protected AbstractSerializableProxy() {
+ }
+
+ protected AbstractSerializableProxy(String entityName, Serializable id, Boolean readOnly) {
+ this.entityName = entityName;
+ this.id = id;
+ this.readOnly = readOnly;
+ }
+
+ protected String getEntityName() {
+ return entityName;
+ }
+
+ protected Serializable getId() {
+ return id;
+ }
+
+ /**
+ * Set the read-only/modifiable setting from this object in an AbstractLazyInitializer.
+ *
+ * This method should only be called during deserialization, before associating the
+ * AbstractLazyInitializer with a session.
+ *
+ * @param li, the read-only/modifiable setting to use when
+ * associated with a session; null indicates that the default should be used.
+ * @throws IllegalStateException if isReadOnlySettingAvailable() == true
+ */
+ protected void setReadOnlyBeforeAttachedToSession(AbstractLazyInitializer li) {
+ li.setReadOnlyBeforeAttachedToSession( readOnly );
+ }
+}
Modified: core/trunk/core/src/main/java/org/hibernate/proxy/LazyInitializer.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/proxy/LazyInitializer.java 2010-02-05 02:42:55 UTC (rev 18698)
+++ core/trunk/core/src/main/java/org/hibernate/proxy/LazyInitializer.java 2010-02-05 04:00:04 UTC (rev 18699)
@@ -105,10 +105,23 @@
public void setImplementation(Object target);
/**
+ * Is the proxy's read-only/modifiable setting available?
+ * @return true, if the setting is available
+ * false, if the proxy is detached or its associated session is closed
+ */
+ public boolean isReadOnlySettingAvailable();
+
+ /**
* Is the proxy read-only?.
*
+ * The read-only/modifiable setting is not available when the proxy is
+ * detached or its associated session is closed.
+ *
+ * To check if the read-only/modifiable setting is available:
+ * @see org.hibernate.proxy.LazyInitializer#isReadOnlySettingAvailable()
+ *
* @return true, if this proxy is read-only; false, otherwise
- * @throws org.hibernate.TransientObjectException if the proxy is not association with a session
+ * @throws org.hibernate.TransientObjectException if the proxy is detached (getSession() == null)
* @throws org.hibernate.SessionException if the proxy is associated with a sesssion that is closed
*
* @see org.hibernate.Session#isReadOnly(Object entityOrProxy)
Modified: core/trunk/core/src/main/java/org/hibernate/proxy/pojo/cglib/CGLIBLazyInitializer.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/proxy/pojo/cglib/CGLIBLazyInitializer.java 2010-02-05 02:42:55 UTC (rev 18698)
+++ core/trunk/core/src/main/java/org/hibernate/proxy/pojo/cglib/CGLIBLazyInitializer.java 2010-02-05 04:00:04 UTC (rev 18699)
@@ -212,11 +212,10 @@
persistentClass,
interfaces,
getIdentifier(),
- ( getSession() != null && getSession().isOpen() ? isReadOnly() : false ),
+ ( isReadOnlySettingAvailable() ? Boolean.valueOf( isReadOnly() ) : isReadOnlyBeforeAttachedToSession() ),
getIdentifierMethod,
setIdentifierMethod,
componentIdType
);
}
-
}
Modified: core/trunk/core/src/main/java/org/hibernate/proxy/pojo/cglib/SerializableProxy.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/proxy/pojo/cglib/SerializableProxy.java 2010-02-05 02:42:55 UTC (rev 18698)
+++ core/trunk/core/src/main/java/org/hibernate/proxy/pojo/cglib/SerializableProxy.java 2010-02-05 04:00:04 UTC (rev 18699)
@@ -28,19 +28,17 @@
import java.lang.reflect.Method;
import org.hibernate.HibernateException;
+import org.hibernate.proxy.AbstractSerializableProxy;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.type.AbstractComponentType;
/**
* Serializable placeholder for <tt>CGLIB</tt> proxies
*/
-public final class SerializableProxy implements Serializable {
+public final class SerializableProxy extends AbstractSerializableProxy {
- private String entityName;
private Class persistentClass;
private Class[] interfaces;
- private Serializable id;
- private boolean readOnly;
private Class getIdentifierMethodClass;
private Class setIdentifierMethodClass;
private String getIdentifierMethodName;
@@ -55,16 +53,14 @@
final Class persistentClass,
final Class[] interfaces,
final Serializable id,
- final boolean readOnly,
+ final Boolean readOnly,
final Method getIdentifierMethod,
final Method setIdentifierMethod,
AbstractComponentType componentIdType
) {
- this.entityName = entityName;
+ super( entityName, id, readOnly );
this.persistentClass = persistentClass;
this.interfaces = interfaces;
- this.id = id;
- this.readOnly = readOnly;
if (getIdentifierMethod!=null) {
getIdentifierMethodClass = getIdentifierMethod.getDeclaringClass();
getIdentifierMethodName = getIdentifierMethod.getName();
@@ -79,8 +75,8 @@
private Object readResolve() {
try {
- return CGLIBLazyInitializer.getProxy(
- entityName,
+ HibernateProxy proxy = CGLIBLazyInitializer.getProxy(
+ getEntityName(),
persistentClass,
interfaces,
getIdentifierMethodName==null ?
@@ -90,12 +86,15 @@
null :
setIdentifierMethodClass.getDeclaredMethod(setIdentifierMethodName, setIdentifierMethodParams),
componentIdType,
- id,
+ getId(),
null
);
+
+ setReadOnlyBeforeAttachedToSession( ( CGLIBLazyInitializer ) proxy.getHibernateLazyInitializer() );
+ return proxy;
}
catch (NoSuchMethodException nsme) {
- throw new HibernateException("could not create proxy for entity: " + entityName, nsme);
+ throw new HibernateException("could not create proxy for entity: " + getEntityName(), nsme);
}
}
Modified: core/trunk/core/src/main/java/org/hibernate/proxy/pojo/javassist/JavassistLazyInitializer.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/proxy/pojo/javassist/JavassistLazyInitializer.java 2010-02-05 02:42:55 UTC (rev 18698)
+++ core/trunk/core/src/main/java/org/hibernate/proxy/pojo/javassist/JavassistLazyInitializer.java 2010-02-05 04:00:04 UTC (rev 18699)
@@ -34,6 +34,7 @@
import javassist.util.proxy.ProxyObject;
import org.slf4j.LoggerFactory;
+
import org.hibernate.HibernateException;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.proxy.pojo.BasicLazyInitializer;
@@ -229,7 +230,7 @@
persistentClass,
interfaces,
getIdentifier(),
- ( getSession() != null && getSession().isOpen() ? isReadOnly() : false ),
+ ( isReadOnlySettingAvailable() ? Boolean.valueOf( isReadOnly() ) : isReadOnlyBeforeAttachedToSession() ),
getIdentifierMethod,
setIdentifierMethod,
componentIdType
Modified: core/trunk/core/src/main/java/org/hibernate/proxy/pojo/javassist/SerializableProxy.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/proxy/pojo/javassist/SerializableProxy.java 2010-02-05 02:42:55 UTC (rev 18698)
+++ core/trunk/core/src/main/java/org/hibernate/proxy/pojo/javassist/SerializableProxy.java 2010-02-05 04:00:04 UTC (rev 18699)
@@ -28,19 +28,17 @@
import java.lang.reflect.Method;
import org.hibernate.HibernateException;
+import org.hibernate.proxy.AbstractSerializableProxy;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.type.AbstractComponentType;
/**
* Serializable placeholder for Javassist proxies
*/
-public final class SerializableProxy implements Serializable {
+public final class SerializableProxy extends AbstractSerializableProxy {
- private String entityName;
private Class persistentClass;
private Class[] interfaces;
- private Serializable id;
- private boolean readOnly;
private Class getIdentifierMethodClass;
private Class setIdentifierMethodClass;
private String getIdentifierMethodName;
@@ -55,16 +53,14 @@
final Class persistentClass,
final Class[] interfaces,
final Serializable id,
- final boolean readOnly,
+ final Boolean readOnly,
final Method getIdentifierMethod,
final Method setIdentifierMethod,
AbstractComponentType componentIdType
) {
- this.entityName = entityName;
+ super( entityName, id, readOnly );
this.persistentClass = persistentClass;
this.interfaces = interfaces;
- this.id = id;
- this.readOnly = readOnly;
if (getIdentifierMethod!=null) {
getIdentifierMethodClass = getIdentifierMethod.getDeclaringClass();
getIdentifierMethodName = getIdentifierMethod.getName();
@@ -79,8 +75,8 @@
private Object readResolve() {
try {
- return JavassistLazyInitializer.getProxy(
- entityName,
+ HibernateProxy proxy = JavassistLazyInitializer.getProxy(
+ getEntityName(),
persistentClass,
interfaces,
getIdentifierMethodName==null ?
@@ -90,13 +86,14 @@
null :
setIdentifierMethodClass.getDeclaredMethod(setIdentifierMethodName, setIdentifierMethodParams),
componentIdType,
- id,
+ getId(),
null
);
+ setReadOnlyBeforeAttachedToSession( ( JavassistLazyInitializer ) proxy.getHibernateLazyInitializer() );
+ return proxy;
}
catch (NoSuchMethodException nsme) {
- throw new HibernateException("could not create proxy for entity: " + entityName, nsme);
+ throw new HibernateException("could not create proxy for entity: " + getEntityName(), nsme);
}
}
-
}
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/nonflushedchanges/GetLoadTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/nonflushedchanges/GetLoadTest.java 2010-02-05 02:42:55 UTC (rev 18698)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/nonflushedchanges/GetLoadTest.java 2010-02-05 04:00:04 UTC (rev 18699)
@@ -185,7 +185,7 @@
SimpleJtaTransactionManagerImpl.getInstance().commit();
}
- public void testLoadReadOnlyFailureExpected() throws Exception {
+ public void testLoadReadOnly() throws Exception {
clearCounts();
SimpleJtaTransactionManagerImpl.getInstance().begin();
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/proxy/ProxyTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/proxy/ProxyTest.java 2010-02-05 02:42:55 UTC (rev 18698)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/proxy/ProxyTest.java 2010-02-05 04:00:04 UTC (rev 18699)
@@ -123,6 +123,31 @@
s.close();
}
+ public void testInitializedProxySerializationAfterSessionClosed() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ DataPoint dp = new DataPoint();
+ dp.setDescription("a data point");
+ dp.setX( new BigDecimal(1.0) );
+ dp.setY( new BigDecimal(2.0) );
+ s.persist(dp);
+ s.flush();
+ s.clear();
+
+ dp = (DataPoint) s.load( DataPoint.class, new Long( dp.getId() ) );
+ assertFalse( Hibernate.isInitialized(dp) );
+ Hibernate.initialize( dp );
+ assertTrue( Hibernate.isInitialized(dp) );
+ s.close();
+ SerializationHelper.clone( dp );
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.delete( dp );
+ t.commit();
+ s.close();
+ }
+
public void testProxySerialization() {
Session s = openSession();
Transaction t = s.beginTransaction();
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlyProxyTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlyProxyTest.java 2010-02-05 02:42:55 UTC (rev 18698)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlyProxyTest.java 2010-02-05 04:00:04 UTC (rev 18699)
@@ -1328,6 +1328,7 @@
}
catch ( SessionException ex) {
// expected
+ assertFalse( ( ( HibernateProxy ) dp ).getHibernateLazyInitializer().isReadOnlySettingAvailable() );
}
finally {
s = openSession();
@@ -1360,6 +1361,7 @@
}
catch ( TransientObjectException ex) {
// expected
+ assertFalse( ( ( HibernateProxy ) dp ).getHibernateLazyInitializer().isReadOnlySettingAvailable() );
}
finally {
s = openSession();
@@ -1393,6 +1395,7 @@
}
catch ( TransientObjectException ex) {
// expected
+ assertFalse( ( ( HibernateProxy ) dp ).getHibernateLazyInitializer().isReadOnlySettingAvailable() );
}
finally {
s.delete( dp );
@@ -1421,6 +1424,7 @@
}
catch ( TransientObjectException ex) {
// expected
+ assertFalse( ( ( HibernateProxy ) dp ).getHibernateLazyInitializer().isReadOnlySettingAvailable() );
}
finally {
s.beginTransaction();
@@ -1450,6 +1454,7 @@
}
catch ( SessionException ex) {
// expected
+ assertFalse( ( ( HibernateProxy ) dp ).getHibernateLazyInitializer().isReadOnlySettingAvailable() );
}
finally {
s = openSession();
@@ -1482,6 +1487,7 @@
}
catch ( TransientObjectException ex) {
// expected
+ assertFalse( ( ( HibernateProxy ) dp ).getHibernateLazyInitializer().isReadOnlySettingAvailable() );
}
finally {
s = openSession();
@@ -1492,7 +1498,40 @@
}
}
+ public void testSetClosedSessionInLazyInitializer() {
+ DataPoint dpOrig = createDataPoint( CacheMode.IGNORE );
+ Session s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+
+ s.beginTransaction();
+ DataPoint dp = ( DataPoint ) s.load( DataPoint.class, new Long( dpOrig.getId() ) );
+ assertTrue( dp instanceof HibernateProxy );
+ assertFalse( Hibernate.isInitialized( dp ) );
+ checkReadOnly( s, dp, false );
+ s.getTransaction().commit();
+ assertTrue( s.contains( dp ) );
+ s.close();
+
+ assertNull( ( ( HibernateProxy ) dp ).getHibernateLazyInitializer().getSession() );
+ assertTrue( ( ( SessionImplementor ) s ).isClosed() );
+ try {
+ ( ( HibernateProxy ) dp ).getHibernateLazyInitializer().setSession( ( SessionImplementor ) s );
+ fail( "should have failed because session was closed" );
+ }
+ catch ( SessionException ex) {
+ // expected
+ assertFalse( ( ( HibernateProxy ) dp ).getHibernateLazyInitializer().isReadOnlySettingAvailable() );
+ }
+ finally {
+ s = openSession();
+ s.beginTransaction();
+ s.delete( dp );
+ s.getTransaction().commit();
+ s.close();
+ }
+ }
+
public void testDetachedSetReadOnlyAfterEvictViaSession() {
DataPoint dpOrig = createDataPoint( CacheMode.IGNORE );
@@ -1515,6 +1554,7 @@
}
catch ( TransientObjectException ex) {
// expected
+ assertFalse( ( ( HibernateProxy ) dp ).getHibernateLazyInitializer().isReadOnlySettingAvailable() );
}
finally {
s.delete( dp );
@@ -1543,6 +1583,7 @@
}
catch ( TransientObjectException ex) {
// expected
+ assertFalse( ( ( HibernateProxy ) dp ).getHibernateLazyInitializer().isReadOnlySettingAvailable() );
}
finally {
s.beginTransaction();
[View Less]
15 years, 1 month
Hibernate SVN: r18698 - in core/trunk: annotations/src/test/java/org/hibernate/test/annotations/embedded/one2many and 3 other directories.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2010-02-04 21:42:55 -0500 (Thu, 04 Feb 2010)
New Revision: 18698
Modified:
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/a/Dependent.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/a/DependentId.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/a/DerivedIdentitySimpleParentIdClassDepTest.java
core/trunk/…
[View More]annotations/src/test/java/org/hibernate/test/annotations/embedded/one2many/EmbeddableWithOne2ManyTest.java
core/trunk/core/src/main/java/org/hibernate/event/def/AbstractSaveEventListener.java
core/trunk/core/src/main/java/org/hibernate/id/ForeignGenerator.java
core/trunk/core/src/main/java/org/hibernate/tuple/entity/AbstractEntityTuplizer.java
Log:
HHH-4848 - Derived identities: Derived entities using @IdClass and mapping a @XToOne are not supported
Modified: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/a/Dependent.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/a/Dependent.java 2010-02-04 21:05:38 UTC (rev 18697)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/a/Dependent.java 2010-02-05 02:42:55 UTC (rev 18698)
@@ -19,4 +19,12 @@
@Id
@ManyToOne
Employee emp;
+
+ public Dependent() {
+ }
+
+ public Dependent(String name, Employee emp) {
+ this.name = name;
+ this.emp = emp;
+ }
}
Modified: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/a/DependentId.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/a/DependentId.java 2010-02-04 21:05:38 UTC (rev 18697)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/a/DependentId.java 2010-02-05 02:42:55 UTC (rev 18698)
@@ -8,4 +8,12 @@
public class DependentId implements Serializable {
String name;
long emp; // corresponds to PK type of Employee
+
+ public DependentId() {
+ }
+
+ public DependentId(String name, long emp) {
+ this.name = name;
+ this.emp = emp;
+ }
}
\ No newline at end of file
Modified: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/a/DerivedIdentitySimpleParentIdClassDepTest.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/a/DerivedIdentitySimpleParentIdClassDepTest.java 2010-02-04 21:05:38 UTC (rev 18697)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/a/DerivedIdentitySimpleParentIdClassDepTest.java 2010-02-05 02:42:55 UTC (rev 18698)
@@ -11,32 +11,35 @@
public class
DerivedIdentitySimpleParentIdClassDepTest extends TestCase {
- @FailureExpected( jiraKey = "HHH-4848" )
public void testManyToOne() throws Exception {
assertTrue( SchemaUtil.isColumnPresent( "Dependent", "emp_empId", getCfg() ) );
assertTrue( ! SchemaUtil.isColumnPresent( "Dependent", "emp", getCfg() ) );
+
+ Session s = openSession();
+ s.getTransaction().begin();
Employee e = new Employee();
e.empId = 1;
e.empName = "Emmanuel";
e.nickname = "Manu";
- Session s = openSession( );
- s.getTransaction().begin();
s.persist( e );
Dependent d = new Dependent();
d.emp = e;
d.name = "Doggy";
d.emp = e;
s.persist( d );
- s.flush();
- s.clear();
- DependentId dId = new DependentId();
- dId.name = d.name;
- dId.emp = d.emp.empId;
+ s.getTransaction().commit();
+ s.close();
+
+ s = openSession();
+ s.getTransaction().begin();
+ DependentId dId = new DependentId( d.name, d.emp.empId );
d = (Dependent) s.get( Dependent.class, dId );
assertEquals( e.empId, d.emp.empId );
assertEquals( e.empName, d.emp.empName );
assertEquals( e.nickname, d.emp.nickname );
- s.getTransaction().rollback();
+ s.delete( d );
+ s.delete( d.emp );
+ s.getTransaction().commit();
s.close();
}
Modified: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/one2many/EmbeddableWithOne2ManyTest.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/one2many/EmbeddableWithOne2ManyTest.java 2010-02-04 21:05:38 UTC (rev 18697)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/one2many/EmbeddableWithOne2ManyTest.java 2010-02-05 02:42:55 UTC (rev 18698)
@@ -37,7 +37,8 @@
public class EmbeddableWithOne2ManyTest extends TestCase {
@Override
protected Class<?>[] getAnnotatedClasses() {
- return new Class[] { Alias.class, Person.class };
+// return new Class[] { Alias.class, Person.class };
+ return new Class[] { };
}
@FailureExpected( jiraKey = "HHH-4883")
Modified: core/trunk/core/src/main/java/org/hibernate/event/def/AbstractSaveEventListener.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/event/def/AbstractSaveEventListener.java 2010-02-04 21:05:38 UTC (rev 18697)
+++ core/trunk/core/src/main/java/org/hibernate/event/def/AbstractSaveEventListener.java 2010-02-05 02:42:55 UTC (rev 18698)
@@ -320,11 +320,8 @@
log.debug( "executing identity-insert immediately" );
source.getActionQueue().execute( insert );
id = insert.getGeneratedId();
- //now done in EntityIdentityInsertAction
- //persister.setIdentifier( entity, id, source.getEntityMode() );
key = new EntityKey( id, persister, source.getEntityMode() );
source.getPersistenceContext().checkUniqueness( key, entity );
- //source.getBatcher().executeBatch(); //found another way to ensure that all batched joined inserts have been executed
}
else {
log.debug( "delaying identity-insert due to no transaction in progress" );
Modified: core/trunk/core/src/main/java/org/hibernate/id/ForeignGenerator.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/id/ForeignGenerator.java 2010-02-04 21:05:38 UTC (rev 18697)
+++ core/trunk/core/src/main/java/org/hibernate/id/ForeignGenerator.java 2010-02-05 02:42:55 UTC (rev 18698)
@@ -33,7 +33,7 @@
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.ForeignKeys;
import org.hibernate.engine.SessionImplementor;
-import org.hibernate.metadata.ClassMetadata;
+import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.type.EntityType;
import org.hibernate.type.Type;
@@ -96,37 +96,35 @@
public Serializable generate(SessionImplementor sessionImplementor, Object object) {
Session session = ( Session ) sessionImplementor;
- final ClassMetadata classMetadata = sessionImplementor.getFactory()
- .getClassMetadata( entityName );
- Object associatedObject = classMetadata
- .getPropertyValue( object, propertyName, session.getEntityMode() );
+ final EntityPersister persister = sessionImplementor.getFactory().getEntityPersister( entityName );
+ Object associatedObject = persister.getPropertyValue( object, propertyName, session.getEntityMode() );
if ( associatedObject == null ) {
throw new IdentifierGenerationException(
"attempted to assign id from null one-to-one property [" + getRole() + "]"
);
}
- final Type uncheckedType = classMetadata
- .getPropertyType( propertyName );
- EntityType type;
- if (uncheckedType instanceof EntityType) {
- type = (EntityType) uncheckedType;
+ final EntityType foreignValueSourceType;
+ final Type propertyType = persister.getPropertyType( propertyName );
+ if ( propertyType.isEntityType() ) {
+ // the normal case
+ foreignValueSourceType = (EntityType) propertyType;
}
else {
- //try identifier mapper
- type = (EntityType) classMetadata.getPropertyType( "_identifierMapper." + propertyName );
+ // try identifier mapper
+ foreignValueSourceType = (EntityType) persister.getPropertyType( "_identifierMapper." + propertyName );
}
Serializable id;
try {
id = ForeignKeys.getEntityIdentifierIfNotUnsaved(
- type.getAssociatedEntityName(),
+ foreignValueSourceType.getAssociatedEntityName(),
associatedObject,
sessionImplementor
);
}
catch (TransientObjectException toe) {
- id = session.save( type.getAssociatedEntityName(), associatedObject );
+ id = session.save( foreignValueSourceType.getAssociatedEntityName(), associatedObject );
}
if ( session.contains(object) ) {
Modified: core/trunk/core/src/main/java/org/hibernate/tuple/entity/AbstractEntityTuplizer.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/tuple/entity/AbstractEntityTuplizer.java 2010-02-04 21:05:38 UTC (rev 18697)
+++ core/trunk/core/src/main/java/org/hibernate/tuple/entity/AbstractEntityTuplizer.java 2010-02-05 02:42:55 UTC (rev 18698)
@@ -28,13 +28,10 @@
import java.util.Map;
import java.util.Set;
+import org.hibernate.EntityMode;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
-import org.hibernate.PropertyAccessException;
-import org.hibernate.persister.entity.EntityPersister;
-import org.hibernate.tuple.Instantiator;
-import org.hibernate.tuple.VersionProperty;
-import org.hibernate.tuple.StandardProperty;
+import org.hibernate.engine.EntityKey;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.id.Assigned;
@@ -42,9 +39,13 @@
import org.hibernate.mapping.Component;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property;
+import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.property.Getter;
import org.hibernate.property.Setter;
import org.hibernate.proxy.ProxyFactory;
+import org.hibernate.tuple.Instantiator;
+import org.hibernate.tuple.StandardProperty;
+import org.hibernate.tuple.VersionProperty;
import org.hibernate.type.AbstractComponentType;
import org.hibernate.type.ComponentType;
import org.hibernate.type.EntityType;
@@ -165,7 +166,17 @@
}
Component mapper = mappingInfo.getIdentifierMapper();
- identifierMapperType = mapper==null ? null : (AbstractComponentType) mapper.getType();
+ if ( mapper == null ) {
+ identifierMapperType = null;
+ mappedIdentifierValueMarshaller = null;
+ }
+ else {
+ identifierMapperType = (AbstractComponentType) mapper.getType();
+ mappedIdentifierValueMarshaller = buildMappedIdentifierValueMarshaller(
+ (ComponentType) entityMetamodel.getIdentifierProperty().getType(),
+ (ComponentType) identifierMapperType
+ );
+ }
}
/** Retreives the defined entity-name for the tuplized entity.
@@ -197,23 +208,7 @@
throw new HibernateException( "The class has no identifier property: " + getEntityName() );
}
else {
- ComponentType copier = (ComponentType) entityMetamodel.getIdentifierProperty().getType();
- id = copier.instantiate( getEntityMode() );
- final Object[] propertyValues = identifierMapperType.getPropertyValues( entity, getEntityMode() );
- Type[] subTypes = identifierMapperType.getSubtypes();
- Type[] copierSubTypes = copier.getSubtypes();
- final int length = subTypes.length;
- for ( int i = 0 ; i < length; i++ ) {
- //JPA 2 in @IdClass points to the pk of the entity
- if ( subTypes[i].isAssociationType() && ! copierSubTypes[i].isAssociationType()) {
- final String associatedEntityName = ( ( EntityType ) subTypes[i] ).getAssociatedEntityName();
- final EntityPersister entityPersister = getFactory().getEntityPersister(
- associatedEntityName
- );
- propertyValues[i] = entityPersister.getIdentifier( propertyValues[i], getEntityMode() );
- }
- }
- copier.setPropertyValues( id, propertyValues, getEntityMode() );
+ id = mappedIdentifierValueMarshaller.getIdentifier( entity, getEntityMode(), getFactory() );
}
}
else {
@@ -245,6 +240,7 @@
setIdentifier( entity, id, null );
}
+
/**
* {@inheritDoc}
*/
@@ -259,21 +255,141 @@
idSetter.set( entity, id, getFactory() );
}
else if ( identifierMapperType != null ) {
- ComponentType extractor = (ComponentType) entityMetamodel.getIdentifierProperty().getType();
- ComponentType copier = (ComponentType) identifierMapperType;
- final Object[] propertyValues = extractor.getPropertyValues( id, getEntityMode() );
- Type[] subTypes = identifierMapperType.getSubtypes();
- Type[] copierSubTypes = copier.getSubtypes();
+ mappedIdentifierValueMarshaller.setIdentifier( entity, id, session );
+ }
+ }
+
+ private static interface MappedIdentifierValueMarshaller {
+ public Object getIdentifier(Object entity, EntityMode entityMode, SessionFactoryImplementor factory);
+ public void setIdentifier(Object entity, Serializable id, SessionImplementor session);
+ }
+
+ private final MappedIdentifierValueMarshaller mappedIdentifierValueMarshaller;
+
+ private static MappedIdentifierValueMarshaller buildMappedIdentifierValueMarshaller(
+ ComponentType mappedIdClassComponentType,
+ ComponentType virtualIdComponent) {
+ // so basically at this point we know we have a "mapped" composite identifier
+ // which is an awful way to say that the identifier is represented differently
+ // in the entity and in the identifier value. The incoming value should
+ // be an instance of the mapped identifier class (@IdClass) while the incoming entity
+ // should be an instance of the entity class as defined by metamodel.
+ //
+ // However, even within that we have 2 potential scenarios:
+ // 1) @IdClass types and entity @Id property types match
+ // - return a NormalMappedIdentifierValueMarshaller
+ // 2) They do not match
+ // - return a IncrediblySillyJpaMapsIdMappedIdentifierValueMarshaller
+ boolean wereAllEquivalent = true;
+ // the sizes being off is a much bigger problem that should have been caught already...
+ for ( int i = 0; i < virtualIdComponent.getSubtypes().length; i++ ) {
+ if ( virtualIdComponent.getSubtypes()[i].isEntityType()
+ && ! mappedIdClassComponentType.getSubtypes()[i].isEntityType() ) {
+ wereAllEquivalent = false;
+ break;
+ }
+ }
+
+ return wereAllEquivalent
+ ? (MappedIdentifierValueMarshaller) new NormalMappedIdentifierValueMarshaller( virtualIdComponent, mappedIdClassComponentType )
+ : (MappedIdentifierValueMarshaller) new IncrediblySillyJpaMapsIdMappedIdentifierValueMarshaller( virtualIdComponent, mappedIdClassComponentType );
+ }
+
+ private static class NormalMappedIdentifierValueMarshaller implements MappedIdentifierValueMarshaller {
+ private final ComponentType virtualIdComponent;
+ private final ComponentType mappedIdentifierType;
+
+ private NormalMappedIdentifierValueMarshaller(ComponentType virtualIdComponent, ComponentType mappedIdentifierType) {
+ this.virtualIdComponent = virtualIdComponent;
+ this.mappedIdentifierType = mappedIdentifierType;
+ }
+
+ public Object getIdentifier(Object entity, EntityMode entityMode, SessionFactoryImplementor factory) {
+ Object id = mappedIdentifierType.instantiate( entityMode );
+ final Object[] propertyValues = virtualIdComponent.getPropertyValues( entity, entityMode );
+ Type[] subTypes = virtualIdComponent.getSubtypes();
+ Type[] copierSubTypes = mappedIdentifierType.getSubtypes();
final int length = subTypes.length;
for ( int i = 0 ; i < length; i++ ) {
//JPA 2 in @IdClass points to the pk of the entity
+ if ( subTypes[i].isAssociationType() && ! copierSubTypes[i].isAssociationType()) {
+ final String associatedEntityName = ( ( EntityType ) subTypes[i] ).getAssociatedEntityName();
+ final EntityPersister entityPersister = factory.getEntityPersister( associatedEntityName );
+ propertyValues[i] = entityPersister.getIdentifier( propertyValues[i], entityMode );
+ }
+ }
+ mappedIdentifierType.setPropertyValues( id, propertyValues, entityMode );
+ return id;
+ }
+
+ public void setIdentifier(Object entity, Serializable id, SessionImplementor session) {
+ virtualIdComponent.setPropertyValues(
+ entity,
+ mappedIdentifierType.getPropertyValues( id, session ),
+ session.getEntityMode()
+ );
+ }
+ }
+
+ private static class IncrediblySillyJpaMapsIdMappedIdentifierValueMarshaller implements MappedIdentifierValueMarshaller {
+ private final ComponentType virtualIdComponent;
+ private final ComponentType mappedIdentifierType;
+
+ private IncrediblySillyJpaMapsIdMappedIdentifierValueMarshaller(ComponentType virtualIdComponent, ComponentType mappedIdentifierType) {
+ this.virtualIdComponent = virtualIdComponent;
+ this.mappedIdentifierType = mappedIdentifierType;
+ }
+
+ public Object getIdentifier(Object entity, EntityMode entityMode, SessionFactoryImplementor factory) {
+ Object id = mappedIdentifierType.instantiate( entityMode );
+ final Object[] propertyValues = virtualIdComponent.getPropertyValues( entity, entityMode );
+ Type[] subTypes = virtualIdComponent.getSubtypes();
+ Type[] copierSubTypes = mappedIdentifierType.getSubtypes();
+ final int length = subTypes.length;
+ for ( int i = 0 ; i < length; i++ ) {
+ if ( propertyValues[i] == null ) {
+ continue;
+ }
+ //JPA 2 in @IdClass points to the pk of the entity
if ( subTypes[i].isAssociationType() && ! copierSubTypes[i].isAssociationType() ) {
final String associatedEntityName = ( ( EntityType ) subTypes[i] ).getAssociatedEntityName();
- //FIXME find the entity for the given id (propertyValue[i])
+ final EntityPersister entityPersister = factory.getEntityPersister( associatedEntityName );
+ propertyValues[i] = entityPersister.getIdentifier( propertyValues[i], entityMode );
}
}
- copier.setPropertyValues( entity, propertyValues, getEntityMode() );
+ mappedIdentifierType.setPropertyValues( id, propertyValues, entityMode );
+ return id;
}
+
+ public void setIdentifier(Object entity, Serializable id, SessionImplementor session) {
+ final Object[] extractedValues = mappedIdentifierType.getPropertyValues( id, session.getEntityMode() );
+ final Object[] injectionValues = new Object[ extractedValues.length ];
+ for ( int i = 0; i < virtualIdComponent.getSubtypes().length; i++ ) {
+ final Type virtualPropertyType = virtualIdComponent.getSubtypes()[i];
+ final Type idClassPropertyType = mappedIdentifierType.getSubtypes()[i];
+ if ( virtualPropertyType.isEntityType() && ! idClassPropertyType.isEntityType() ) {
+ final String associatedEntityName = ( (EntityType) virtualPropertyType ).getAssociatedEntityName();
+ final EntityKey entityKey = new EntityKey(
+ (Serializable) extractedValues[i],
+ session.getFactory().getEntityPersister( associatedEntityName ),
+ session.getEntityMode()
+ );
+ // it is conceivable there is a proxy, so check that first
+ Object association = session.getPersistenceContext()
+ .getProxy( entityKey );
+ if ( association == null ) {
+ // otherwise look for an initialized version
+ association = session.getPersistenceContext()
+ .getEntity( entityKey );
+ }
+ injectionValues[i] = association;
+ }
+ else {
+ injectionValues[i] = extractedValues[i];
+ }
+ }
+ virtualIdComponent.setPropertyValues( entity, injectionValues, session.getEntityMode() );
+ }
}
/**
[View Less]
15 years, 1 month
Hibernate SVN: r18697 - in core/trunk: core/src/main/java/org/hibernate/event/def and 6 other directories.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2010-02-04 16:05:38 -0500 (Thu, 04 Feb 2010)
New Revision: 18697
Modified:
core/trunk/core/src/main/java/org/hibernate/action/EntityIdentityInsertAction.java
core/trunk/core/src/main/java/org/hibernate/event/def/AbstractSaveEventListener.java
core/trunk/core/src/main/java/org/hibernate/event/def/DefaultDeleteEventListener.java
core/trunk/core/src/main/java/org/hibernate/event/def/DefaultLoadEventListener.java
core/trunk/core/src/main/java/…
[View More]org/hibernate/event/def/DefaultMergeEventListener.java
core/trunk/core/src/main/java/org/hibernate/event/def/DefaultSaveOrUpdateEventListener.java
core/trunk/core/src/main/java/org/hibernate/event/def/DefaultUpdateEventListener.java
core/trunk/core/src/main/java/org/hibernate/impl/SessionImpl.java
core/trunk/core/src/main/java/org/hibernate/impl/StatelessSessionImpl.java
core/trunk/core/src/main/java/org/hibernate/metadata/ClassMetadata.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/tuple/entity/AbstractEntityTuplizer.java
core/trunk/core/src/main/java/org/hibernate/tuple/entity/EntityTuplizer.java
core/trunk/core/src/main/java/org/hibernate/type/EntityType.java
core/trunk/testsuite/src/test/java/org/hibernate/test/legacy/CustomPersister.java
Log:
HHH-4704 - Pass session into EntityTuplizer#setIdentifier
Modified: core/trunk/core/src/main/java/org/hibernate/action/EntityIdentityInsertAction.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/action/EntityIdentityInsertAction.java 2010-02-04 20:07:08 UTC (rev 18696)
+++ core/trunk/core/src/main/java/org/hibernate/action/EntityIdentityInsertAction.java 2010-02-04 21:05:38 UTC (rev 18697)
@@ -74,7 +74,7 @@
}
//need to do that here rather than in the save event listener to let
//the post insert events to have a id-filled entity when IDENTITY is used (EJB3)
- persister.setIdentifier( instance, generatedId, session.getEntityMode() );
+ persister.setIdentifier( instance, generatedId, session );
}
Modified: core/trunk/core/src/main/java/org/hibernate/event/def/AbstractSaveEventListener.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/event/def/AbstractSaveEventListener.java 2010-02-04 20:07:08 UTC (rev 18696)
+++ core/trunk/core/src/main/java/org/hibernate/event/def/AbstractSaveEventListener.java 2010-02-04 21:05:38 UTC (rev 18697)
@@ -191,7 +191,7 @@
throw new NonUniqueObjectException( id, persister.getEntityName() );
}
}
- persister.setIdentifier( entity, id, source.getEntityMode() );
+ persister.setIdentifier( entity, id, source );
}
else {
key = null;
Modified: core/trunk/core/src/main/java/org/hibernate/event/def/DefaultDeleteEventListener.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/event/def/DefaultDeleteEventListener.java 2010-02-04 20:07:08 UTC (rev 18696)
+++ core/trunk/core/src/main/java/org/hibernate/event/def/DefaultDeleteEventListener.java 2010-02-04 21:05:38 UTC (rev 18697)
@@ -163,7 +163,7 @@
deleteEntity( source, entity, entityEntry, event.isCascadeDeleteEnabled(), persister, transientEntities );
if ( source.getFactory().getSettings().isIdentifierRollbackEnabled() ) {
- persister.resetIdentifier( entity, id, version, source.getEntityMode() );
+ persister.resetIdentifier( entity, id, version, source );
}
}
Modified: core/trunk/core/src/main/java/org/hibernate/event/def/DefaultLoadEventListener.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/event/def/DefaultLoadEventListener.java 2010-02-04 20:07:08 UTC (rev 18696)
+++ core/trunk/core/src/main/java/org/hibernate/event/def/DefaultLoadEventListener.java 2010-02-04 21:05:38 UTC (rev 18697)
@@ -221,7 +221,7 @@
MessageHelper.infoString( persister, event.getEntityId(), event.getSession().getFactory() )
);
}
- persister.setIdentifier( event.getInstanceToLoad(), event.getEntityId(), event.getSession().getEntityMode() );
+ persister.setIdentifier( event.getInstanceToLoad(), event.getEntityId(), event.getSession() );
}
Object entity = doLoad(event, persister, keyToLoad, options);
Modified: core/trunk/core/src/main/java/org/hibernate/event/def/DefaultMergeEventListener.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/event/def/DefaultMergeEventListener.java 2010-02-04 20:07:08 UTC (rev 18696)
+++ core/trunk/core/src/main/java/org/hibernate/event/def/DefaultMergeEventListener.java 2010-02-04 21:05:38 UTC (rev 18697)
@@ -292,10 +292,10 @@
persister.getIdentifier( entity, source.getEntityMode() ) :
null;
if ( copyCache.containsKey( entity ) ) {
- persister.setIdentifier( copyCache.get( entity ), id, source.getEntityMode() );
+ persister.setIdentifier( copyCache.get( entity ), id, source );
}
else {
- ( ( EventCache ) copyCache ).put( entity, persister.instantiate( id, source.getEntityMode() ), true ); //before cascade!
+ ( ( EventCache ) copyCache ).put( entity, persister.instantiate( id, source ), true ); //before cascade!
//TODO: should this be Session.instantiate(Persister, ...)?
}
final Object copy = copyCache.get( entity );
Modified: core/trunk/core/src/main/java/org/hibernate/event/def/DefaultSaveOrUpdateEventListener.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/event/def/DefaultSaveOrUpdateEventListener.java 2010-02-04 20:07:08 UTC (rev 18696)
+++ core/trunk/core/src/main/java/org/hibernate/event/def/DefaultSaveOrUpdateEventListener.java 2010-02-04 21:05:38 UTC (rev 18697)
@@ -239,7 +239,7 @@
event.setRequestedId(
getUpdateId(
- entity, persister, event.getRequestedId(), event.getSession().getEntityMode()
+ entity, persister, event.getRequestedId(), event.getSession()
)
);
@@ -253,7 +253,7 @@
* @param entity The entity.
* @param persister The entity persister
* @param requestedId The requested identifier
- * @param entityMode The entity mode.
+ * @param session The session
*
* @return The id.
*
@@ -263,9 +263,9 @@
Object entity,
EntityPersister persister,
Serializable requestedId,
- EntityMode entityMode) {
+ SessionImplementor session) {
// use the id assigned to the instance
- Serializable id = persister.getIdentifier( entity, entityMode );
+ Serializable id = persister.getIdentifier( entity, session.getEntityMode() );
if ( id == null ) {
// assume this is a newly instantiated transient object
// which should be saved rather than updated
Modified: core/trunk/core/src/main/java/org/hibernate/event/def/DefaultUpdateEventListener.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/event/def/DefaultUpdateEventListener.java 2010-02-04 20:07:08 UTC (rev 18696)
+++ core/trunk/core/src/main/java/org/hibernate/event/def/DefaultUpdateEventListener.java 2010-02-04 21:05:38 UTC (rev 18697)
@@ -30,6 +30,7 @@
import org.hibernate.ObjectDeletedException;
import org.hibernate.EntityMode;
import org.hibernate.engine.EntityEntry;
+import org.hibernate.engine.SessionImplementor;
import org.hibernate.engine.Status;
import org.hibernate.event.SaveOrUpdateEvent;
import org.hibernate.persister.entity.EntityPersister;
@@ -62,14 +63,16 @@
* If the user specified an id, assign it to the instance and use that,
* otherwise use the id already assigned to the instance
*/
- protected Serializable getUpdateId(Object entity, EntityPersister persister, Serializable requestedId, EntityMode entityMode)
- throws HibernateException {
-
- if ( requestedId==null ) {
- return super.getUpdateId(entity, persister, requestedId, entityMode);
+ protected Serializable getUpdateId(
+ Object entity,
+ EntityPersister persister,
+ Serializable requestedId,
+ SessionImplementor session) throws HibernateException {
+ if ( requestedId == null ) {
+ return super.getUpdateId( entity, persister, requestedId, session );
}
else {
- persister.setIdentifier(entity, requestedId, entityMode);
+ persister.setIdentifier( entity, requestedId, session );
return requestedId;
}
}
Modified: core/trunk/core/src/main/java/org/hibernate/impl/SessionImpl.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/impl/SessionImpl.java 2010-02-04 20:07:08 UTC (rev 18696)
+++ core/trunk/core/src/main/java/org/hibernate/impl/SessionImpl.java 2010-02-04 21:05:38 UTC (rev 18697)
@@ -1409,7 +1409,7 @@
checkTransactionSynchStatus();
Object result = interceptor.instantiate( persister.getEntityName(), entityMode, id );
if ( result == null ) {
- result = persister.instantiate( id, entityMode );
+ result = persister.instantiate( id, this );
}
return result;
}
Modified: core/trunk/core/src/main/java/org/hibernate/impl/StatelessSessionImpl.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/impl/StatelessSessionImpl.java 2010-02-04 20:07:08 UTC (rev 18696)
+++ core/trunk/core/src/main/java/org/hibernate/impl/StatelessSessionImpl.java 2010-02-04 21:05:38 UTC (rev 18697)
@@ -114,7 +114,7 @@
else {
persister.insert(id, state, entity, this);
}
- persister.setIdentifier(entity, id, EntityMode.POJO);
+ persister.setIdentifier( entity, id, this );
return id;
}
@@ -253,7 +253,7 @@
Serializable id) throws HibernateException {
errorIfClosed();
return getFactory().getEntityPersister( entityName )
- .instantiate( id, EntityMode.POJO );
+ .instantiate( id, this );
}
public Object internalLoad(
Modified: core/trunk/core/src/main/java/org/hibernate/metadata/ClassMetadata.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/metadata/ClassMetadata.java 2010-02-04 20:07:08 UTC (rev 18696)
+++ core/trunk/core/src/main/java/org/hibernate/metadata/ClassMetadata.java 2010-02-04 21:05:38 UTC (rev 18697)
@@ -152,10 +152,23 @@
/**
* Create a class instance initialized with the given identifier
+ *
+ * @deprecated Use {@link #instantiate(Serializable, SessionImplementor)} instead
+ * @noinspection JavaDoc
*/
public Object instantiate(Serializable id, EntityMode entityMode) throws HibernateException;
/**
+ * Create a class instance initialized with the given identifier
+ *
+ * @param id The identifier value to use (may be null to represent no value)
+ * @param session The session from which the request originated.
+ *
+ * @return The instantiated entity.
+ */
+ public Object instantiate(Serializable id, SessionImplementor session);
+
+ /**
* Get the value of a particular (named) property
*/
public Object getPropertyValue(Object object, String propertyName, EntityMode entityMode) throws HibernateException;
@@ -186,11 +199,30 @@
public Serializable getIdentifier(Object entity, EntityMode entityMode) throws HibernateException;
/**
- * Set the identifier of an instance (or do nothing if no identifier property)
+ * Inject the identifier value into the given entity.
+ * </p>
+ * Has no effect if the entity does not define an identifier property
+ *
+ * @param entity The entity to inject with the identifier value.
+ * @param id The value to be injected as the identifier.
+ * @param entityMode The entity mode
+ *
+ * @deprecated Use {@link #setIdentifier(Object, Serializable, SessionImplementor)} instead.
+ * @noinspection JavaDoc
*/
- public void setIdentifier(Object object, Serializable id, EntityMode entityMode) throws HibernateException;
+ public void setIdentifier(Object entity, Serializable id, EntityMode entityMode) throws HibernateException;
/**
+ * Inject the identifier value into the given entity.
+ *
+ * @param entity The entity to inject with the identifier value.
+ * @param id The value to be injected as the identifier.
+ * @param session The session from which is requests originates
+ */
+ public void setIdentifier(Object entity, Serializable id, SessionImplementor session);
+
+
+ /**
* Does the class implement the <tt>Lifecycle</tt> interface?
*/
public boolean implementsLifecycle(EntityMode entityMode);
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 2010-02-04 20:07:08 UTC (rev 18696)
+++ core/trunk/core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java 2010-02-04 21:05:38 UTC (rev 18697)
@@ -3801,21 +3801,42 @@
return getTuplizer( entityMode ).getIdentifier( object );
}
- public void setIdentifier(Object object, Serializable id, EntityMode entityMode)
+ /**
+ * {@inheritDoc}
+ */
+ public void setIdentifier(Object entity, Serializable id, EntityMode entityMode)
throws HibernateException {
- getTuplizer( entityMode ).setIdentifier( object, id );
+ getTuplizer( entityMode ).setIdentifier( entity, id, null );
}
+ /**
+ * {@inheritDoc}
+ */
+ public void setIdentifier(Object entity, Serializable id, SessionImplementor session) {
+ getTuplizer( session ).setIdentifier( entity, id, session );
+ }
+
public Object getVersion(Object object, EntityMode entityMode)
throws HibernateException {
return getTuplizer( entityMode ).getVersion( object );
}
+ /**
+ * {@inheritDoc}
+ */
public Object instantiate(Serializable id, EntityMode entityMode)
throws HibernateException {
- return getTuplizer( entityMode ).instantiate( id );
+ return getTuplizer( entityMode ).instantiate( id, null );
}
+ /**
+ * {@inheritDoc}
+ */
+ public Object instantiate(Serializable id, SessionImplementor session)
+ throws HibernateException {
+ return getTuplizer( session ).instantiate( id, session );
+ }
+
public boolean isInstance(Object object, EntityMode entityMode) {
return getTuplizer( entityMode ).isInstance( object );
}
@@ -3825,9 +3846,16 @@
}
public void resetIdentifier(Object entity, Serializable currentId, Object currentVersion, EntityMode entityMode) {
- getTuplizer( entityMode ).resetIdentifier( entity, currentId, currentVersion );
+ getTuplizer( entityMode ).resetIdentifier( entity, currentId, currentVersion, null );
}
+ public void resetIdentifier(Object entity, Serializable currentId, Object currentVersion, SessionImplementor session) {
+ getTuplizer( session ).resetIdentifier( entity, currentId, currentVersion, session );
+ }
+
+ /**
+ * {@inheritDoc}
+ */
public EntityPersister getSubclassEntityPersister(
Object instance,
SessionFactoryImplementor factory,
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 2010-02-04 20:07:08 UTC (rev 18696)
+++ core/trunk/core/src/main/java/org/hibernate/persister/entity/EntityPersister.java 2010-02-04 21:05:38 UTC (rev 18697)
@@ -655,11 +655,29 @@
*/
public Serializable getIdentifier(Object object, EntityMode entityMode) throws HibernateException;
- /**
- * Set the identifier of an instance (or do nothing if no identifier property)
- */
- public void setIdentifier(Object object, Serializable id, EntityMode entityMode) throws HibernateException;
+ /**
+ * Inject the identifier value into the given entity.
+ * </p>
+ * Has no effect if the entity does not define an identifier property
+ *
+ * @param entity The entity to inject with the identifier value.
+ * @param id The value to be injected as the identifier.
+ * @param entityMode The entity mode
+ *
+ * @deprecated Use {@link #setIdentifier(Object, Serializable, SessionImplementor)} instead.
+ * @noinspection JavaDoc
+ */
+ public void setIdentifier(Object entity, Serializable id, EntityMode entityMode) throws HibernateException;
+ /**
+ * Inject the identifier value into the given entity.
+ *
+ * @param entity The entity to inject with the identifier value.
+ * @param id The value to be injected as the identifier.
+ * @param session The session from which is requests originates
+ */
+ public void setIdentifier(Object entity, Serializable id, SessionImplementor session);
+
/**
* Get the version number (or timestamp) from the object's version property (or return null if not versioned)
*/
@@ -667,10 +685,23 @@
/**
* Create a class instance initialized with the given identifier
+ *
+ * @deprecated Use {@link #instantiate(Serializable, SessionImplementor)} instead
+ * @noinspection JavaDoc
*/
public Object instantiate(Serializable id, EntityMode entityMode) throws HibernateException;
/**
+ * Create a class instance initialized with the given identifier
+ *
+ * @param id The identifier value to use (may be null to represent no value)
+ * @param session The session from which the request originated.
+ *
+ * @return The instantiated entity.
+ */
+ public Object instantiate(Serializable id, SessionImplementor session);
+
+ /**
* Is the given object an instance of this entity?
*/
public boolean isInstance(Object object, EntityMode entityMode);
@@ -687,10 +718,22 @@
* @param currentId The currently assigned identifier value.
* @param currentVersion The currently assigned version value.
* @param entityMode The entity mode represented by the entity instance.
+ *
+ * @deprecated Use {@link #resetIdentifier(Object, Serializable, Object, SessionImplementor)} instead
*/
public void resetIdentifier(Object entity, Serializable currentId, Object currentVersion, EntityMode entityMode);
/**
+ * Set the identifier and version of the given instance back to its "unsaved" value.
+ *
+ * @param entity The entity instance
+ * @param currentId The currently assigned identifier value.
+ * @param currentVersion The currently assigned version value.
+ * @param session The session from which the request originated.
+ */
+ public void resetIdentifier(Object entity, Serializable currentId, Object currentVersion, SessionImplementor session);
+
+ /**
* A request has already identified the entity-name of this persister as the mapping for the given instance.
* However, we still need to account for possible subclassing and potentially re-route to the more appropriate
* persister.
Modified: core/trunk/core/src/main/java/org/hibernate/tuple/entity/AbstractEntityTuplizer.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/tuple/entity/AbstractEntityTuplizer.java 2010-02-04 20:07:08 UTC (rev 18696)
+++ core/trunk/core/src/main/java/org/hibernate/tuple/entity/AbstractEntityTuplizer.java 2010-02-04 21:05:38 UTC (rev 18697)
@@ -236,8 +236,19 @@
}
}
+ /**
+ * {@inheritDoc}
+ */
+ public void setIdentifier(Object entity, Serializable id) throws HibernateException {
+ // 99% of the time the session is not needed. Its only needed for certain brain-dead
+ // interpretations of JPA 2 "derived identity" support
+ setIdentifier( entity, id, null );
+ }
- public void setIdentifier(Object entity, Serializable id) throws HibernateException {
+ /**
+ * {@inheritDoc}
+ */
+ public void setIdentifier(Object entity, Serializable id, SessionImplementor session) {
if ( entityMetamodel.getIdentifierProperty().isEmbedded() ) {
if ( entity != id ) {
AbstractComponentType copier = (AbstractComponentType) entityMetamodel.getIdentifierProperty().getType();
@@ -265,16 +276,31 @@
}
}
+ /**
+ * {@inheritDoc}
+ */
public void resetIdentifier(Object entity, Serializable currentId, Object currentVersion) {
+ // 99% of the time the session is not needed. Its only needed for certain brain-dead
+ // interpretations of JPA 2 "derived identity" support
+ resetIdentifier( entity, currentId, currentVersion, null );
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public void resetIdentifier(
+ Object entity,
+ Serializable currentId,
+ Object currentVersion,
+ SessionImplementor session) {
if ( entityMetamodel.getIdentifierProperty().getIdentifierGenerator() instanceof Assigned ) {
- //return currentId;
}
else {
//reset the id
Serializable result = entityMetamodel.getIdentifierProperty()
.getUnsavedValue()
.getDefaultValue( currentId );
- setIdentifier( entity, result );
+ setIdentifier( entity, result, session );
//reset the version
VersionProperty versionProperty = entityMetamodel.getVersionProperty();
if ( entityMetamodel.isVersioned() ) {
@@ -282,10 +308,8 @@
entity,
entityMetamodel.getVersionPropertyIndex(),
versionProperty.getUnsavedValue().getDefaultValue( currentVersion )
- );
+ );
}
- //return the id, so we can use it to reset the proxy id
- //return result;
}
}
@@ -421,15 +445,21 @@
}
public final Object instantiate(Serializable id) throws HibernateException {
+ // 99% of the time the session is not needed. Its only needed for certain brain-dead
+ // interpretations of JPA 2 "derived identity" support
+ return instantiate( id, null );
+ }
+
+ public final Object instantiate(Serializable id, SessionImplementor session) {
Object result = getInstantiator().instantiate( id );
if ( id != null ) {
- setIdentifier( result, id );
+ setIdentifier( result, id, session );
}
return result;
}
public final Object instantiate() throws HibernateException {
- return instantiate( null );
+ return instantiate( null, null );
}
public void afterInitialize(Object entity, boolean lazyPropertiesAreUnfetched, SessionImplementor session) {}
Modified: core/trunk/core/src/main/java/org/hibernate/tuple/entity/EntityTuplizer.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/tuple/entity/EntityTuplizer.java 2010-02-04 20:07:08 UTC (rev 18696)
+++ core/trunk/core/src/main/java/org/hibernate/tuple/entity/EntityTuplizer.java 2010-02-04 21:05:38 UTC (rev 18697)
@@ -59,10 +59,23 @@
* @param id The identifier value for the entity to be instantiated.
* @return The instantiated entity.
* @throws HibernateException
+ *
+ * @deprecated Use {@link #instantiate(Serializable, SessionImplementor)} instead.
+ * @noinspection JavaDoc
*/
public Object instantiate(Serializable id) throws HibernateException;
/**
+ * Create an entity instance initialized with the given identifier.
+ *
+ * @param id The identifier value for the entity to be instantiated.
+ * @param session The session from which is requests originates
+ *
+ * @return The instantiated entity.
+ */
+ public Object instantiate(Serializable id, SessionImplementor session);
+
+ /**
* Extract the identifier value from the given entity.
*
* @param entity The entity from which to extract the identifier value.
@@ -79,19 +92,46 @@
*
* @param entity The entity to inject with the identifier value.
* @param id The value to be injected as the identifier.
- * @throws HibernateException
+ *
+ * @deprecated Use {@link #setIdentifier(Object, Serializable, SessionImplementor)} instead.
+ * @noinspection JavaDoc
*/
public void setIdentifier(Object entity, Serializable id) throws HibernateException;
+ /**
+ * Inject the identifier value into the given entity.
+ * </p>
+ * Has no effect if the entity does not define an identifier property
+ *
+ * @param entity The entity to inject with the identifier value.
+ * @param id The value to be injected as the identifier.
+ * @param session The session from which is requests originates
+ */
+ public void setIdentifier(Object entity, Serializable id, SessionImplementor session);
+
/**
* Inject the given identifier and version into the entity, in order to
* "roll back" to their original values.
*
+ * @param entity The entity for which to reset the id/version values
* @param currentId The identifier value to inject into the entity.
* @param currentVersion The version value to inject into the entity.
+ *
+ * @deprecated Use {@link #resetIdentifier(Object, Serializable, Object, SessionImplementor)} instead
*/
public void resetIdentifier(Object entity, Serializable currentId, Object currentVersion);
+ /**
+ * Inject the given identifier and version into the entity, in order to
+ * "roll back" to their original values.
+ *
+ * @param entity The entity for which to reset the id/version values
+ * @param currentId The identifier value to inject into the entity.
+ * @param currentVersion The version value to inject into the entity.
+ * @param session The session from which the request originated
+ */
+ public void resetIdentifier(Object entity, Serializable currentId, Object currentVersion, SessionImplementor session);
+
/**
* Extract the value of the version property from the given entity.
*
Modified: core/trunk/core/src/main/java/org/hibernate/type/EntityType.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/type/EntityType.java 2010-02-04 20:07:08 UTC (rev 18696)
+++ core/trunk/core/src/main/java/org/hibernate/type/EntityType.java 2010-02-04 21:05:38 UTC (rev 18697)
@@ -276,7 +276,7 @@
if ( session.getContextEntityIdentifier( original ) == null &&
ForeignKeys.isTransient( associatedEntityName, original, Boolean.FALSE, session ) ) {
final Object copy = session.getFactory().getEntityPersister( associatedEntityName )
- .instantiate( null, session.getEntityMode() );
+ .instantiate( null, session );
//TODO: should this be Session.instantiate(Persister, ...)?
copyCache.put( original, copy );
return copy;
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 2010-02-04 20:07:08 UTC (rev 18696)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/legacy/CustomPersister.java 2010-02-04 21:05:38 UTC (rev 18697)
@@ -62,6 +62,10 @@
}
}
+ private void checkEntityMode(SessionImplementor session) {
+ checkEntityMode( session.getEntityMode() );
+ }
+
public boolean isInherited() {
return false;
}
@@ -183,6 +187,11 @@
( (Custom) object ).id = (String) id;
}
+ public void setIdentifier(Object entity, Serializable id, SessionImplementor session) {
+ checkEntityMode( session );
+ ( (Custom) entity ).id = (String) id;
+ }
+
public Object getVersion(Object object, EntityMode entityMode) throws HibernateException {
checkEntityMode( entityMode );
return null;
@@ -190,11 +199,20 @@
public Object instantiate(Serializable id, EntityMode entityMode) throws HibernateException {
checkEntityMode( entityMode );
+ return instantiate( id );
+ }
+
+ private Object instantiate(Serializable id) {
Custom c = new Custom();
c.id = (String) id;
return c;
}
+ public Object instantiate(Serializable id, SessionImplementor session) {
+ checkEntityMode( session );
+ return instantiate( id );
+ }
+
public boolean isInstance(Object object, EntityMode entityMode) {
checkEntityMode( entityMode );
return object instanceof Custom;
@@ -210,6 +228,11 @@
( ( Custom ) entity ).id = ( String ) currentId;
}
+ public void resetIdentifier(Object entity, Serializable currentId, Object currentVersion, SessionImplementor session) {
+ checkEntityMode( session );
+ ( ( Custom ) entity ).id = ( String ) currentId;
+ }
+
public EntityPersister getSubclassEntityPersister(Object instance, SessionFactoryImplementor factory, EntityMode entityMode) {
checkEntityMode( entityMode );
return this;
[View Less]
15 years, 1 month
Hibernate SVN: r18696 - core/trunk/testing/src/main/java/org/hibernate/test/annotations.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2010-02-04 15:07:08 -0500 (Thu, 04 Feb 2010)
New Revision: 18696
Modified:
core/trunk/testing/src/main/java/org/hibernate/test/annotations/HibernateTestCase.java
Log:
HHH-4848 - Derived identities: Derived entities using @IdClass and mapping a @XToOne are not supported
Modified: core/trunk/testing/src/main/java/org/hibernate/test/annotations/HibernateTestCase.java
===================================================================
--- core/trunk/…
[View More]testing/src/main/java/org/hibernate/test/annotations/HibernateTestCase.java 2010-02-04 19:32:54 UTC (rev 18695)
+++ core/trunk/testing/src/main/java/org/hibernate/test/annotations/HibernateTestCase.java 2010-02-04 20:07:08 UTC (rev 18696)
@@ -43,6 +43,7 @@
import org.hibernate.junit.FailureExpected;
import org.hibernate.junit.RequiresDialect;
import org.hibernate.junit.SkipForDialect;
+import org.hibernate.junit.SkipLog;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.util.StringHelper;
@@ -136,7 +137,7 @@
builder.append( " (" )
.append( failureExpected.jiraKey() )
.append( ")" );
- reportSkip( "Failed with: " + t.toString(), builder.toString() );
+ SkipLog.LOG.warn( builder.toString(), t );
}
else {
throw t;
@@ -340,8 +341,7 @@
builder.append( testDescription );
builder.append( " : " );
builder.append( reason );
-
- log.warn( builder.toString() );
+ SkipLog.LOG.warn( builder.toString() );
}
public class RollbackWork implements Work {
[View Less]
15 years, 1 month
Hibernate SVN: r18695 - in core/trunk: annotations/src/test/java/org/hibernate/test/annotations/embedded and 3 other directories.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2010-02-04 14:32:54 -0500 (Thu, 04 Feb 2010)
New Revision: 18695
Added:
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/many2one/
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/many2one/Address.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/many2one/Country.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/many2one/…
[View More]EmbeddableWithMany2OneTest.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/many2one/Person.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/one2many/
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/one2many/Alias.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/one2many/EmbeddableWithOne2ManyTest.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/one2many/Name.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/one2many/Person.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/one2many/PersonName.java
Modified:
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/TestCase.java
core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/TestCase.java
Log:
HHH-4599 - An embeddable class may contain ToOne or ToMany associations
Modified: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/TestCase.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/TestCase.java 2010-02-04 18:25:03 UTC (rev 18694)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/TestCase.java 2010-02-04 19:32:54 UTC (rev 18695)
@@ -95,6 +95,8 @@
}
try {
setCfg( new AnnotationConfiguration() );
+ // by default use the new id generator scheme...
+ cfg.setProperty( AnnotationConfiguration.USE_NEW_ID_GENERATOR_MAPPINGS, "true" );
configure( cfg );
if ( recreateSchema() ) {
cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
Added: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/many2one/Address.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/many2one/Address.java (rev 0)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/many2one/Address.java 2010-02-04 19:32:54 UTC (rev 18695)
@@ -0,0 +1,85 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2010, Red Hat Inc. or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.test.annotations.embedded.many2one;
+
+import javax.persistence.Embeddable;
+import javax.persistence.ManyToOne;
+
+import org.hibernate.annotations.AccessType;
+
+/**
+ * TODO : javadoc
+ *
+ * @author Steve Ebersole
+ */
+@Embeddable
+@AccessType("property")
+public class Address {
+ private String line1;
+ private String line2;
+ private String city;
+ private Country country;
+ private String postalCode;
+
+ public String getLine1() {
+ return line1;
+ }
+
+ public void setLine1(String line1) {
+ this.line1 = line1;
+ }
+
+ public String getLine2() {
+ return line2;
+ }
+
+ public void setLine2(String line2) {
+ this.line2 = line2;
+ }
+
+ public String getCity() {
+ return city;
+ }
+
+ public void setCity(String city) {
+ this.city = city;
+ }
+
+ @ManyToOne
+ public Country getCountry() {
+ return country;
+ }
+
+ public void setCountry(Country country) {
+ this.country = country;
+ }
+
+ public String getPostalCode() {
+ return postalCode;
+ }
+
+ public void setPostalCode(String postalCode) {
+ this.postalCode = postalCode;
+ }
+}
Copied: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/many2one/Country.java (from rev 18674, core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/Country.java)
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/many2one/Country.java (rev 0)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/many2one/Country.java 2010-02-04 19:32:54 UTC (rev 18695)
@@ -0,0 +1,64 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2010, Red Hat Inc. or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.test.annotations.embedded.many2one;
+
+import java.io.Serializable;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+/**
+ * THe entity target of the many-to-one from a component/embeddable.
+ *
+ * @author Steve Ebersole
+ */
+@Entity
+public class Country implements Serializable {
+ private String iso2;
+ private String name;
+
+ public Country() {
+ }
+
+ public Country(String iso2, String name) {
+ this.iso2 = iso2;
+ this.name = name;
+ }
+
+ @Id
+ public String getIso2() {
+ return iso2;
+ }
+
+ public void setIso2(String iso2) {
+ this.iso2 = iso2;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
\ No newline at end of file
Added: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/many2one/EmbeddableWithMany2OneTest.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/many2one/EmbeddableWithMany2OneTest.java (rev 0)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/many2one/EmbeddableWithMany2OneTest.java 2010-02-04 19:32:54 UTC (rev 18695)
@@ -0,0 +1,85 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2010, Red Hat Inc. or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.test.annotations.embedded.many2one;
+
+import java.util.List;
+
+import org.hibernate.Session;
+import org.hibernate.junit.FailureExpected;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * TODO : javadoc
+ *
+ * @author Steve Ebersole
+ */
+public class EmbeddableWithMany2OneTest extends TestCase {
+ @Override
+ protected Class<?>[] getAnnotatedClasses() {
+ return new Class[] { Person.class, Country.class };
+ }
+
+ @FailureExpected( jiraKey = "HHH-4883")
+ public void testJoinAcrossEmbedded() {
+ Session session = openSession();
+ session.beginTransaction();
+ session.createQuery( "from Person p join p.address as a join a.country as c where c.name = 'US'" )
+ .list();
+ session.createQuery( "from Person p join p.address as a join a.country as c where c.id = 'US'" )
+ .list();
+ session.getTransaction().commit();
+ session.close();
+ }
+
+ public void testBasicOps() {
+ Session session = openSession();
+ session.beginTransaction();
+ Country country = new Country( "US", "United States of America" );
+ session.persist( country );
+ Person person = new Person( "Steve", new Address() );
+ person.getAddress().setLine1( "123 Main" );
+ person.getAddress().setCity( "Anywhere" );
+ person.getAddress().setCountry( country );
+ person.getAddress().setPostalCode( "123456789" );
+ session.persist( person );
+ session.getTransaction().commit();
+ session.close();
+
+ session = openSession();
+ session.beginTransaction();
+ session.createQuery( "from Person p where p.address.country.iso2 = 'US'" )
+ .list();
+ // same query!
+ session.createQuery( "from Person p where p.address.country.id = 'US'" )
+ .list();
+ person = (Person) session.load( Person.class, person.getId() );
+ session.delete( person );
+ List countries = session.createQuery( "from Country" ).list();
+ assertEquals( 1, countries.size() );
+ session.delete( countries.get( 0 ) );
+
+ session.getTransaction().commit();
+ session.close();
+ }
+}
Added: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/many2one/Person.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/many2one/Person.java (rev 0)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/many2one/Person.java 2010-02-04 19:32:54 UTC (rev 18695)
@@ -0,0 +1,77 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2010, Red Hat Inc. or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.test.annotations.embedded.many2one;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * TODO : javadoc
+ *
+ * @author Steve Ebersole
+ */
+@Entity
+public class Person {
+ private Long id;
+ private String name;
+ private Address address;
+
+ public Person() {
+ }
+
+ public Person(String name) {
+ this.name = name;
+ }
+
+ public Person(String name, Address address) {
+ this.name = name;
+ this.address = address;
+ }
+
+ @Id @GeneratedValue
+ 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 Address getAddress() {
+ return address;
+ }
+
+ public void setAddress(Address address) {
+ this.address = address;
+ }
+}
Added: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/one2many/Alias.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/one2many/Alias.java (rev 0)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/one2many/Alias.java 2010-02-04 19:32:54 UTC (rev 18695)
@@ -0,0 +1,78 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2010, Red Hat Inc. or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.test.annotations.embedded.one2many;
+
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+import org.hibernate.annotations.Entity;
+
+/**
+ * TODO : javadoc
+ *
+ * @author Steve Ebersole
+ */
+@Entity
+public class Alias {
+ private Long id;
+ private Name name;
+ private String source;
+
+ public Alias() {
+ }
+
+ public Alias(String firstName, String lastName, String source) {
+ this( new PersonName( firstName, lastName ), source );
+ }
+
+ public Alias(Name name, String source) {
+ this.name = name;
+ this.source = source;
+ }
+
+ @Id @GeneratedValue
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public Name getName() {
+ return name;
+ }
+
+ public void setName(Name name) {
+ this.name = name;
+ }
+
+ public String getSource() {
+ return source;
+ }
+
+ public void setSource(String source) {
+ this.source = source;
+ }
+}
Added: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/one2many/EmbeddableWithOne2ManyTest.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/one2many/EmbeddableWithOne2ManyTest.java (rev 0)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/one2many/EmbeddableWithOne2ManyTest.java 2010-02-04 19:32:54 UTC (rev 18695)
@@ -0,0 +1,74 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2010, Red Hat Inc. or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.test.annotations.embedded.one2many;
+
+import java.util.List;
+
+import org.hibernate.Session;
+import org.hibernate.junit.FailureExpected;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * TODO : javadoc
+ *
+ * @author Steve Ebersole
+ */
+public class EmbeddableWithOne2ManyTest extends TestCase {
+ @Override
+ protected Class<?>[] getAnnotatedClasses() {
+ return new Class[] { Alias.class, Person.class };
+ }
+
+ @FailureExpected( jiraKey = "HHH-4883")
+ public void testJoinAcrossEmbedded() {
+ Session session = openSession();
+ session.beginTransaction();
+ session.createQuery( "from Person p join p.name.aliases a where a.source = 'FBI'" )
+ .list();
+ session.getTransaction().commit();
+ session.close();
+ }
+
+ @FailureExpected( jiraKey = "HHH-4599")
+ public void testBasicOps() {
+ Session session = openSession();
+ session.beginTransaction();
+ Alias alias = new Alias( "Public Enemy", "Number 1", "FBI" );
+ session.persist( alias );
+ Person person = new Person( "John", "Dillinger" );
+ person.getName().getAliases().add( alias );
+ session.persist( person );
+ session.getTransaction().commit();
+ session.close();
+
+ session = openSession();
+ session.beginTransaction();
+ person = (Person) session.load( Person.class, person.getId() );
+ session.delete( person );
+ List aliases = session.createQuery( "from Alias" ).list();
+ assertEquals( 0, aliases.size() );
+ session.getTransaction().commit();
+ session.close();
+ }
+}
\ No newline at end of file
Added: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/one2many/Name.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/one2many/Name.java (rev 0)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/one2many/Name.java 2010-02-04 19:32:54 UTC (rev 18695)
@@ -0,0 +1,64 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2010, Red Hat Inc. or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.test.annotations.embedded.one2many;
+
+import javax.persistence.Embeddable;
+
+import org.hibernate.annotations.AccessType;
+
+/**
+ * TODO : javadoc
+ *
+ * @author Steve Ebersole
+ */
+@Embeddable
+@AccessType("property")
+public class Name {
+ private String first;
+ private String last;
+
+ public Name() {
+ }
+
+ public Name(String first, String last) {
+ this.first = first;
+ this.last = last;
+ }
+
+ public String getFirst() {
+ return first;
+ }
+
+ public void setFirst(String first) {
+ this.first = first;
+ }
+
+ public String getLast() {
+ return last;
+ }
+
+ public void setLast(String last) {
+ this.last = last;
+ }
+}
Added: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/one2many/Person.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/one2many/Person.java (rev 0)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/one2many/Person.java 2010-02-04 19:32:54 UTC (rev 18695)
@@ -0,0 +1,67 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2010, Red Hat Inc. or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.test.annotations.embedded.one2many;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * TODO : javadoc
+ *
+ * @author Steve Ebersole
+ */
+@Entity
+public class Person {
+ private Long id;
+ private PersonName name;
+
+ public Person() {
+ }
+
+ public Person(String firstName, String lastName) {
+ this( new PersonName( firstName, lastName ) );
+ }
+
+ public Person(PersonName name) {
+ this.name = name;
+ }
+
+ @Id @GeneratedValue
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public PersonName getName() {
+ return name;
+ }
+
+ public void setName(PersonName name) {
+ this.name = name;
+ }
+}
Added: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/one2many/PersonName.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/one2many/PersonName.java (rev 0)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/embedded/one2many/PersonName.java 2010-02-04 19:32:54 UTC (rev 18695)
@@ -0,0 +1,59 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2010, Red Hat Inc. or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.test.annotations.embedded.one2many;
+
+import java.util.HashSet;
+import java.util.Set;
+import javax.persistence.CascadeType;
+import javax.persistence.Embeddable;
+import javax.persistence.OneToMany;
+
+import org.hibernate.annotations.AccessType;
+
+/**
+ * TODO : javadoc
+ *
+ * @author Steve Ebersole
+ */
+@Embeddable
+@AccessType("property")
+public class PersonName extends Name {
+ private Set<Alias> aliases = new HashSet<Alias>();
+
+ public PersonName() {
+ }
+
+ public PersonName(String first, String last) {
+ super( first, last );
+ }
+
+ @OneToMany( cascade = CascadeType.ALL )
+ public Set<Alias> getAliases() {
+ return aliases;
+ }
+
+ public void setAliases(Set<Alias> aliases) {
+ this.aliases = aliases;
+ }
+}
Modified: core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/TestCase.java
===================================================================
--- core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/TestCase.java 2010-02-04 18:25:03 UTC (rev 18694)
+++ core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/TestCase.java 2010-02-04 19:32:54 UTC (rev 18695)
@@ -38,6 +38,7 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.Dialect;
import org.hibernate.ejb.AvailableSettings;
@@ -79,6 +80,7 @@
if ( recreateSchema() ) {
cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
}
+ cfg.setProperty( AnnotationConfiguration.USE_NEW_ID_GENERATOR_MAPPINGS, "true" );
factory = ejbconfig.createEntityManagerFactory( getConfig() );
}
[View Less]
15 years, 1 month
Hibernate SVN: r18694 - in search/branches/Branch_3_1/src: test/java/org/hibernate/search/test/directoryProvider and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: sannegrinovero
Date: 2010-02-04 13:25:03 -0500 (Thu, 04 Feb 2010)
New Revision: 18694
Modified:
search/branches/Branch_3_1/src/main/java/org/hibernate/search/store/FSMasterDirectoryProvider.java
search/branches/Branch_3_1/src/main/java/org/hibernate/search/store/FSSlaveDirectoryProvider.java
search/branches/Branch_3_1/src/test/java/org/hibernate/search/test/directoryProvider/FSSlaveAndMasterDPTest.java
Log:
HSEARCH-452 (branch 3.1) FSMasterDirectoryProvider: typo in marker …
[View More]file name (Stephan Bublava)
Modified: search/branches/Branch_3_1/src/main/java/org/hibernate/search/store/FSMasterDirectoryProvider.java
===================================================================
--- search/branches/Branch_3_1/src/main/java/org/hibernate/search/store/FSMasterDirectoryProvider.java 2010-02-04 18:04:33 UTC (rev 18693)
+++ search/branches/Branch_3_1/src/main/java/org/hibernate/search/store/FSMasterDirectoryProvider.java 2010-02-04 18:25:03 UTC (rev 18694)
@@ -33,6 +33,11 @@
//TODO rename copy?
public class FSMasterDirectoryProvider implements DirectoryProvider<FSDirectory> {
+ private static final String CURRENT1 = "current1";
+ private static final String CURRENT2 = "current2";
+ // defined to have CURRENT_DIR_NAME[1] == "current"+"1":
+ private static final String[] CURRENT_DIR_NAME = { null, CURRENT1, CURRENT2 };
+
private static final Logger log = LoggerFactory.make();
private final Timer timer = new Timer( true ); //daemon thread, the copy algorithm is robust
@@ -74,10 +79,10 @@
int currentLocal = 0;
try {
//copy to source
- if ( new File( sourceDir, "current1").exists() ) {
+ if ( new File( sourceDir, CURRENT1 ).exists() ) {
currentLocal = 2;
}
- else if ( new File( sourceDir, "current2").exists() ) {
+ else if ( new File( sourceDir, CURRENT2 ).exists() ) {
currentLocal = 1;
}
else {
@@ -87,10 +92,10 @@
String currentString = Integer.valueOf( currentLocal ).toString();
File subDir = new File( sourceDir, currentString );
FileHelper.synchronize( indexDir, subDir, true, copyChunkSize );
- new File( sourceDir, "current1 ").delete();
- new File( sourceDir, "current2" ).delete();
+ new File( sourceDir, CURRENT1 ).delete();
+ new File( sourceDir, CURRENT2 ).delete();
//TODO small hole, no file can be found here
- new File( sourceDir, "current" + currentString ).createNewFile();
+ new File( sourceDir, CURRENT_DIR_NAME[currentLocal] ).createNewFile();
log.debug( "Current directory: {}", currentLocal );
}
catch (IOException e) {
@@ -196,11 +201,11 @@
log.error( "Unable to synchronize source of " + indexName, e );
return;
}
- if ( ! new File( destination, "current" + oldIndex ).delete() ) {
+ if ( ! new File( destination, CURRENT_DIR_NAME[oldIndex] ).delete() ) {
log.warn( "Unable to remove previous marker file from source of {}", indexName );
}
try {
- new File( destination, "current" + index ).createNewFile();
+ new File( destination, CURRENT_DIR_NAME[index] ).createNewFile();
}
catch( IOException e ) {
log.warn( "Unable to create current marker in source of " + indexName, e );
Modified: search/branches/Branch_3_1/src/main/java/org/hibernate/search/store/FSSlaveDirectoryProvider.java
===================================================================
--- search/branches/Branch_3_1/src/main/java/org/hibernate/search/store/FSSlaveDirectoryProvider.java 2010-02-04 18:04:33 UTC (rev 18693)
+++ search/branches/Branch_3_1/src/main/java/org/hibernate/search/store/FSSlaveDirectoryProvider.java 2010-02-04 18:25:03 UTC (rev 18694)
@@ -154,8 +154,8 @@
FSSlaveDirectoryProvider other = ( FSSlaveDirectoryProvider ) obj;
//need to break memory barriers on both instances:
@SuppressWarnings("unused")
- int readCurrentState = this.current; //unneded value, but ensure visibility of indexName
- readCurrentState = other.current; //another unneded value, but ensure visibility of indexName
+ int readCurrentState = this.current; //unneeded value, but ensure visibility of indexName
+ readCurrentState = other.current; //another unneeded value, but ensure visibility of indexName
return indexName.equals( other.indexName );
}
Modified: search/branches/Branch_3_1/src/test/java/org/hibernate/search/test/directoryProvider/FSSlaveAndMasterDPTest.java
===================================================================
--- search/branches/Branch_3_1/src/test/java/org/hibernate/search/test/directoryProvider/FSSlaveAndMasterDPTest.java 2010-02-04 18:04:33 UTC (rev 18693)
+++ search/branches/Branch_3_1/src/test/java/org/hibernate/search/test/directoryProvider/FSSlaveAndMasterDPTest.java 2010-02-04 18:25:03 UTC (rev 18694)
@@ -40,7 +40,7 @@
}
/**
- * The lucene index directory which is shared bewtween master and slave.
+ * The lucene index directory which is shared between master and slave.
*/
private String masterCopy = "/master/copy";
[View Less]
15 years, 1 month
Hibernate SVN: r18693 - in search/trunk/src: test/java/org/hibernate/search/test/directoryProvider and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: sannegrinovero
Date: 2010-02-04 13:04:33 -0500 (Thu, 04 Feb 2010)
New Revision: 18693
Modified:
search/trunk/src/main/java/org/hibernate/search/store/FSMasterDirectoryProvider.java
search/trunk/src/main/java/org/hibernate/search/store/FSSlaveDirectoryProvider.java
search/trunk/src/test/java/org/hibernate/search/test/directoryProvider/FSSlaveAndMasterDPTest.java
Log:
HSEARCH-452 (trunk) FSMasterDirectoryProvider: typo in marker file name (Stephan Bublava)
Modified: search/…
[View More]trunk/src/main/java/org/hibernate/search/store/FSMasterDirectoryProvider.java
===================================================================
--- search/trunk/src/main/java/org/hibernate/search/store/FSMasterDirectoryProvider.java 2010-02-04 17:54:05 UTC (rev 18692)
+++ search/trunk/src/main/java/org/hibernate/search/store/FSMasterDirectoryProvider.java 2010-02-04 18:04:33 UTC (rev 18693)
@@ -56,6 +56,11 @@
//TODO rename copy?
public class FSMasterDirectoryProvider implements DirectoryProvider<FSDirectory> {
+ private static final String CURRENT1 = "current1";
+ private static final String CURRENT2 = "current2";
+ // defined to have CURRENT_DIR_NAME[1] == "current"+"1":
+ private static final String[] CURRENT_DIR_NAME = { null, CURRENT1, CURRENT2 };
+
private static final Logger log = LoggerFactory.make();
private final Timer timer = new Timer( true ); //daemon thread, the copy algorithm is robust
@@ -97,10 +102,10 @@
int currentLocal = 0;
try {
//copy to source
- if ( new File( sourceDir, "current1").exists() ) {
+ if ( new File( sourceDir, CURRENT1 ).exists() ) {
currentLocal = 2;
}
- else if ( new File( sourceDir, "current2").exists() ) {
+ else if ( new File( sourceDir, CURRENT2 ).exists() ) {
currentLocal = 1;
}
else {
@@ -110,10 +115,10 @@
String currentString = Integer.valueOf( currentLocal ).toString();
File subDir = new File( sourceDir, currentString );
FileHelper.synchronize( indexDir, subDir, true, copyChunkSize );
- new File( sourceDir, "current1 ").delete();
- new File( sourceDir, "current2" ).delete();
+ new File( sourceDir, CURRENT1 ).delete();
+ new File( sourceDir, CURRENT2 ).delete();
//TODO small hole, no file can be found here
- new File( sourceDir, "current" + currentString ).createNewFile();
+ new File( sourceDir, CURRENT_DIR_NAME[currentLocal] ).createNewFile();
log.debug( "Current directory: {}", currentLocal );
}
catch (IOException e) {
@@ -219,11 +224,11 @@
log.error( "Unable to synchronize source of " + indexName, e );
return;
}
- if ( ! new File( destination, "current" + oldIndex ).delete() ) {
+ if ( ! new File( destination, CURRENT_DIR_NAME[oldIndex] ).delete() ) {
log.warn( "Unable to remove previous marker file from source of {}", indexName );
}
try {
- new File( destination, "current" + index ).createNewFile();
+ new File( destination, CURRENT_DIR_NAME[index] ).createNewFile();
}
catch( IOException e ) {
log.warn( "Unable to create current marker in source of " + indexName, e );
Modified: search/trunk/src/main/java/org/hibernate/search/store/FSSlaveDirectoryProvider.java
===================================================================
--- search/trunk/src/main/java/org/hibernate/search/store/FSSlaveDirectoryProvider.java 2010-02-04 17:54:05 UTC (rev 18692)
+++ search/trunk/src/main/java/org/hibernate/search/store/FSSlaveDirectoryProvider.java 2010-02-04 18:04:33 UTC (rev 18693)
@@ -177,8 +177,8 @@
FSSlaveDirectoryProvider other = ( FSSlaveDirectoryProvider ) obj;
//need to break memory barriers on both instances:
@SuppressWarnings("unused")
- int readCurrentState = this.current; //unneded value, but ensure visibility of indexName
- readCurrentState = other.current; //another unneded value, but ensure visibility of indexName
+ int readCurrentState = this.current; //unneeded value, but ensure visibility of indexName
+ readCurrentState = other.current; //another unneeded value, but ensure visibility of indexName
return indexName.equals( other.indexName );
}
Modified: search/trunk/src/test/java/org/hibernate/search/test/directoryProvider/FSSlaveAndMasterDPTest.java
===================================================================
--- search/trunk/src/test/java/org/hibernate/search/test/directoryProvider/FSSlaveAndMasterDPTest.java 2010-02-04 17:54:05 UTC (rev 18692)
+++ search/trunk/src/test/java/org/hibernate/search/test/directoryProvider/FSSlaveAndMasterDPTest.java 2010-02-04 18:04:33 UTC (rev 18693)
@@ -63,7 +63,7 @@
}
/**
- * The lucene index directory which is shared bewtween master and slave.
+ * The lucene index directory which is shared between master and slave.
*/
private String masterCopy = "/master/copy";
[View Less]
15 years, 1 month
Hibernate SVN: r18692 - in core/trunk: annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/a and 3 other directories.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2010-02-04 12:54:05 -0500 (Thu, 04 Feb 2010)
New Revision: 18692
Modified:
core/trunk/annotations/src/main/java/org/hibernate/cfg/AbstractPropertyHolder.java
core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationBinder.java
core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationConfiguration.java
core/trunk/annotations/src/main/java/org/hibernate/cfg/BinderHelper.java
core/trunk/annotations/src/main/java/org/hibernate/cfg/…
[View More]ColumnsBuilder.java
core/trunk/annotations/src/main/java/org/hibernate/cfg/ExtendedMappings.java
core/trunk/annotations/src/main/java/org/hibernate/cfg/PropertyHolder.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/a/DependentId.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/a/DerivedIdentitySimpleParentIdClassDepTest.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/a/Employee.java
core/trunk/core/src/main/java/org/hibernate/id/ForeignGenerator.java
core/trunk/core/src/main/java/org/hibernate/tuple/entity/AbstractEntityTuplizer.java
core/trunk/core/src/main/java/org/hibernate/type/EntityType.java
Log:
HHH-4848 partial implementation of @IdClass support in derivedidentity (example 1 case a of the spec)
Modified: core/trunk/annotations/src/main/java/org/hibernate/cfg/AbstractPropertyHolder.java
===================================================================
--- core/trunk/annotations/src/main/java/org/hibernate/cfg/AbstractPropertyHolder.java 2010-02-04 17:27:20 UTC (rev 18691)
+++ core/trunk/annotations/src/main/java/org/hibernate/cfg/AbstractPropertyHolder.java 2010-02-04 17:54:05 UTC (rev 18692)
@@ -55,6 +55,7 @@
private Map<String, JoinTable> currentPropertyJoinTableOverride;
private String path;
private ExtendedMappings mappings;
+ private Boolean isInIdClass;
public AbstractPropertyHolder(
@@ -66,6 +67,15 @@
buildHierarchyColumnOverride( clazzToProcess );
}
+
+ public boolean isInIdClass() {
+ return isInIdClass != null ? isInIdClass : parent != null ? parent.isInIdClass() : false;
+ }
+
+ public void setInIdClass(Boolean isInIdClass) {
+ this.isInIdClass = isInIdClass;
+ }
+
public String getPath() {
return path;
}
Modified: core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationBinder.java
===================================================================
--- core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationBinder.java 2010-02-04 17:27:20 UTC (rev 18691)
+++ core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationBinder.java 2010-02-04 17:54:05 UTC (rev 18692)
@@ -701,6 +701,7 @@
HashMap<String, IdGenerator> localGenerators = new HashMap<String, IdGenerator>();
boolean ignoreIdAnnotations = entityBinder.isIgnoreIdAnnotations();
entityBinder.setIgnoreIdAnnotations( true );
+ propertyHolder.setInIdClass( true );
bindId(
generatorType,
generator,
@@ -716,6 +717,7 @@
mappings,
inheritanceStatePerClass
);
+ propertyHolder.setInIdClass( null );
inferredData = new PropertyPreloadedData(
propertyAccessor, "_identifierMapper", compositeClass
);
@@ -728,7 +730,9 @@
entityBinder,
true,
true,
- false, mappings, inheritanceStatePerClass
+ false,
+ mappings,
+ inheritanceStatePerClass
);
entityBinder.setIgnoreIdAnnotations( ignoreIdAnnotations );
persistentClass.setIdentifierMapper( mapper );
@@ -1164,7 +1168,7 @@
* strategy is used
* @param propertyContainer Metadata about a class and its properties
* @param mappings Mapping meta data
- * @return the number of id properties found while iterating the elements of {@code annoatedClass} using
+ * @return the number of id properties found while iterating the elements of {@code annotatedClass} using
* the determined access strategy, {@code false} otherwise.
*/
static int addElementsOfClass(
@@ -1206,6 +1210,9 @@
final XAnnotatedElement element = propertyAnnotatedElement.getProperty();
if ( element.isAnnotationPresent( Id.class ) || element.isAnnotationPresent( EmbeddedId.class ) ) {
annElts.add( 0, propertyAnnotatedElement );
+ if ( element.isAnnotationPresent( ManyToOne.class ) || element.isAnnotationPresent( OneToOne.class ) ) {
+ mappings.addToOneAndIdProperty( entity, propertyAnnotatedElement );
+ }
idPropertyCounter++;
}
else {
@@ -1713,15 +1720,15 @@
//FIXME do the overrideColumnFromMapsIdProperty here and force the idclass type to look like an @embedded
//Overrides from @MapsId if needed
boolean isOverridden = false;
- if ( isId || propertyHolder.isOrWithinEmbeddedId() ) {
+ if ( isId || propertyHolder.isOrWithinEmbeddedId() || propertyHolder.isInIdClass() ) {
Ejb3Column[] oldColumns = columns;
- columns = columnsBuilder.overrideColumnFromMapsIdProperty(isId);
+ columns = columnsBuilder.overrideColumnFromMapperOrMapsIdProperty(isId);
isOverridden = oldColumns != columns;
}
if ( isComponent ) {
String referencedEntityName = null;
if (isOverridden) {
- final PropertyData mapsIdProperty = BinderHelper.getPropertyAnnotatedWithMapsId(
+ final PropertyData mapsIdProperty = BinderHelper.getPropertyOverriddenByMapperOrMapsId(
isId, propertyHolder, property.getName(), mappings
);
referencedEntityName = mapsIdProperty.getClassOrElementName();
@@ -1761,7 +1768,7 @@
propertyBinder.setLazy( lazy );
propertyBinder.setColumns( columns );
if (isOverridden) {
- final PropertyData mapsIdProperty = BinderHelper.getPropertyAnnotatedWithMapsId(
+ final PropertyData mapsIdProperty = BinderHelper.getPropertyOverriddenByMapperOrMapsId(
isId, propertyHolder, property.getName(), mappings
);
propertyBinder.setReferencedEntityName( mapsIdProperty.getClassOrElementName() );
@@ -1771,7 +1778,7 @@
}
if (isOverridden) {
- final PropertyData mapsIdProperty = BinderHelper.getPropertyAnnotatedWithMapsId(
+ final PropertyData mapsIdProperty = BinderHelper.getPropertyOverriddenByMapperOrMapsId(
isId, propertyHolder, property.getName(), mappings
);
HashMap<String, IdGenerator> localGenerators = (HashMap<String, IdGenerator>) classGenerators.clone();
@@ -2021,7 +2028,8 @@
}
public static Component fillComponent(
- PropertyHolder propertyHolder, PropertyData inferredData, PropertyData baseInferredData,
+ PropertyHolder propertyHolder, PropertyData inferredData,
+ PropertyData baseInferredData, //base inferred data correspond to the entity reproducing inferredData's properties (ie IdClass)
AccessType propertyAccessor, boolean isNullable, EntityBinder entityBinder,
boolean isComponentEmbedded, boolean isIdentifierMapper, boolean inSecondPass, ExtendedMappings mappings,
Map<XClass, InheritanceState> inheritanceStatePerClass
@@ -2045,14 +2053,17 @@
XClass returnedClassOrElement = inferredData.getClassOrElement();
List<PropertyData> baseClassElements = null;
+ Map<String, PropertyData> orderedBaseClassElements = new HashMap<String, PropertyData>();
XClass baseReturnedClassOrElement;
- if(baseInferredData != null)
- {
+ if(baseInferredData != null) {
baseClassElements = new ArrayList<PropertyData>();
baseReturnedClassOrElement = baseInferredData.getClassOrElement();
bindTypeDefs(baseReturnedClassOrElement, mappings);
PropertyContainer propContainer = new PropertyContainer( baseReturnedClassOrElement, entityXClass );
addElementsOfClass( baseClassElements, propertyAccessor, propContainer, mappings );
+ for (PropertyData element : baseClassElements) {
+ orderedBaseClassElements.put( element.getPropertyName(), element );
+ }
}
//embeddable elements can have type defs
@@ -2069,9 +2080,24 @@
superClass = superClass.getSuperclass();
}
if ( baseClassElements != null ) {
- if ( !hasIdClassAnnotations( entityXClass ) ) {
+ //useful to avoid breaking pre JPA 2 mappings
+ if ( !hasAnnotationsOnIdClass( entityXClass ) ) {
for ( int i = 0; i < classElements.size(); i++ ) {
- classElements.set( i, baseClassElements.get( i ) ); //this works since they are in the same order
+ final PropertyData idClassPropertyData = classElements.get( i );
+ final PropertyData entityPropertyData = orderedBaseClassElements.get( idClassPropertyData.getPropertyName() );
+ if ( propertyHolder.isInIdClass() ) {
+ if ( entityPropertyData.getProperty().isAnnotationPresent( ManyToOne.class )
+ || entityPropertyData.getProperty().isAnnotationPresent( OneToOne.class ) ) {
+ //don't replace here as we need to use the actual original return type
+ //the annotation overriding will be dealt with by a mechanism similar to @MapsId
+ }
+ else {
+ classElements.set( i, entityPropertyData ); //this works since they are in the same order
+ }
+ }
+ else {
+ classElements.set( i, entityPropertyData ); //this works since they are in the same order
+ }
}
}
}
@@ -2087,10 +2113,9 @@
XProperty property = propertyAnnotatedElement.getProperty();
if(property.isAnnotationPresent(GeneratedValue.class) &&
- property.isAnnotationPresent(Id.class))
- {
+ property.isAnnotationPresent(Id.class) ) {
//clone classGenerator and override with local values
- HashMap<String, IdGenerator> localGenerators = (HashMap<String, IdGenerator>) new HashMap<String, IdGenerator>();
+ HashMap<String, IdGenerator> localGenerators = new HashMap<String, IdGenerator>();
localGenerators.putAll( buildLocalGenerators( property, mappings ) );
GeneratedValue generatedValue = property.getAnnotation( GeneratedValue.class );
@@ -2647,10 +2672,10 @@
return inheritanceStatePerClass;
}
- private static boolean hasIdClassAnnotations(XClass idClass)
+ private static boolean hasAnnotationsOnIdClass(XClass idClass)
{
- if(idClass.getAnnotation(Embeddable.class) != null)
- return true;
+// if(idClass.getAnnotation(Embeddable.class) != null)
+// return true;
List<XProperty> properties = idClass.getDeclaredProperties( XClass.ACCESS_FIELD );
for ( XProperty property : properties ) {
Modified: core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationConfiguration.java
===================================================================
--- core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationConfiguration.java 2010-02-04 17:27:20 UTC (rev 18691)
+++ core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationConfiguration.java 2010-02-04 17:54:05 UTC (rev 18692)
@@ -65,7 +65,6 @@
import org.hibernate.HibernateException;
import org.hibernate.Interceptor;
import org.hibernate.MappingException;
-import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.annotations.AnyMetaDef;
import org.hibernate.annotations.Cache;
@@ -158,6 +157,7 @@
private boolean isDefaultProcessed = false;
private boolean isValidatorNotPresentLogged;
private Map<XClass,Map<String,PropertyData>> propertiesAnnotatedWithMapsId;
+ private Map<XClass,Map<String,PropertyData>> propertiesAnnotatedWithIdAndToOne;
public AnnotationConfiguration() {
super();
@@ -297,6 +297,7 @@
setEntityResolver( new EJB3DTDEntityResolver() );
anyMetaDefs = new HashMap<String, AnyMetaDef>();
propertiesAnnotatedWithMapsId = new HashMap<XClass, Map<String,PropertyData>>();
+ propertiesAnnotatedWithIdAndToOne = new HashMap<XClass, Map<String,PropertyData>>();
reflectionManager = new JavaReflectionManager();
( ( MetadataProviderInjector ) reflectionManager ).setMetadataProvider( new JPAMetadataProvider() );
@@ -1293,6 +1294,20 @@
map.put( property.getProperty().getAnnotation( MapsId.class ).value(), property );
}
+ public PropertyData getPropertyAnnotatedWithIdAndToOne(XClass entityType, String propertyName) {
+ final Map<String, PropertyData> map = propertiesAnnotatedWithIdAndToOne.get( entityType );
+ return map == null ? null : map.get( propertyName );
+ }
+
+ public void addToOneAndIdProperty(XClass entityType, PropertyData property) {
+ Map<String, PropertyData> map = propertiesAnnotatedWithIdAndToOne.get( entityType );
+ if (map == null) {
+ map = new HashMap<String, PropertyData>();
+ propertiesAnnotatedWithIdAndToOne.put( entityType, map );
+ }
+ map.put( property.getPropertyName(), property );
+ }
+
private Boolean useNewGeneratorMappings;
@SuppressWarnings({ "UnnecessaryUnboxing" })
Modified: core/trunk/annotations/src/main/java/org/hibernate/cfg/BinderHelper.java
===================================================================
--- core/trunk/annotations/src/main/java/org/hibernate/cfg/BinderHelper.java 2010-02-04 17:27:20 UTC (rev 18691)
+++ core/trunk/annotations/src/main/java/org/hibernate/cfg/BinderHelper.java 2010-02-04 17:54:05 UTC (rev 18692)
@@ -652,7 +652,7 @@
return StringHelper.qualify( holder.getPath(), property.getPropertyName() );
}
- static PropertyData getPropertyAnnotatedWithMapsId(boolean isId, PropertyHolder propertyHolder, String propertyName, ExtendedMappings mappings) {
+ static PropertyData getPropertyOverriddenByMapperOrMapsId(boolean isId, PropertyHolder propertyHolder, String propertyName, ExtendedMappings mappings) {
final XClass persistentXClass;
try {
persistentXClass = mappings.getReflectionManager()
@@ -661,8 +661,12 @@
catch ( ClassNotFoundException e ) {
throw new AssertionFailure( "PersistentClass name cannot be converted into a Class", e);
}
- String propertyPath = isId ? "" : propertyName;
- final PropertyData annotatedWithMapsId = mappings.getPropertyAnnotatedWithMapsId( persistentXClass, propertyPath );
- return annotatedWithMapsId;
+ if ( propertyHolder.isInIdClass() ) {
+ return mappings.getPropertyAnnotatedWithIdAndToOne( persistentXClass, propertyName );
+ }
+ else {
+ String propertyPath = isId ? "" : propertyName;
+ return mappings.getPropertyAnnotatedWithMapsId( persistentXClass, propertyPath );
+ }
}
}
Modified: core/trunk/annotations/src/main/java/org/hibernate/cfg/ColumnsBuilder.java
===================================================================
--- core/trunk/annotations/src/main/java/org/hibernate/cfg/ColumnsBuilder.java 2010-02-04 17:27:20 UTC (rev 18691)
+++ core/trunk/annotations/src/main/java/org/hibernate/cfg/ColumnsBuilder.java 2010-02-04 17:54:05 UTC (rev 18692)
@@ -11,12 +11,10 @@
import javax.persistence.OneToOne;
import org.hibernate.AnnotationException;
-import org.hibernate.AssertionFailure;
import org.hibernate.annotations.CollectionOfElements;
import org.hibernate.annotations.Columns;
import org.hibernate.annotations.Formula;
import org.hibernate.annotations.JoinColumnsOrFormulas;
-import org.hibernate.annotations.common.reflection.XClass;
import org.hibernate.annotations.common.reflection.XProperty;
import org.hibernate.cfg.annotations.EntityBinder;
import org.hibernate.cfg.annotations.Nullability;
@@ -183,15 +181,13 @@
return joinColumns;
}
- Ejb3Column[] overrideColumnFromMapsIdProperty(boolean isId) {
+ Ejb3Column[] overrideColumnFromMapperOrMapsIdProperty(boolean isId) {
Ejb3Column[] result = columns;
- final PropertyData annotatedWithMapsId = BinderHelper.getPropertyAnnotatedWithMapsId( isId, propertyHolder, property.getName(), mappings );
+ final PropertyData annotatedWithMapsId = BinderHelper.getPropertyOverriddenByMapperOrMapsId( isId, propertyHolder, property.getName(), mappings );
if ( annotatedWithMapsId != null ) {
result = buildExplicitJoinColumns( annotatedWithMapsId.getProperty(), annotatedWithMapsId );
if (result == null) {
result = buildDefaultJoinColumnsForXToOne( annotatedWithMapsId.getProperty(), annotatedWithMapsId);
-// throw new UnsupportedOperationException( "Implicit @JoinColumn is not supported on @MapsId properties: "
-// + annotatedWithMapsId.getDeclaringClass() + " " + annotatedWithMapsId.getPropertyName() );
}
}
return result;
Modified: core/trunk/annotations/src/main/java/org/hibernate/cfg/ExtendedMappings.java
===================================================================
--- core/trunk/annotations/src/main/java/org/hibernate/cfg/ExtendedMappings.java 2010-02-04 17:27:20 UTC (rev 18691)
+++ core/trunk/annotations/src/main/java/org/hibernate/cfg/ExtendedMappings.java 2010-02-04 17:54:05 UTC (rev 18692)
@@ -188,4 +188,12 @@
* @return True if the new generators should be used, false otherwise.
*/
public boolean useNewGeneratorMappings();
+
+ /**
+ * Return the property annotated with @ToOne and @Id if any.
+ * Null otherwise
+ */
+ public PropertyData getPropertyAnnotatedWithIdAndToOne(XClass entityType, String propertyName);
+
+ void addToOneAndIdProperty(XClass entity, PropertyData property);
}
\ No newline at end of file
Modified: core/trunk/annotations/src/main/java/org/hibernate/cfg/PropertyHolder.java
===================================================================
--- core/trunk/annotations/src/main/java/org/hibernate/cfg/PropertyHolder.java 2010-02-04 17:27:20 UTC (rev 18691)
+++ core/trunk/annotations/src/main/java/org/hibernate/cfg/PropertyHolder.java 2010-02-04 17:54:05 UTC (rev 18692)
@@ -89,4 +89,8 @@
String getEntityName();
Join addJoin(JoinTable joinTableAnn, boolean noDelayInPkColumnCreation);
+
+ boolean isInIdClass();
+
+ void setInIdClass(Boolean isInIdClass);
}
Modified: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/a/DependentId.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/a/DependentId.java 2010-02-04 17:27:20 UTC (rev 18691)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/a/DependentId.java 2010-02-04 17:54:05 UTC (rev 18692)
@@ -7,5 +7,5 @@
*/
public class DependentId implements Serializable {
String name;
- long empPK; // corresponds to PK type of Employee
+ long emp; // corresponds to PK type of Employee
}
\ No newline at end of file
Modified: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/a/DerivedIdentitySimpleParentIdClassDepTest.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/a/DerivedIdentitySimpleParentIdClassDepTest.java 2010-02-04 17:27:20 UTC (rev 18691)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/a/DerivedIdentitySimpleParentIdClassDepTest.java 2010-02-04 17:54:05 UTC (rev 18692)
@@ -1,6 +1,7 @@
package org.hibernate.test.annotations.derivedidentities.e1.a;
import org.hibernate.Session;
+import org.hibernate.junit.FailureExpected;
import org.hibernate.test.annotations.TestCase;
import org.hibernate.test.util.SchemaUtil;
@@ -10,36 +11,40 @@
public class
DerivedIdentitySimpleParentIdClassDepTest extends TestCase {
+ @FailureExpected( jiraKey = "HHH-4848" )
public void testManyToOne() throws Exception {
-// assertTrue( SchemaUtil.isColumnPresent( "Dependent", "FK", getCfg() ) );
-// assertTrue( ! SchemaUtil.isColumnPresent( "Dependent", "empPK", getCfg() ) );
-// Employee e = new Employee();
-// e.empId = 1;
-// e.empName = "Emmanuel";
-// Session s = openSession( );
-// s.getTransaction().begin();
-// s.persist( e );
-// Dependent d = new Dependent();
-// d.emp = e;
-// d.name = "Doggy";
-// d.emp = e;
-// s.persist( d );
-// s.flush();
-// s.clear();
-// DependentId dId = new DependentId();
-// dId.name = d.name;
-// dId.empPK = d.emp.empId;
-// d = (Dependent) s.get( Dependent.class, dId );
-// assertEquals( e.empId, d.emp.empId );
-// s.getTransaction().rollback();
-// s.close();
+ assertTrue( SchemaUtil.isColumnPresent( "Dependent", "emp_empId", getCfg() ) );
+ assertTrue( ! SchemaUtil.isColumnPresent( "Dependent", "emp", getCfg() ) );
+ Employee e = new Employee();
+ e.empId = 1;
+ e.empName = "Emmanuel";
+ e.nickname = "Manu";
+ Session s = openSession( );
+ s.getTransaction().begin();
+ s.persist( e );
+ Dependent d = new Dependent();
+ d.emp = e;
+ d.name = "Doggy";
+ d.emp = e;
+ s.persist( d );
+ s.flush();
+ s.clear();
+ DependentId dId = new DependentId();
+ dId.name = d.name;
+ dId.emp = d.emp.empId;
+ d = (Dependent) s.get( Dependent.class, dId );
+ assertEquals( e.empId, d.emp.empId );
+ assertEquals( e.empName, d.emp.empName );
+ assertEquals( e.nickname, d.emp.nickname );
+ s.getTransaction().rollback();
+ s.close();
}
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class<?>[] {
- //Dependent.class,
- //Employee.class
+ Dependent.class,
+ Employee.class
};
}
}
\ No newline at end of file
Modified: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/a/Employee.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/a/Employee.java 2010-02-04 17:27:20 UTC (rev 18691)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/a/Employee.java 2010-02-04 17:54:05 UTC (rev 18692)
@@ -11,4 +11,6 @@
@Id
long empId;
String empName;
+
+ String nickname;
}
\ No newline at end of file
Modified: core/trunk/core/src/main/java/org/hibernate/id/ForeignGenerator.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/id/ForeignGenerator.java 2010-02-04 17:27:20 UTC (rev 18691)
+++ core/trunk/core/src/main/java/org/hibernate/id/ForeignGenerator.java 2010-02-04 17:54:05 UTC (rev 18692)
@@ -33,6 +33,7 @@
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.ForeignKeys;
import org.hibernate.engine.SessionImplementor;
+import org.hibernate.metadata.ClassMetadata;
import org.hibernate.type.EntityType;
import org.hibernate.type.Type;
@@ -95,19 +96,27 @@
public Serializable generate(SessionImplementor sessionImplementor, Object object) {
Session session = ( Session ) sessionImplementor;
- Object associatedObject = sessionImplementor.getFactory()
- .getClassMetadata( entityName )
+ final ClassMetadata classMetadata = sessionImplementor.getFactory()
+ .getClassMetadata( entityName );
+ Object associatedObject = classMetadata
.getPropertyValue( object, propertyName, session.getEntityMode() );
if ( associatedObject == null ) {
throw new IdentifierGenerationException(
"attempted to assign id from null one-to-one property [" + getRole() + "]"
);
}
-
- EntityType type = (EntityType) sessionImplementor.getFactory()
- .getClassMetadata( entityName )
- .getPropertyType( propertyName );
+ final Type uncheckedType = classMetadata
+ .getPropertyType( propertyName );
+ EntityType type;
+ if (uncheckedType instanceof EntityType) {
+ type = (EntityType) uncheckedType;
+ }
+ else {
+ //try identifier mapper
+ type = (EntityType) classMetadata.getPropertyType( "_identifierMapper." + propertyName );
+ }
+
Serializable id;
try {
id = ForeignKeys.getEntityIdentifierIfNotUnsaved(
Modified: core/trunk/core/src/main/java/org/hibernate/tuple/entity/AbstractEntityTuplizer.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/tuple/entity/AbstractEntityTuplizer.java 2010-02-04 17:27:20 UTC (rev 18691)
+++ core/trunk/core/src/main/java/org/hibernate/tuple/entity/AbstractEntityTuplizer.java 2010-02-04 17:54:05 UTC (rev 18692)
@@ -30,6 +30,8 @@
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
+import org.hibernate.PropertyAccessException;
+import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.tuple.Instantiator;
import org.hibernate.tuple.VersionProperty;
import org.hibernate.tuple.StandardProperty;
@@ -45,6 +47,8 @@
import org.hibernate.proxy.ProxyFactory;
import org.hibernate.type.AbstractComponentType;
import org.hibernate.type.ComponentType;
+import org.hibernate.type.EntityType;
+import org.hibernate.type.Type;
/**
@@ -70,6 +74,9 @@
private final ProxyFactory proxyFactory;
private final AbstractComponentType identifierMapperType;
+ public Type getIdentifierMapperType() {
+ return identifierMapperType;
+ }
/**
* Build an appropriate Getter for the given property.
@@ -192,13 +199,27 @@
else {
ComponentType copier = (ComponentType) entityMetamodel.getIdentifierProperty().getType();
id = copier.instantiate( getEntityMode() );
- copier.setPropertyValues( id, identifierMapperType.getPropertyValues( entity, getEntityMode() ), getEntityMode() );
+ final Object[] propertyValues = identifierMapperType.getPropertyValues( entity, getEntityMode() );
+ Type[] subTypes = identifierMapperType.getSubtypes();
+ Type[] copierSubTypes = copier.getSubtypes();
+ final int length = subTypes.length;
+ for ( int i = 0 ; i < length; i++ ) {
+ //JPA 2 in @IdClass points to the pk of the entity
+ if ( subTypes[i].isAssociationType() && ! copierSubTypes[i].isAssociationType()) {
+ final String associatedEntityName = ( ( EntityType ) subTypes[i] ).getAssociatedEntityName();
+ final EntityPersister entityPersister = getFactory().getEntityPersister(
+ associatedEntityName
+ );
+ propertyValues[i] = entityPersister.getIdentifier( propertyValues[i], getEntityMode() );
+ }
+ }
+ copier.setPropertyValues( id, propertyValues, getEntityMode() );
}
}
else {
- id = idGetter.get( entity );
- }
- }
+ id = idGetter.get( entity );
+ }
+ }
try {
return (Serializable) id;
@@ -229,7 +250,18 @@
else if ( identifierMapperType != null ) {
ComponentType extractor = (ComponentType) entityMetamodel.getIdentifierProperty().getType();
ComponentType copier = (ComponentType) identifierMapperType;
- copier.setPropertyValues( entity, extractor.getPropertyValues( id, getEntityMode() ), getEntityMode() );
+ final Object[] propertyValues = extractor.getPropertyValues( id, getEntityMode() );
+ Type[] subTypes = identifierMapperType.getSubtypes();
+ Type[] copierSubTypes = copier.getSubtypes();
+ final int length = subTypes.length;
+ for ( int i = 0 ; i < length; i++ ) {
+ //JPA 2 in @IdClass points to the pk of the entity
+ if ( subTypes[i].isAssociationType() && ! copierSubTypes[i].isAssociationType() ) {
+ final String associatedEntityName = ( ( EntityType ) subTypes[i] ).getAssociatedEntityName();
+ //FIXME find the entity for the given id (propertyValue[i])
+ }
+ }
+ copier.setPropertyValues( entity, propertyValues, getEntityMode() );
}
}
@@ -299,18 +331,27 @@
}
public Object getPropertyValue(Object entity, String propertyPath) throws HibernateException {
- final int loc = propertyPath.indexOf('.');
- final String basePropertyName = loc > 0
+ int loc = propertyPath.indexOf('.');
+ String basePropertyName = loc > 0
? propertyPath.substring( 0, loc )
: propertyPath;
- final int index = entityMetamodel.getPropertyIndex( basePropertyName );
- final Object baseValue = getPropertyValue( entity, index );
+ //final int index = entityMetamodel.getPropertyIndexOrNull( basePropertyName );
+ Integer index = entityMetamodel.getPropertyIndexOrNull( basePropertyName );
+ if (index == null) {
+ propertyPath = "_identifierMapper." + propertyPath;
+ loc = propertyPath.indexOf('.');
+ basePropertyName = loc > 0
+ ? propertyPath.substring( 0, loc )
+ : propertyPath;
+ }
+ index = entityMetamodel.getPropertyIndexOrNull( basePropertyName );
+ final Object baseValue = getPropertyValue( entity, index.intValue() );
if ( loc > 0 ) {
if ( baseValue == null ) {
return null;
}
return getComponentValue(
- (ComponentType) entityMetamodel.getPropertyTypes()[index],
+ (ComponentType) entityMetamodel.getPropertyTypes()[index.intValue()],
baseValue,
propertyPath.substring(loc+1)
);
Modified: core/trunk/core/src/main/java/org/hibernate/type/EntityType.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/type/EntityType.java 2010-02-04 17:27:20 UTC (rev 18691)
+++ core/trunk/core/src/main/java/org/hibernate/type/EntityType.java 2010-02-04 17:54:05 UTC (rev 18692)
@@ -307,7 +307,13 @@
id = ( (HibernateProxy) x ).getHibernateLazyInitializer().getIdentifier();
}
else {
- id = persister.getIdentifier(x, entityMode);
+ final Class mappedClass = persister.getMappedClass( entityMode );
+ if ( mappedClass.isAssignableFrom( x.getClass() ) ) {
+ id = persister.getIdentifier(x, entityMode);
+ }
+ else {
+ id = (Serializable) x;
+ }
}
return persister.getIdentifierType().getHashCode(id, entityMode, factory);
}
@@ -321,13 +327,20 @@
return super.isEqual(x, y, entityMode);
}
+ final Class mappedClass = persister.getMappedClass( entityMode );
Serializable xid;
if (x instanceof HibernateProxy) {
xid = ( (HibernateProxy) x ).getHibernateLazyInitializer()
.getIdentifier();
}
else {
- xid = persister.getIdentifier(x, entityMode);
+ if ( mappedClass.isAssignableFrom( x.getClass() ) ) {
+ xid = persister.getIdentifier(x, entityMode);
+ }
+ else {
+ //JPA 2 case where @IdClass contains the id and not the associated entity
+ xid = (Serializable) x;
+ }
}
Serializable yid;
@@ -336,7 +349,13 @@
.getIdentifier();
}
else {
- yid = persister.getIdentifier(y, entityMode);
+ if ( mappedClass.isAssignableFrom( y.getClass() ) ) {
+ yid = persister.getIdentifier(x, entityMode);
+ }
+ else {
+ //JPA 2 case where @IdClass contains the id and not the associated entity
+ yid = (Serializable) y;
+ }
}
return persister.getIdentifierType()
[View Less]
15 years, 1 month
Hibernate SVN: r18691 - in search/trunk: src/main/java/org/hibernate/search/impl and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: sannegrinovero
Date: 2010-02-04 12:27:20 -0500 (Thu, 04 Feb 2010)
New Revision: 18691
Modified:
search/trunk/pom.xml
search/trunk/src/main/java/org/hibernate/search/impl/FullTextSessionImpl.java
Log:
HSEARCH-455 Keep Search compatible with latest Hibernate Core
Modified: search/trunk/pom.xml
===================================================================
--- search/trunk/pom.xml 2010-02-04 16:12:07 UTC (rev 18690)
+++ search/trunk/pom.xml 2010-02-04 17:27:20 UTC (rev 18691)
@…
[View More]@ -116,7 +116,7 @@
<properties>
<slf4jVersion>1.5.8</slf4jVersion>
<luceneVersion>2.9.1</luceneVersion>
- <hibernateVersion>3.5.0-SNAPSHOT</hibernateVersion>
+ <hibernateVersion>3.5.0-Beta-4</hibernateVersion>
<hibernateCommonsAnnotationVersion>3.2.0.Beta1</hibernateCommonsAnnotationVersion>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
Modified: search/trunk/src/main/java/org/hibernate/search/impl/FullTextSessionImpl.java
===================================================================
--- search/trunk/src/main/java/org/hibernate/search/impl/FullTextSessionImpl.java 2010-02-04 16:12:07 UTC (rev 18690)
+++ search/trunk/src/main/java/org/hibernate/search/impl/FullTextSessionImpl.java 2010-02-04 17:27:20 UTC (rev 18691)
@@ -654,6 +654,10 @@
return session.isDirty();
}
+ public boolean isDefaultReadOnly() {
+ return session.isDefaultReadOnly();
+ }
+
public boolean isOpen() {
return session.isOpen();
}
@@ -762,6 +766,10 @@
session.setCacheMode( cacheMode );
}
+ public void setDefaultReadOnly(boolean readOnly) {
+ session.setDefaultReadOnly( readOnly );
+ }
+
public void setFlushMode(FlushMode flushMode) {
session.setFlushMode( flushMode );
}
[View Less]
15 years, 1 month
Hibernate SVN: r18690 - in jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen: annotation and 2 other directories.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2010-02-04 11:12:07 -0500 (Thu, 04 Feb 2010)
New Revision: 18690
Added:
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/model/
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/model/ImportContext.java
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/model/MetaAttribute.java
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/model/MetaCollection.java
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/model/…
[View More]MetaEntity.java
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/model/MetaSingleAttribute.java
Removed:
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/ImportContext.java
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/MetaAttribute.java
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/MetaCollection.java
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/MetaEntity.java
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/MetaSingleAttribute.java
Modified:
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/ClassWriter.java
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/Context.java
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/ImportContextImpl.java
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/JPAMetaModelEntityProcessor.java
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationMetaAttribute.java
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationMetaCollection.java
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationMetaEntity.java
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationMetaSingleAttribute.java
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaAttribute.java
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaCollection.java
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaEntity.java
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaSingleAttribute.java
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlParser.java
Log:
METAGEN-9
Modified: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/ClassWriter.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/ClassWriter.java 2010-02-04 10:57:52 UTC (rev 18689)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/ClassWriter.java 2010-02-04 16:12:07 UTC (rev 18690)
@@ -31,6 +31,9 @@
import javax.tools.Diagnostic;
import javax.tools.FileObject;
+import org.hibernate.jpamodelgen.model.MetaAttribute;
+import org.hibernate.jpamodelgen.model.MetaEntity;
+
/**
* @author Emmanuel Bernard
*/
@@ -112,8 +115,8 @@
//F..king Ch...t Have those people used their horrible APIs even once?
final Element superClassElement = ( ( DeclaredType ) superClass ).asElement();
String superClassName = ( ( TypeElement ) superClassElement ).getQualifiedName().toString();
- if ( context.getMetaEntities().containsKey( superClassName )
- || context.getMetaSuperclassAndEmbeddable().containsKey( superClassName ) ) {
+ if ( context.containsMetaEntity( superClassName )
+ || context.containsMetaSuperclassOrEmbeddable( superClassName ) ) {
pw.print( " extends " + superClassName + "_" );
}
}
Modified: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/Context.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/Context.java 2010-02-04 10:57:52 UTC (rev 18689)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/Context.java 2010-02-04 16:12:07 UTC (rev 18690)
@@ -18,6 +18,7 @@
package org.hibernate.jpamodelgen;
import java.util.ArrayList;
+import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
@@ -30,6 +31,7 @@
import javax.tools.Diagnostic;
import org.hibernate.jpamodelgen.annotation.AnnotationMetaEntity;
+import org.hibernate.jpamodelgen.model.MetaEntity;
import org.hibernate.jpamodelgen.util.TypeUtils;
/**
@@ -104,14 +106,42 @@
return ormXmlFiles;
}
- public Map<String, MetaEntity> getMetaEntities() {
- return metaEntities;
+ public boolean containsMetaEntity(String fqcn) {
+ return metaEntities.containsKey( fqcn );
}
- public Map<String, MetaEntity> getMetaSuperclassAndEmbeddable() {
- return metaSuperclassAndEmbeddable;
+ public MetaEntity getMetaEntity(String fqcn) {
+ return metaEntities.get( fqcn );
}
+ public Collection<MetaEntity> getMetaEntities() {
+ return metaEntities.values();
+ }
+
+ public void addMetaEntity(String fcqn, MetaEntity metaEntity) {
+ metaEntities.put( fcqn, metaEntity );
+ }
+
+ public boolean containsMetaSuperclassOrEmbeddable(String fqcn) {
+ return metaSuperclassAndEmbeddable.containsKey( fqcn );
+ }
+
+ public MetaEntity getMetaSuperclassOrEmbeddable(String fqcn) {
+ return metaSuperclassAndEmbeddable.get( fqcn );
+ }
+
+ public void addMetaSuperclassOrEmbeddable(String fcqn, MetaEntity metaEntity) {
+ metaSuperclassAndEmbeddable.put( fcqn, metaEntity );
+ }
+
+ public void removeMetaSuperclassOrEmbeddable(String fcqn) {
+ metaSuperclassAndEmbeddable.remove( fcqn );
+ }
+
+ public Collection<MetaEntity> getMetaSuperclassOrEmbeddable() {
+ return metaSuperclassAndEmbeddable.values();
+ }
+
public void addAccessType(TypeElement element, AccessType accessType) {
AccessTypeHolder typeHolder = accessTypes.get( element );
if ( typeHolder == null ) {
Deleted: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/ImportContext.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/ImportContext.java 2010-02-04 10:57:52 UTC (rev 18689)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/ImportContext.java 2010-02-04 16:12:07 UTC (rev 18690)
@@ -1,46 +0,0 @@
-// $Id$
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2008, Red Hat Middleware LLC, and individual contributors
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-* http://www.apache.org/licenses/LICENSE-2.0
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-package org.hibernate.jpamodelgen;
-
-/**
- *
- * @author Max Andersen
- * @author Hardy Ferentschik
- * @author Emmanuel Bernard
- */
-public interface ImportContext {
-
- /**
- * Add fqcn to the import list. Returns fqcn as needed in source code.
- * Attempts to handle fqcn with array and generics references.
- * <p/>
- * e.g.
- * java.util.Collection<org.marvel.Hulk> imports java.util.Collection and returns Collection
- * org.marvel.Hulk[] imports org.marvel.Hulk and returns Hulk
- *
- * @param fqcn Fully qualified class name of the type to import.
- *
- * @return import string
- */
- public abstract String importType(String fqcn);
-
- public abstract String staticImport(String fqcn, String member);
-
- public abstract String generateImports();
-
-}
\ No newline at end of file
Modified: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/ImportContextImpl.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/ImportContextImpl.java 2010-02-04 10:57:52 UTC (rev 18689)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/ImportContextImpl.java 2010-02-04 16:12:07 UTC (rev 18690)
@@ -18,14 +18,14 @@
package org.hibernate.jpamodelgen;
import java.util.HashMap;
-import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
+import org.hibernate.jpamodelgen.model.ImportContext;
+
/**
- *
* @author Max Andersen
* @author Hardy Ferentschik
* @author Emmanuel Bernard
@@ -35,10 +35,11 @@
Set<String> imports = new TreeSet<String>();
Set<String> staticImports = new TreeSet<String>();
Map<String, String> simpleNames = new HashMap<String, String>();
-
+
String basePackage = "";
private static final Map<String, String> PRIMITIVES = new HashMap<String, String>();
+
static {
PRIMITIVES.put( "char", "Character" );
@@ -61,77 +62,81 @@
/**
* Add fqcn to the import list. Returns fqcn as needed in source code.
* Attempts to handle fqcn with array and generics references.
- *
+ * <p/>
* e.g.
* java.util.Collection<org.marvel.Hulk> imports java.util.Collection and returns Collection
* org.marvel.Hulk[] imports org.marvel.Hulk and returns Hulk
- *
- *
- * @param fqcn
+ *
+ * @param fqcn Fully qualified class name
+ *
* @return import string
*/
public String importType(String fqcn) {
- String result = fqcn;
-
+ String result = fqcn;
+
//if(fqcn==null) return "/** (null) **/";
-
+
String additionalTypePart = null;
- if(fqcn.indexOf('<')>=0) {
- additionalTypePart = result.substring(fqcn.indexOf('<'));
- result = result.substring(0,fqcn.indexOf('<'));
+ if ( fqcn.indexOf( '<' ) >= 0 ) {
+ additionalTypePart = result.substring( fqcn.indexOf( '<' ) );
+ result = result.substring( 0, fqcn.indexOf( '<' ) );
fqcn = result;
- } else if(fqcn.indexOf('[')>=0) {
- additionalTypePart = result.substring(fqcn.indexOf('['));
- result = result.substring(0,fqcn.indexOf('['));
+ }
+ else if ( fqcn.indexOf( '[' ) >= 0 ) {
+ additionalTypePart = result.substring( fqcn.indexOf( '[' ) );
+ result = result.substring( 0, fqcn.indexOf( '[' ) );
fqcn = result;
}
-
+
String pureFqcn = fqcn.replace( '$', '.' );
-
- boolean canBeSimple = true;
-
-
- String simpleName = unqualify(fqcn);
- if(simpleNames.containsKey(simpleName)) {
- String existingFqcn = simpleNames.get(simpleName);
- if(existingFqcn.equals(pureFqcn)) {
+
+ boolean canBeSimple;
+
+ String simpleName = unqualify( fqcn );
+ if ( simpleNames.containsKey( simpleName ) ) {
+ String existingFqcn = simpleNames.get( simpleName );
+ if ( existingFqcn.equals( pureFqcn ) ) {
canBeSimple = true;
- } else {
+ }
+ else {
canBeSimple = false;
}
- } else {
+ }
+ else {
canBeSimple = true;
- simpleNames.put(simpleName, pureFqcn);
+ simpleNames.put( simpleName, pureFqcn );
imports.add( pureFqcn );
}
-
-
- if ( inSamePackage(fqcn) || (imports.contains( pureFqcn ) && canBeSimple) ) {
+
+
+ if ( inSamePackage( fqcn ) || ( imports.contains( pureFqcn ) && canBeSimple ) ) {
result = unqualify( result ); // dequalify
- } else if ( inJavaLang( fqcn ) ) {
+ }
+ else if ( inJavaLang( fqcn ) ) {
result = result.substring( "java.lang.".length() );
}
- if(additionalTypePart!=null) {
+ if ( additionalTypePart != null ) {
result = result + additionalTypePart;
- }
-
+ }
+
result = result.replace( '$', '.' );
- return result;
+ return result;
}
-
+
public String staticImport(String fqcn, String member) {
String local = fqcn + "." + member;
- imports.add(local);
- staticImports.add(local);
-
- if(member.equals("*")) {
+ imports.add( local );
+ staticImports.add( local );
+
+ if ( member.equals( "*" ) ) {
return "";
- } else {
+ }
+ else {
return member;
}
}
-
+
private boolean inDefaultPackage(String className) {
return className.indexOf( "." ) < 0;
}
@@ -143,7 +148,7 @@
private boolean inSamePackage(String className) {
String other = qualifier( className );
return other == basePackage
- || (other != null && other.equals( basePackage ) );
+ || ( other != null && other.equals( basePackage ) );
}
private boolean inJavaLang(String className) {
@@ -152,33 +157,34 @@
public String generateImports() {
StringBuffer buf = new StringBuffer();
-
- for ( Iterator<String> imps = imports.iterator(); imps.hasNext(); ) {
- String next = imps.next();
- if(isPrimitive(next) || inDefaultPackage(next) || inJavaLang(next) || inSamePackage(next)) {
- // dont add automatically "imported" stuff
- } else {
- if(staticImports.contains(next)) {
- buf.append("import static " + next + ";\r\n");
- } else {
- buf.append("import " + next + ";\r\n");
- }
+
+ for ( String next : imports ) {
+ if ( isPrimitive( next ) || inDefaultPackage( next ) || inJavaLang( next ) || inSamePackage( next ) ) {
+ // dont add automatically "imported" stuff
+ }
+ else {
+ if ( staticImports.contains( next ) ) {
+ buf.append( "import static " + next + ";\r\n" );
}
+ else {
+ buf.append( "import " + next + ";\r\n" );
+ }
+ }
}
-
- if(buf.indexOf( "$" )>=0) {
+
+ if ( buf.indexOf( "$" ) >= 0 ) {
return buf.toString();
}
- return buf.toString();
+ return buf.toString();
}
-
+
public static String unqualify(String qualifiedName) {
- int loc = qualifiedName.lastIndexOf(".");
- return ( loc < 0 ) ? qualifiedName : qualifiedName.substring( qualifiedName.lastIndexOf(".") + 1 );
+ int loc = qualifiedName.lastIndexOf( "." );
+ return ( loc < 0 ) ? qualifiedName : qualifiedName.substring( qualifiedName.lastIndexOf( "." ) + 1 );
}
public static String qualifier(String qualifiedName) {
- int loc = qualifiedName.lastIndexOf(".");
+ int loc = qualifiedName.lastIndexOf( "." );
return ( loc < 0 ) ? "" : qualifiedName.substring( 0, loc );
}
}
Modified: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/JPAMetaModelEntityProcessor.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/JPAMetaModelEntityProcessor.java 2010-02-04 10:57:52 UTC (rev 18689)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/JPAMetaModelEntityProcessor.java 2010-02-04 16:12:07 UTC (rev 18690)
@@ -35,6 +35,7 @@
import javax.tools.Diagnostic;
import org.hibernate.jpamodelgen.annotation.AnnotationMetaEntity;
+import org.hibernate.jpamodelgen.model.MetaEntity;
import org.hibernate.jpamodelgen.util.TypeUtils;
import org.hibernate.jpamodelgen.xml.XmlParser;
@@ -103,17 +104,17 @@
}
private void createMetaModelClasses() {
- for ( MetaEntity entity : context.getMetaEntities().values() ) {
+ for ( MetaEntity entity : context.getMetaEntities()) {
context.logMessage( Diagnostic.Kind.OTHER, "Writing meta model for " + entity );
ClassWriter.writeFile( entity, context );
}
//process left over, in most cases is empty
for ( String className : context.getElementsAlreadyProcessed() ) {
- context.getMetaSuperclassAndEmbeddable().remove( className );
+ context.removeMetaSuperclassOrEmbeddable( className );
}
- for ( MetaEntity entity : context.getMetaSuperclassAndEmbeddable().values() ) {
+ for ( MetaEntity entity : context.getMetaSuperclassOrEmbeddable() ) {
context.logMessage( Diagnostic.Kind.OTHER, "Writing meta model for " + entity );
ClassWriter.writeFile( entity, context );
}
@@ -139,7 +140,7 @@
for ( AnnotationMirror mirror : annotationMirrors ) {
if ( element.getKind() == ElementKind.CLASS ) {
String fqn = ( ( TypeElement ) element ).getQualifiedName().toString();
- MetaEntity alreadyExistingMetaEntity = context.getMetaEntities().get( fqn );
+ MetaEntity alreadyExistingMetaEntity = context.getMetaEntity( fqn );
if ( alreadyExistingMetaEntity != null && alreadyExistingMetaEntity.isMetaComplete() ) {
String msg = "Skipping processing of annotations for " + fqn + " since xml configuration is metadata complete.";
context.logMessage( Diagnostic.Kind.OTHER, msg );
@@ -154,12 +155,12 @@
private void addMetaEntityToContext(AnnotationMirror mirror, AnnotationMetaEntity metaEntity) {
if ( TypeUtils.isAnnotationMirrorOfType( mirror, Entity.class ) ) {
- context.getMetaEntities().put( metaEntity.getQualifiedName(), metaEntity );
+ context.addMetaEntity( metaEntity.getQualifiedName(), metaEntity );
}
else if ( TypeUtils.isAnnotationMirrorOfType( mirror, MappedSuperclass.class )
|| TypeUtils.isAnnotationMirrorOfType( mirror, Embeddable.class ) ) {
- context.getMetaSuperclassAndEmbeddable().put( metaEntity.getQualifiedName(), metaEntity );
+ context.addMetaSuperclassOrEmbeddable( metaEntity.getQualifiedName(), metaEntity );
}
}
}
Deleted: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/MetaAttribute.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/MetaAttribute.java 2010-02-04 10:57:52 UTC (rev 18689)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/MetaAttribute.java 2010-02-04 16:12:07 UTC (rev 18690)
@@ -1,31 +0,0 @@
-// $Id$
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2008, Red Hat Middleware LLC, and individual contributors
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-* http://www.apache.org/licenses/LICENSE-2.0
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-package org.hibernate.jpamodelgen;
-
-/**
- * @author Hardy Ferentschik
- */
-public interface MetaAttribute {
- String getDeclarationString();
-
- String getMetaType();
-
- String getPropertyName();
-
- String getTypeDeclaration();
-}
Deleted: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/MetaCollection.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/MetaCollection.java 2010-02-04 10:57:52 UTC (rev 18689)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/MetaCollection.java 2010-02-04 16:12:07 UTC (rev 18690)
@@ -1,24 +0,0 @@
-// $Id$
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2008, Red Hat Middleware LLC, and individual contributors
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-* http://www.apache.org/licenses/LICENSE-2.0
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-package org.hibernate.jpamodelgen;
-
-/**
- * @author Hardy Ferentschik
- */
-public interface MetaCollection extends MetaAttribute {
-}
Deleted: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/MetaEntity.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/MetaEntity.java 2010-02-04 10:57:52 UTC (rev 18689)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/MetaEntity.java 2010-02-04 16:12:07 UTC (rev 18690)
@@ -1,47 +0,0 @@
-// $Id$
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2008, Red Hat Middleware LLC, and individual contributors
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-* http://www.apache.org/licenses/LICENSE-2.0
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-package org.hibernate.jpamodelgen;
-
-import javax.lang.model.element.Name;
-import javax.lang.model.element.TypeElement;
-import java.util.List;
-
-/**
- * @author Hardy Ferentschik
- */
-public interface MetaEntity extends ImportContext {
- String getSimpleName();
-
- String getQualifiedName();
-
- String getPackageName();
-
- List<MetaAttribute> getMembers();
-
- String generateImports();
-
- String importType(String fqcn);
-
- String staticImport(String fqcn, String member);
-
- String importType(Name qualifiedName);
-
- TypeElement getTypeElement();
-
- boolean isMetaComplete();
-}
Deleted: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/MetaSingleAttribute.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/MetaSingleAttribute.java 2010-02-04 10:57:52 UTC (rev 18689)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/MetaSingleAttribute.java 2010-02-04 16:12:07 UTC (rev 18690)
@@ -1,24 +0,0 @@
-// $Id$
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2008, Red Hat Middleware LLC, and individual contributors
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-* http://www.apache.org/licenses/LICENSE-2.0
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-package org.hibernate.jpamodelgen;
-
-/**
- * @author Hardy Ferentschik
- */
-public interface MetaSingleAttribute extends MetaAttribute {
-}
Modified: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationMetaAttribute.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationMetaAttribute.java 2010-02-04 10:57:52 UTC (rev 18689)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationMetaAttribute.java 2010-02-04 16:12:07 UTC (rev 18690)
@@ -22,7 +22,7 @@
import javax.lang.model.element.ElementKind;
import javax.lang.model.util.Elements;
-import org.hibernate.jpamodelgen.MetaAttribute;
+import org.hibernate.jpamodelgen.model.MetaAttribute;
/**
* @author Max Andersen
Modified: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationMetaCollection.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationMetaCollection.java 2010-02-04 10:57:52 UTC (rev 18689)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationMetaCollection.java 2010-02-04 16:12:07 UTC (rev 18690)
@@ -19,7 +19,7 @@
import javax.lang.model.element.Element;
-import org.hibernate.jpamodelgen.MetaCollection;
+import org.hibernate.jpamodelgen.model.MetaCollection;
/**
* @author Max Andersen
Modified: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationMetaEntity.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationMetaEntity.java 2010-02-04 10:57:52 UTC (rev 18689)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationMetaEntity.java 2010-02-04 16:12:07 UTC (rev 18690)
@@ -55,10 +55,10 @@
import javax.tools.Diagnostic;
import org.hibernate.jpamodelgen.Context;
-import org.hibernate.jpamodelgen.ImportContext;
+import org.hibernate.jpamodelgen.model.ImportContext;
import org.hibernate.jpamodelgen.ImportContextImpl;
-import org.hibernate.jpamodelgen.MetaAttribute;
-import org.hibernate.jpamodelgen.MetaEntity;
+import org.hibernate.jpamodelgen.model.MetaAttribute;
+import org.hibernate.jpamodelgen.model.MetaEntity;
import org.hibernate.jpamodelgen.MetaModelGenerationException;
import org.hibernate.jpamodelgen.util.TypeUtils;
Modified: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationMetaSingleAttribute.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationMetaSingleAttribute.java 2010-02-04 10:57:52 UTC (rev 18689)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationMetaSingleAttribute.java 2010-02-04 16:12:07 UTC (rev 18690)
@@ -19,7 +19,7 @@
import javax.lang.model.element.Element;
-import org.hibernate.jpamodelgen.MetaSingleAttribute;
+import org.hibernate.jpamodelgen.model.MetaSingleAttribute;
/**
* @author Max Andersen
Copied: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/model/ImportContext.java (from rev 18677, jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/ImportContext.java)
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/model/ImportContext.java (rev 0)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/model/ImportContext.java 2010-02-04 16:12:07 UTC (rev 18690)
@@ -0,0 +1,45 @@
+// $Id$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+* http://www.apache.org/licenses/LICENSE-2.0
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.hibernate.jpamodelgen.model;
+
+/**
+ * @author Max Andersen
+ * @author Hardy Ferentschik
+ * @author Emmanuel Bernard
+ */
+public interface ImportContext {
+
+ /**
+ * Add fqcn to the import list. Returns fqcn as needed in source code.
+ * Attempts to handle fqcn with array and generics references.
+ * <p/>
+ * e.g.
+ * java.util.Collection<org.marvel.Hulk> imports java.util.Collection and returns Collection
+ * org.marvel.Hulk[] imports org.marvel.Hulk and returns Hulk
+ *
+ * @param fqcn Fully qualified class name of the type to import.
+ *
+ * @return import string
+ */
+ public abstract String importType(String fqcn);
+
+ public abstract String staticImport(String fqcn, String member);
+
+ public abstract String generateImports();
+
+}
\ No newline at end of file
Property changes on: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/model/ImportContext.java
___________________________________________________________________
Name: svn:keywords
+ Id
Copied: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/model/MetaAttribute.java (from rev 18677, jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/MetaAttribute.java)
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/model/MetaAttribute.java (rev 0)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/model/MetaAttribute.java 2010-02-04 16:12:07 UTC (rev 18690)
@@ -0,0 +1,31 @@
+// $Id$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+* http://www.apache.org/licenses/LICENSE-2.0
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.hibernate.jpamodelgen.model;
+
+/**
+ * @author Hardy Ferentschik
+ */
+public interface MetaAttribute {
+ String getDeclarationString();
+
+ String getMetaType();
+
+ String getPropertyName();
+
+ String getTypeDeclaration();
+}
Property changes on: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/model/MetaAttribute.java
___________________________________________________________________
Name: svn:keywords
+ Id
Copied: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/model/MetaCollection.java (from rev 18677, jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/MetaCollection.java)
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/model/MetaCollection.java (rev 0)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/model/MetaCollection.java 2010-02-04 16:12:07 UTC (rev 18690)
@@ -0,0 +1,24 @@
+// $Id$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+* http://www.apache.org/licenses/LICENSE-2.0
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.hibernate.jpamodelgen.model;
+
+/**
+ * @author Hardy Ferentschik
+ */
+public interface MetaCollection extends MetaAttribute {
+}
Property changes on: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/model/MetaCollection.java
___________________________________________________________________
Name: svn:keywords
+ Id
Copied: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/model/MetaEntity.java (from rev 18677, jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/MetaEntity.java)
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/model/MetaEntity.java (rev 0)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/model/MetaEntity.java 2010-02-04 16:12:07 UTC (rev 18690)
@@ -0,0 +1,47 @@
+// $Id$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+* http://www.apache.org/licenses/LICENSE-2.0
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.hibernate.jpamodelgen.model;
+
+import java.util.List;
+import javax.lang.model.element.Name;
+import javax.lang.model.element.TypeElement;
+
+/**
+ * @author Hardy Ferentschik
+ */
+public interface MetaEntity extends ImportContext {
+ String getSimpleName();
+
+ String getQualifiedName();
+
+ String getPackageName();
+
+ List<MetaAttribute> getMembers();
+
+ String generateImports();
+
+ String importType(String fqcn);
+
+ String staticImport(String fqcn, String member);
+
+ String importType(Name qualifiedName);
+
+ TypeElement getTypeElement();
+
+ boolean isMetaComplete();
+}
Property changes on: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/model/MetaEntity.java
___________________________________________________________________
Name: svn:keywords
+ Id
Copied: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/model/MetaSingleAttribute.java (from rev 18677, jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/MetaSingleAttribute.java)
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/model/MetaSingleAttribute.java (rev 0)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/model/MetaSingleAttribute.java 2010-02-04 16:12:07 UTC (rev 18690)
@@ -0,0 +1,24 @@
+// $Id$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+* http://www.apache.org/licenses/LICENSE-2.0
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.hibernate.jpamodelgen.model;
+
+/**
+ * @author Hardy Ferentschik
+ */
+public interface MetaSingleAttribute extends MetaAttribute {
+}
Property changes on: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/model/MetaSingleAttribute.java
___________________________________________________________________
Name: svn:keywords
+ Id
Modified: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaAttribute.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaAttribute.java 2010-02-04 10:57:52 UTC (rev 18689)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaAttribute.java 2010-02-04 16:12:07 UTC (rev 18690)
@@ -18,7 +18,7 @@
package org.hibernate.jpamodelgen.xml;
-import org.hibernate.jpamodelgen.MetaAttribute;
+import org.hibernate.jpamodelgen.model.MetaAttribute;
/**
* @author Hardy Ferentschik
Modified: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaCollection.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaCollection.java 2010-02-04 10:57:52 UTC (rev 18689)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaCollection.java 2010-02-04 16:12:07 UTC (rev 18690)
@@ -17,7 +17,7 @@
*/
package org.hibernate.jpamodelgen.xml;
-import org.hibernate.jpamodelgen.MetaCollection;
+import org.hibernate.jpamodelgen.model.MetaCollection;
/**
* @author Hardy Ferentschik
Modified: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaEntity.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaEntity.java 2010-02-04 10:57:52 UTC (rev 18689)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaEntity.java 2010-02-04 16:12:07 UTC (rev 18690)
@@ -29,10 +29,10 @@
import javax.tools.Diagnostic;
import org.hibernate.jpamodelgen.Context;
-import org.hibernate.jpamodelgen.ImportContext;
+import org.hibernate.jpamodelgen.model.ImportContext;
import org.hibernate.jpamodelgen.ImportContextImpl;
-import org.hibernate.jpamodelgen.MetaAttribute;
-import org.hibernate.jpamodelgen.MetaEntity;
+import org.hibernate.jpamodelgen.model.MetaAttribute;
+import org.hibernate.jpamodelgen.model.MetaEntity;
import org.hibernate.jpamodelgen.MetaModelGenerationException;
import org.hibernate.jpamodelgen.util.TypeUtils;
import org.hibernate.jpamodelgen.xml.jaxb.Attributes;
Modified: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaSingleAttribute.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaSingleAttribute.java 2010-02-04 10:57:52 UTC (rev 18689)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaSingleAttribute.java 2010-02-04 16:12:07 UTC (rev 18690)
@@ -17,7 +17,7 @@
*/
package org.hibernate.jpamodelgen.xml;
-import org.hibernate.jpamodelgen.MetaSingleAttribute;
+import org.hibernate.jpamodelgen.model.MetaSingleAttribute;
/**
* @author Hardy Ferentschik
Modified: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlParser.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlParser.java 2010-02-04 10:57:52 UTC (rev 18689)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlParser.java 2010-02-04 16:12:07 UTC (rev 18690)
@@ -20,6 +20,7 @@
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
+import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.lang.model.element.TypeElement;
@@ -55,12 +56,28 @@
private static final AccessType DEFAULT_XML_ACCESS_TYPE = AccessType.PROPERTY;
private Context context;
+ private List<EntityMappings> entityMappings;
+ private AccessType defaultAccessType = DEFAULT_XML_ACCESS_TYPE;
public XmlParser(Context context) {
this.context = context;
+ this.entityMappings = new ArrayList<EntityMappings>();
}
public void parsePersistenceXml() {
+ collectAllEntityMappings();
+ determineDefaultAccessTypeAndMetaCompleteness();
+
+ for ( EntityMappings mappings : entityMappings ) {
+ String packageName = mappings.getPackage();
+ AccessType entityAccessType = determineEntityAccessType( mappings );
+ parseEntities( mappings.getEntity(), packageName, entityAccessType );
+ parseEmbeddable( mappings.getEmbeddable(), packageName, entityAccessType );
+ parseMappedSuperClass( mappings.getMappedSuperclass(), packageName, entityAccessType );
+ }
+ }
+
+ private void collectAllEntityMappings() {
Persistence persistence = parseXml(
context.getPersistenceXmlLocation(), Persistence.class, PERSISTENCE_XML_XSD
);
@@ -69,38 +86,29 @@
for ( Persistence.PersistenceUnit unit : persistenceUnits ) {
List<String> mappingFiles = unit.getMappingFile();
for ( String mappingFile : mappingFiles ) {
- parsingOrmXml( mappingFile );
+ loadEntityMappings( mappingFile );
}
}
}
// /META-INF/orm.xml is implicit
- parsingOrmXml( ORM_XML );
+ loadEntityMappings( ORM_XML );
// not really part of the official spec, but the processor allows to specify mapping files directly as
// command line options
for ( String optionalOrmFiles : context.getOrmXmlFiles() ) {
- parsingOrmXml( optionalOrmFiles );
+ loadEntityMappings( optionalOrmFiles );
}
}
- private void parsingOrmXml(String resource) {
- EntityMappings mappings = parseXml( resource, EntityMappings.class, ORM_XSD );
- if ( mappings == null ) {
- return;
+ private void loadEntityMappings(String resource) {
+ EntityMappings mapping = parseXml( resource, EntityMappings.class, ORM_XSD );
+ if ( mapping != null ) {
+ entityMappings.add( mapping );
}
-
- AccessType accessType = determineGlobalAccessType( mappings );
- context.setPersistenceUnitCompletelyXmlConfigured( determineGlobalXmlMetadataCompleteness( mappings ) );
-
- parseEntities( mappings, accessType );
- parseEmbeddable( mappings, accessType );
- parseMappedSuperClass( mappings, accessType );
}
- private void parseEntities(EntityMappings mappings, AccessType accessType) {
- String packageName = mappings.getPackage();
- Collection<Entity> entities = mappings.getEntity();
+ private void parseEntities(Collection<Entity> entities, String packageName, AccessType accessType) {
for ( Entity entity : entities ) {
String fullyQualifiedClassName = packageName + "." + entity.getClazz();
@@ -117,19 +125,17 @@
context
);
- if ( context.getMetaEntities().containsKey( fullyQualifiedClassName ) ) {
+ if ( context.containsMetaEntity( fullyQualifiedClassName ) ) {
context.logMessage(
Diagnostic.Kind.WARNING,
fullyQualifiedClassName + " was already processed once. Skipping second occurance."
);
}
- context.getMetaEntities().put( fullyQualifiedClassName, metaEntity );
+ context.addMetaEntity( fullyQualifiedClassName, metaEntity );
}
}
- private void parseEmbeddable(EntityMappings mappings, AccessType accessType) {
- String packageName = mappings.getPackage();
- Collection<org.hibernate.jpamodelgen.xml.jaxb.Embeddable> embeddables = mappings.getEmbeddable();
+ private void parseEmbeddable(Collection<org.hibernate.jpamodelgen.xml.jaxb.Embeddable> embeddables, String packageName, AccessType accessType) {
for ( org.hibernate.jpamodelgen.xml.jaxb.Embeddable embeddable : embeddables ) {
String fullyQualifiedClassName = packageName + "." + embeddable.getClazz();
@@ -146,20 +152,18 @@
context
);
- if ( context.getMetaSuperclassAndEmbeddable().containsKey( fullyQualifiedClassName ) ) {
+ if ( context.containsMetaSuperclassOrEmbeddable( fullyQualifiedClassName ) ) {
context.logMessage(
Diagnostic.Kind.WARNING,
fullyQualifiedClassName + " was already processed once. Skipping second occurance."
);
}
- context.getMetaSuperclassAndEmbeddable().put( fullyQualifiedClassName, metaEntity );
+ context.addMetaSuperclassOrEmbeddable( fullyQualifiedClassName, metaEntity );
}
}
- private void parseMappedSuperClass(EntityMappings mappings, AccessType accessType) {
- String packageName = mappings.getPackage();
- Collection<org.hibernate.jpamodelgen.xml.jaxb.MappedSuperclass> mappedSuperClasses = mappings.getMappedSuperclass();
+ private void parseMappedSuperClass(Collection<org.hibernate.jpamodelgen.xml.jaxb.MappedSuperclass> mappedSuperClasses, String packageName, AccessType accessType) {
for ( org.hibernate.jpamodelgen.xml.jaxb.MappedSuperclass mappedSuperClass : mappedSuperClasses ) {
String fullyQualifiedClassName = packageName + "." + mappedSuperClass.getClazz();
@@ -176,13 +180,13 @@
context
);
- if ( context.getMetaSuperclassAndEmbeddable().containsKey( fullyQualifiedClassName ) ) {
+ if ( context.containsMetaSuperclassOrEmbeddable( fullyQualifiedClassName ) ) {
context.logMessage(
Diagnostic.Kind.WARNING,
fullyQualifiedClassName + " was already processed once. Skipping second occurance."
);
}
- context.getMetaSuperclassAndEmbeddable().put( fullyQualifiedClassName, metaEntity );
+ context.addMetaSuperclassOrEmbeddable( fullyQualifiedClassName, metaEntity );
}
}
@@ -193,7 +197,8 @@
* @param clazz The type of jaxb node to return
* @param schemaName The schema to validate against (can be {@code null});
*
- * @return The top level jaxb instance contained in the xml file or {@code null} in case the file could not be found.
+ * @return The top level jaxb instance contained in the xml file or {@code null} in case the file could not be found
+ * or could not be unmarshalled.
*/
private <T> T parseXml(String resource, Class<T> clazz, String schemaName) {
@@ -292,36 +297,52 @@
return utils.getTypeElement( fullyQualifiedClassName );
}
- private AccessType determineGlobalAccessType(EntityMappings mappings) {
- AccessType accessType = DEFAULT_XML_ACCESS_TYPE;
-
+ private AccessType determineEntityAccessType(EntityMappings mappings) {
+ AccessType accessType = defaultAccessType;
if ( mappings.getAccess() != null ) {
accessType = mapXmlAccessTypeToJpaAccessType( mappings.getAccess() );
- return accessType; // no need to check persistence unit default
}
+ return accessType;
+ }
- PersistenceUnitMetadata meta = mappings.getPersistenceUnitMetadata();
- if ( meta != null ) {
- PersistenceUnitDefaults persistenceUnitDefaults = meta.getPersistenceUnitDefaults();
- if ( persistenceUnitDefaults != null ) {
- org.hibernate.jpamodelgen.xml.jaxb.AccessType xmlAccessType = persistenceUnitDefaults.getAccess();
- if ( xmlAccessType != null ) {
- accessType = mapXmlAccessTypeToJpaAccessType( xmlAccessType );
+ /**
+ * Determines the default access type as specified in the <i>persistence-unit-defaults</i> as well as whether the
+ * xml configuration is complete and annotations should be ignored.
+ * <p/>
+ * Note, the spec says:
+ * <ul>
+ * <li>The persistence-unit-metadata element contains metadata for the entire persistence unit. It is
+ * undefined if this element occurs in multiple mapping files within the same persistence unit.</li>
+ * <li>If the xml-mapping-metadata-complete subelement is specified, the complete set of mapping
+ * metadata for the persistence unit is contained in the XML mapping files for the persistence unit, and any
+ * persistence annotations on the classes are ignored.</li>
+ * <li>When the xml-mapping-metadata-complete element is specified, any metadata-complete attributes specified
+ * within the entity, mapped-superclass, and embeddable elements are ignored.<li>
+ * </ul>
+ */
+ private void determineDefaultAccessTypeAndMetaCompleteness() {
+ for ( EntityMappings mappings : entityMappings ) {
+ PersistenceUnitMetadata meta = mappings.getPersistenceUnitMetadata();
+ if ( meta != null ) {
+ if ( meta.getXmlMappingMetadataComplete() != null ) {
+ context.setPersistenceUnitCompletelyXmlConfigured( true );
}
+
+ PersistenceUnitDefaults persistenceUnitDefaults = meta.getPersistenceUnitDefaults();
+ if ( persistenceUnitDefaults != null ) {
+ org.hibernate.jpamodelgen.xml.jaxb.AccessType xmlAccessType = persistenceUnitDefaults.getAccess();
+ if ( xmlAccessType != null ) {
+ defaultAccessType = mapXmlAccessTypeToJpaAccessType( xmlAccessType );
+ }
+ }
+ // for simplicity we stop looking for PersistenceUnitMetadata instances. We assume that all files
+ // are consistent in the data specified in PersistenceUnitMetadata. If not the behaviour is not specified
+ // anyways. It is up to the JPA provider to handle this when bootstrapping
+ break;
}
}
- return accessType;
}
- private boolean determineGlobalXmlMetadataCompleteness(EntityMappings mappings) {
- boolean metadataComplete = false;
- PersistenceUnitMetadata puMetadata = mappings.getPersistenceUnitMetadata();
- if ( puMetadata != null && puMetadata.getXmlMappingMetadataComplete() != null ) {
- metadataComplete = true;
- }
- return metadataComplete;
- }
-
private AccessType mapXmlAccessTypeToJpaAccessType(org.hibernate.jpamodelgen.xml.jaxb.AccessType xmlAccessType) {
switch ( xmlAccessType ) {
case FIELD: {
[View Less]
15 years, 1 month