Hibernate SVN: r18664 - in jpamodelgen/trunk/src: test/java/org/hibernate/jpamodelgen/test/accesstype and 9 other directories.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2010-01-28 11:56:51 -0500 (Thu, 28 Jan 2010)
New Revision: 18664
Added:
jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/xmlmapped/FakeHero.java
jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/xmlmapped/Superhero.java
Modified:
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaEntity.java
jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/accesstype/AccessTypeTest.java
jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/arraytype/ArrayTest.java
jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/elementcollection/ElementCollectionTest.java
jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/generics/GenericsTest.java
jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/inheritance/InheritanceTest.java
jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/rawTypes/RawTypesTest.java
jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/util/CompilationTest.java
jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/util/TestUtil.java
jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/xmlmapped/Boy.java
jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/xmlmapped/XmlMappingTest.java
jpamodelgen/trunk/src/test/resources/org/hibernate/jpamodelgen/test/xmlmapped/boy.xml
jpamodelgen/trunk/src/test/suite/unit-tests.xml
Log:
METAGEN-17 - Consider XML for targetEntity
Modified: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaEntity.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaEntity.java 2010-01-28 09:35:59 UTC (rev 18663)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaEntity.java 2010-01-28 16:56:51 UTC (rev 18664)
@@ -39,6 +39,7 @@
import org.hibernate.jpamodelgen.xml.jaxb.EmbeddableAttributes;
import org.hibernate.jpamodelgen.xml.jaxb.Entity;
import org.hibernate.jpamodelgen.xml.jaxb.Id;
+import org.hibernate.jpamodelgen.xml.jaxb.ManyToMany;
import org.hibernate.jpamodelgen.xml.jaxb.ManyToOne;
import org.hibernate.jpamodelgen.xml.jaxb.MappedSuperclass;
import org.hibernate.jpamodelgen.xml.jaxb.OneToMany;
@@ -87,7 +88,6 @@
this.importContext = new ImportContextImpl( getPackageName() );
this.element = element;
Attributes attributes = mappedSuperclass.getAttributes();
-
parseAttributes( attributes );
}
@@ -98,39 +98,7 @@
this.importContext = new ImportContextImpl( getPackageName() );
this.element = element;
EmbeddableAttributes attributes = embeddable.getAttributes();
-
- XmlMetaSingleAttribute attribute;
- for ( Basic basic : attributes.getBasic() ) {
- attribute = new XmlMetaSingleAttribute( this, basic.getName(), getType( basic.getName(), null ) );
- members.add( attribute );
- }
-
- for ( ManyToOne manyToOne : attributes.getManyToOne() ) {
- attribute = new XmlMetaSingleAttribute(
- this, manyToOne.getName(), getType( manyToOne.getName(), manyToOne.getTargetEntity() )
- );
- members.add( attribute );
- }
-
- for ( OneToOne oneToOne : attributes.getOneToOne() ) {
- attribute = new XmlMetaSingleAttribute(
- this, oneToOne.getName(), getType( oneToOne.getName(), oneToOne.getTargetEntity() )
- );
- members.add( attribute );
- }
-
- XmlMetaCollection metaCollection;
- for ( OneToMany oneToMany : attributes.getOneToMany() ) {
- String[] types = getCollectionType( oneToMany.getName(), oneToMany.getTargetEntity() );
- metaCollection = new XmlMetaCollection( this, oneToMany.getName(), types[0], types[1] );
- members.add( metaCollection );
- }
-
- for ( ElementCollection collection : attributes.getElementCollection() ) {
- String[] types = getCollectionType( collection.getName(), collection.getTargetClass() );
- metaCollection = new XmlMetaCollection( this, collection.getName(), types[0], types[1] );
- members.add( metaCollection );
- }
+ parseEmbeddableAttributes( attributes );
}
public String getSimpleName() {
@@ -272,6 +240,12 @@
}
XmlMetaCollection metaCollection;
+ for ( ManyToMany manyToMany : attributes.getManyToMany() ) {
+ String[] types = getCollectionType( manyToMany.getName(), manyToMany.getTargetEntity() );
+ metaCollection = new XmlMetaCollection( this, manyToMany.getName(), types[0], types[1] );
+ members.add( metaCollection );
+ }
+
for ( OneToMany oneToMany : attributes.getOneToMany() ) {
String[] types = getCollectionType( oneToMany.getName(), oneToMany.getTargetEntity() );
metaCollection = new XmlMetaCollection( this, oneToMany.getName(), types[0], types[1] );
@@ -284,4 +258,45 @@
members.add( metaCollection );
}
}
+
+ private void parseEmbeddableAttributes(EmbeddableAttributes attributes) {
+ XmlMetaSingleAttribute attribute;
+ for ( Basic basic : attributes.getBasic() ) {
+ attribute = new XmlMetaSingleAttribute( this, basic.getName(), getType( basic.getName(), null ) );
+ members.add( attribute );
+ }
+
+ for ( ManyToOne manyToOne : attributes.getManyToOne() ) {
+ attribute = new XmlMetaSingleAttribute(
+ this, manyToOne.getName(), getType( manyToOne.getName(), manyToOne.getTargetEntity() )
+ );
+ members.add( attribute );
+ }
+
+ for ( OneToOne oneToOne : attributes.getOneToOne() ) {
+ attribute = new XmlMetaSingleAttribute(
+ this, oneToOne.getName(), getType( oneToOne.getName(), oneToOne.getTargetEntity() )
+ );
+ members.add( attribute );
+ }
+
+ XmlMetaCollection metaCollection;
+ for ( ManyToMany manyToMany : attributes.getManyToMany() ) {
+ String[] types = getCollectionType( manyToMany.getName(), manyToMany.getTargetEntity() );
+ metaCollection = new XmlMetaCollection( this, manyToMany.getName(), types[0], types[1] );
+ members.add( metaCollection );
+ }
+
+ for ( OneToMany oneToMany : attributes.getOneToMany() ) {
+ String[] types = getCollectionType( oneToMany.getName(), oneToMany.getTargetEntity() );
+ metaCollection = new XmlMetaCollection( this, oneToMany.getName(), types[0], types[1] );
+ members.add( metaCollection );
+ }
+
+ for ( ElementCollection collection : attributes.getElementCollection() ) {
+ String[] types = getCollectionType( collection.getName(), collection.getTargetClass() );
+ metaCollection = new XmlMetaCollection( this, collection.getName(), types[0], types[1] );
+ members.add( metaCollection );
+ }
+ }
}
Modified: jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/accesstype/AccessTypeTest.java
===================================================================
--- jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/accesstype/AccessTypeTest.java 2010-01-28 09:35:59 UTC (rev 18663)
+++ jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/accesstype/AccessTypeTest.java 2010-01-28 16:56:51 UTC (rev 18664)
@@ -20,10 +20,12 @@
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
-import static org.hibernate.jpamodelgen.test.util.TestUtil.assertAbsenceOfField;
-import static org.hibernate.jpamodelgen.test.util.TestUtil.assertFieldType;
-import static org.hibernate.jpamodelgen.test.util.TestUtil.assertPresenceOfField;
+import org.hibernate.jpamodelgen.test.util.TestUtil;
+import static org.hibernate.jpamodelgen.test.util.TestUtil.assertAbsenceOfFieldInMetamodelFor;
+import static org.hibernate.jpamodelgen.test.util.TestUtil.assertFieldTypeInMetaModelFor;
+import static org.hibernate.jpamodelgen.test.util.TestUtil.assertPresenceOfFieldInMetamodelFor;
+
/**
* @author Emmanuel Bernard
* @author Hardy Ferentschik
@@ -31,58 +33,58 @@
public class AccessTypeTest extends CompilationTest {
@Test
- public void testExcludeTransientFieldAndStatic() throws Exception {
- assertAbsenceOfField( Product.class.getName() + "_", "nonPersistent" );
- assertAbsenceOfField( Product.class.getName() + "_", "nonPersistent2" );
+ public void testExcludeTransientFieldAndStatic() {
+ TestUtil.assertAbsenceOfFieldInMetamodelFor( Product.class, "nonPersistent" );
+ TestUtil.assertAbsenceOfFieldInMetamodelFor( Product.class, "nonPersistent2" );
}
@Test
- public void testDefaultAccessTypeOnEntity() throws Exception {
- assertAbsenceOfField( User.class.getName() + "_", "nonPersistent" );
+ public void testDefaultAccessTypeOnEntity() {
+ TestUtil.assertAbsenceOfFieldInMetamodelFor( User.class, "nonPersistent" );
}
@Test
- public void testDefaultAccessTypeForSubclassOfEntity() throws Exception {
- assertAbsenceOfField( Customer.class.getName() + "_", "nonPersistent" );
+ public void testDefaultAccessTypeForSubclassOfEntity() {
+ TestUtil.assertAbsenceOfFieldInMetamodelFor( Customer.class, "nonPersistent" );
}
@Test
- public void testDefaultAccessTypeForEmbeddable() throws Exception {
- assertAbsenceOfField( Detail.class.getName() + "_", "nonPersistent" );
+ public void testDefaultAccessTypeForEmbeddable() {
+ TestUtil.assertAbsenceOfFieldInMetamodelFor( Detail.class, "nonPersistent" );
}
@Test
- public void testInheritedAccessTypeForEmbeddable() throws Exception {
- assertAbsenceOfField( Country.class.getName() + "_", "nonPersistent" );
- assertAbsenceOfField(
- Pet.class.getName() + "_", "nonPersistent", "Collection of embeddable not taken care of"
+ public void testInheritedAccessTypeForEmbeddable() {
+ TestUtil.assertAbsenceOfFieldInMetamodelFor( Country.class, "nonPersistent" );
+ assertAbsenceOfFieldInMetamodelFor(
+ Pet.class, "nonPersistent", "Collection of embeddable not taken care of"
);
}
@Test
- public void testDefaultAccessTypeForMappedSuperclass() throws Exception {
- assertAbsenceOfField( Detail.class.getName() + "_", "volume" );
+ public void testDefaultAccessTypeForMappedSuperclass() {
+ TestUtil.assertAbsenceOfFieldInMetamodelFor( Detail.class, "volume" );
}
@Test
- public void testExplicitAccessTypeAndDefaultFromRootEntity() throws Exception {
- assertAbsenceOfField(
- LivingBeing.class.getName() + "_",
+ public void testExplicitAccessTypeAndDefaultFromRootEntity() {
+ assertAbsenceOfFieldInMetamodelFor(
+ LivingBeing.class,
"nonPersistent",
"explicit access type on mapped superclass"
);
- assertAbsenceOfField( Hominidae.class.getName() + "_", "nonPersistent", "explicit access type on entity" );
- assertAbsenceOfField(
- Human.class.getName() + "_",
+ assertAbsenceOfFieldInMetamodelFor( Hominidae.class, "nonPersistent", "explicit access type on entity" );
+ assertAbsenceOfFieldInMetamodelFor(
+ Human.class,
"nonPersistent",
"proper inheritance from root entity access type"
);
}
@Test
- public void testMemberAccessType() throws Exception {
- assertPresenceOfField( Customer.class.getName() + "_", "goodPayer", "access type overriding" );
- assertFieldType( Customer.class.getName() + "_", "goodPayer", Boolean.class, "access type overriding" );
+ public void testMemberAccessType() {
+ assertPresenceOfFieldInMetamodelFor( Customer.class, "goodPayer", "access type overriding" );
+ assertFieldTypeInMetaModelFor( Customer.class, "goodPayer", Boolean.class, "access type overriding" );
}
@Override
Modified: jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/arraytype/ArrayTest.java
===================================================================
--- jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/arraytype/ArrayTest.java 2010-01-28 09:35:59 UTC (rev 18663)
+++ jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/arraytype/ArrayTest.java 2010-01-28 16:56:51 UTC (rev 18664)
@@ -20,27 +20,29 @@
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
-import static org.hibernate.jpamodelgen.test.util.TestUtil.assertFieldType;
+import static org.hibernate.jpamodelgen.test.util.TestUtil.assertFieldTypeInMetaModelFor;
+
/**
* @author Hardy Ferentschik
*/
public class ArrayTest extends CompilationTest {
+
/**
* METAGEN-2
*/
@Test
- public void testPrimitiveArray() throws Exception {
- assertFieldType( Image.class.getName() + "_", "data", byte[].class, "Wrong type for field." );
+ public void testPrimitiveArray() {
+ assertFieldTypeInMetaModelFor( Image.class, "data", byte[].class, "Wrong type for field." );
}
/**
* METAGEN-2
*/
@Test
- public void testIntegerArray() throws Exception {
- assertFieldType(
- TemperatureSamples.class.getName() + "_", "samples", Integer[].class, "Wrong type for field."
+ public void testIntegerArray() {
+ assertFieldTypeInMetaModelFor(
+ TemperatureSamples.class, "samples", Integer[].class, "Wrong type for field."
);
}
Modified: jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/elementcollection/ElementCollectionTest.java
===================================================================
--- jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/elementcollection/ElementCollectionTest.java 2010-01-28 09:35:59 UTC (rev 18663)
+++ jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/elementcollection/ElementCollectionTest.java 2010-01-28 16:56:51 UTC (rev 18664)
@@ -20,10 +20,10 @@
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
-import static org.hibernate.jpamodelgen.test.util.TestUtil.assertClassGenerated;
-import static org.hibernate.jpamodelgen.test.util.TestUtil.assertClassNotFound;
-import static org.hibernate.jpamodelgen.test.util.TestUtil.assertNoGeneratedSourceFile;
+import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassGeneratedFor;
+import static org.hibernate.jpamodelgen.test.util.TestUtil.assertNoSourceFileGeneratedFor;
+
/**
* @author Hardy Ferentschik
*/
@@ -33,10 +33,10 @@
*/
@Test
public void testElementCollectionOnMap() {
- assertClassGenerated( House.class.getName() + "_" );
- assertClassGenerated( House.class.getName() + "_" );
+ assertMetamodelClassGeneratedFor( House.class );
+ assertMetamodelClassGeneratedFor( House.class );
// side effect of METAGEN-8 was that a meta class for String was created!
- assertNoGeneratedSourceFile( String.class.getName() + "_" );
+ assertNoSourceFileGeneratedFor( String.class );
}
@Override
Modified: jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/generics/GenericsTest.java
===================================================================
--- jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/generics/GenericsTest.java 2010-01-28 09:35:59 UTC (rev 18663)
+++ jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/generics/GenericsTest.java 2010-01-28 16:56:51 UTC (rev 18664)
@@ -19,11 +19,9 @@
import org.testng.annotations.Test;
-import org.hibernate.jpamodelgen.test.elementcollection.House;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
-import static org.hibernate.jpamodelgen.test.util.TestUtil.assertClassGenerated;
-import static org.hibernate.jpamodelgen.test.util.TestUtil.assertNoGeneratedSourceFile;
+import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassGeneratedFor;
/**
* @author Emmanuel Bernard
@@ -32,8 +30,8 @@
@Test
public void testGenerics() {
- assertClassGenerated( Parent.class.getName() + "_" );
- assertClassGenerated( Child.class.getName() + "_" );
+ assertMetamodelClassGeneratedFor( Parent.class );
+ assertMetamodelClassGeneratedFor( Child.class );
}
@Override
Modified: jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/inheritance/InheritanceTest.java
===================================================================
--- jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/inheritance/InheritanceTest.java 2010-01-28 09:35:59 UTC (rev 18663)
+++ jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/inheritance/InheritanceTest.java 2010-01-28 16:56:51 UTC (rev 18664)
@@ -20,8 +20,9 @@
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
-import static org.hibernate.jpamodelgen.test.util.TestUtil.assertSuperClass;
+import static org.hibernate.jpamodelgen.test.util.TestUtil.assertSuperClassRelationShipInMetamodel;
+
/**
* @author Emmanuel Bernard
* @author Hardy Ferentschik
@@ -29,15 +30,13 @@
public class InheritanceTest extends CompilationTest {
@Test
public void testSuperEntity() throws Exception {
- assertSuperClass(
- Customer.class.getName() + "_", User.class.getName() + "_"
- );
+ assertSuperClassRelationShipInMetamodel( Customer.class, User.class );
}
@Test
public void testMappedSuperclass() throws Exception {
- assertSuperClass( House.class.getName() + "_", Building.class.getName() + "_" );
- assertSuperClass( Building.class.getName() + "_", Area.class.getName() + "_" );
+ assertSuperClassRelationShipInMetamodel( House.class, Building.class );
+ assertSuperClassRelationShipInMetamodel( Building.class, Area.class );
}
@Override
Modified: jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/rawTypes/RawTypesTest.java
===================================================================
--- jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/rawTypes/RawTypesTest.java 2010-01-28 09:35:59 UTC (rev 18663)
+++ jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/rawTypes/RawTypesTest.java 2010-01-28 16:56:51 UTC (rev 18664)
@@ -21,7 +21,7 @@
import org.hibernate.jpamodelgen.test.util.CompilationTest;
-import static org.hibernate.jpamodelgen.test.util.TestUtil.assertClassGenerated;
+import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassGeneratedFor;
/**
* @author Emmanuel Bernard
@@ -30,8 +30,8 @@
@Test
public void testGenerics() {
- assertClassGenerated( DeskWithRawType.class.getName() + "_" );
- assertClassGenerated( EmployeeWithRawType.class.getName() + "_" );
+ assertMetamodelClassGeneratedFor( DeskWithRawType.class );
+ assertMetamodelClassGeneratedFor( EmployeeWithRawType.class );
}
@Override
Modified: jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/util/CompilationTest.java
===================================================================
--- jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/util/CompilationTest.java 2010-01-28 09:35:59 UTC (rev 18663)
+++ jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/util/CompilationTest.java 2010-01-28 16:56:51 UTC (rev 18664)
@@ -55,6 +55,7 @@
public CompilationTest() {
try {
+ TestUtil.clearOutputFolder();
compile();
}
catch ( Exception e ) {
Modified: jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/util/TestUtil.java
===================================================================
--- jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/util/TestUtil.java 2010-01-28 09:35:59 UTC (rev 18663)
+++ jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/util/TestUtil.java 2010-01-28 16:56:51 UTC (rev 18664)
@@ -18,15 +18,13 @@
package org.hibernate.jpamodelgen.test.util;
import java.io.File;
-import java.io.FilenameFilter;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
-import java.util.Collection;
-import java.util.Vector;
import org.testng.Assert;
+
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
@@ -38,6 +36,7 @@
public class TestUtil {
private static final String PATH_SEPARATOR = System.getProperty( "file.separator" );
+ private static final String META_MODEL_CLASS_POSTFIX = "_";
private static final String outBaseDir;
static {
@@ -51,51 +50,54 @@
private TestUtil() {
}
- public static void assertClassGenerated(String className) {
- try {
- assertNotNull( Class.forName( className ) );
+ public static void clearOutputFolder() {
+ File outDir = new File( outBaseDir );
+ File[] files = outDir.listFiles();
+ for ( File file : files ) {
+ file.delete();
}
- catch ( ClassNotFoundException e ) {
- fail( className + " was not generated." );
- }
}
- public static void assertClassNotFound(String className) {
+ /**
+ * Asserts that a metamodel class for the specified class got generated.
+ *
+ * @param clazz the class for which a metamodel class should have been generated.
+ */
+ public static void assertMetamodelClassGeneratedFor(Class<?> clazz) {
+ assertNotNull( clazz, "Class parameter cannot be null" );
+ String metaModelClassName = clazz.getName() + META_MODEL_CLASS_POSTFIX;
try {
- Class.forName( className );
- fail( "Class " + className + " should not have been found." );
+ assertNotNull( Class.forName( metaModelClassName ) );
}
catch ( ClassNotFoundException e ) {
- // success
+ fail( metaModelClassName + " was not generated." );
}
}
- public static void assertNoGeneratedSourceFile(String className) {
+ public static void assertNoSourceFileGeneratedFor(Class<?> clazz) {
+ assertNotNull( clazz, "Class parameter cannot be null" );
+ String metaModelClassName = clazz.getName() + META_MODEL_CLASS_POSTFIX;
// generate the file name
- String fileName = className.replace( ".", PATH_SEPARATOR );
+ String fileName = metaModelClassName.replace( ".", PATH_SEPARATOR );
fileName = fileName.concat( ".java" );
- File sourceFile = new File(outBaseDir + PATH_SEPARATOR + fileName);
- assertFalse(sourceFile.exists(), "There should be no source file: " + fileName);
-
+ File sourceFile = new File( outBaseDir + PATH_SEPARATOR + fileName );
+ assertFalse( sourceFile.exists(), "There should be no source file: " + fileName );
}
- public static void assertAbsenceOfField(String className, String fieldName) throws ClassNotFoundException {
- assertAbsenceOfField( className, fieldName, "field should not be persistent" );
+ public static void assertAbsenceOfFieldInMetamodelFor(Class<?> clazz, String fieldName) {
+ assertAbsenceOfFieldInMetamodelFor( clazz, fieldName, "field should not be persistent" );
}
- public static void assertAbsenceOfField(String className, String fieldName, String errorString)
- throws ClassNotFoundException {
- Assert.assertFalse( isFieldHere( className, fieldName ), errorString );
+ public static void assertAbsenceOfFieldInMetamodelFor(Class<?> clazz, String fieldName, String errorString) {
+ Assert.assertFalse( hasFieldInMetamodelFor( clazz, fieldName ), errorString );
}
- public static void assertPresenceOfField(String className, String fieldName, String errorString)
- throws ClassNotFoundException {
- Assert.assertTrue( isFieldHere( className, fieldName ), errorString );
+ public static void assertPresenceOfFieldInMetamodelFor(Class<?> clazz, String fieldName, String errorString) {
+ Assert.assertTrue( hasFieldInMetamodelFor( clazz, fieldName ), errorString );
}
- public static void assertFieldType(String className, String fieldName, Class expectedType, String errorString)
- throws ClassNotFoundException {
- Field field = getField( className, fieldName );
+ public static void assertFieldTypeInMetaModelFor(Class<?> clazz, String fieldName, Class expectedType, String errorString) {
+ Field field = getFieldFromMetamodelFor( clazz, fieldName );
assertNotNull( field );
ParameterizedType type = ( ParameterizedType ) field.getGenericType();
Type actualType = type.getActualTypeArguments()[1];
@@ -106,15 +108,17 @@
assertEquals( actualType, expectedType, errorString );
}
- public static void assertSuperClass(String className, String superClassName) {
+ public static void assertSuperClassRelationShipInMetamodel(Class<?> entityClass, Class<?> superEntityClass) {
+ String entityModelClassName = entityClass.getName() + META_MODEL_CLASS_POSTFIX;
+ String superEntityModelClassName = superEntityClass.getName() + META_MODEL_CLASS_POSTFIX;
Class<?> clazz;
Class<?> superClazz;
try {
- clazz = Class.forName( className );
- superClazz = Class.forName( superClassName );
+ clazz = Class.forName( entityModelClassName );
+ superClazz = Class.forName( superEntityModelClassName );
Assert.assertEquals(
clazz.getSuperclass(), superClazz,
- "Entity " + superClassName + " should be the superclass of " + className
+ "Entity " + superEntityModelClassName + " should be the superclass of " + entityModelClassName
);
}
catch ( ClassNotFoundException e ) {
@@ -122,18 +126,24 @@
}
}
- private static boolean isFieldHere(String className, String fieldName) throws ClassNotFoundException {
- return getField( className, fieldName ) != null;
+ private static boolean hasFieldInMetamodelFor(Class<?> clazz, String fieldName) {
+ return getFieldFromMetamodelFor( clazz, fieldName ) != null;
}
- public static Field getField(String className, String fieldName) throws ClassNotFoundException {
- Class<?> clazz = Class.forName( className );
+ public static Field getFieldFromMetamodelFor(Class<?> entityClass, String fieldName) {
+ String entityModelClassName = entityClass.getName() + META_MODEL_CLASS_POSTFIX;
+ Field field = null;
try {
- return clazz.getField( fieldName );
+ Class<?> clazz = Class.forName( entityModelClassName );
+ field = clazz.getField( fieldName );
}
+ catch ( ClassNotFoundException e ) {
+ fail( "Unable to load class " + entityModelClassName );
+ }
catch ( NoSuchFieldException e ) {
- return null;
+ field = null;
}
+ return field;
}
}
Modified: jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/xmlmapped/Boy.java
===================================================================
--- jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/xmlmapped/Boy.java 2010-01-28 09:35:59 UTC (rev 18663)
+++ jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/xmlmapped/Boy.java 2010-01-28 16:56:51 UTC (rev 18664)
@@ -33,6 +33,36 @@
*/
private List<String> nickNames;
+ private Superhero favoriteSuperhero;
+
+ private List<Superhero> knowsHeros;
+
+ private List<Superhero> savedBy;
+
+ public List<Superhero> getSavedBy() {
+ return savedBy;
+ }
+
+ public void setSavedBy(List<Superhero> savedBy) {
+ this.savedBy = savedBy;
+ }
+
+ public Superhero getFavoriteSuperhero() {
+ return favoriteSuperhero;
+ }
+
+ public void setFavoriteSuperhero(Superhero favoriteSuperhero) {
+ this.favoriteSuperhero = favoriteSuperhero;
+ }
+
+ public List<Superhero> getKnowsHeros() {
+ return knowsHeros;
+ }
+
+ public void setKnowsHeros(List<Superhero> knowsHeros) {
+ this.knowsHeros = knowsHeros;
+ }
+
public long getId() {
return id;
}
Added: jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/xmlmapped/FakeHero.java
===================================================================
--- jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/xmlmapped/FakeHero.java (rev 0)
+++ jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/xmlmapped/FakeHero.java 2010-01-28 16:56:51 UTC (rev 18664)
@@ -0,0 +1,24 @@
+// $Id:$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2009, Red Hat, Inc. and/or its affiliates, 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.test.xmlmapped;
+
+/**
+ * @author Hardy Ferentschik
+ */
+public class FakeHero {
+}
\ No newline at end of file
Added: jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/xmlmapped/Superhero.java
===================================================================
--- jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/xmlmapped/Superhero.java (rev 0)
+++ jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/xmlmapped/Superhero.java 2010-01-28 16:56:51 UTC (rev 18664)
@@ -0,0 +1,62 @@
+// $Id:$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2009, Red Hat, Inc. and/or its affiliates, 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.test.xmlmapped;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+/**
+ * @author Hardy Ferentschik
+ */
+@Entity
+public class Superhero {
+ @Id
+ @GeneratedValue
+ private long id;
+
+ private String name;
+
+ private String superPower;
+
+ 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 String getSuperPower() {
+ return superPower;
+ }
+
+ public void setSuperPower(String superPower) {
+ this.superPower = superPower;
+ }
+}
+
+
Modified: jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/xmlmapped/XmlMappingTest.java
===================================================================
--- jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/xmlmapped/XmlMappingTest.java 2010-01-28 09:35:59 UTC (rev 18663)
+++ jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/xmlmapped/XmlMappingTest.java 2010-01-28 16:56:51 UTC (rev 18664)
@@ -17,54 +17,81 @@
*/
package org.hibernate.jpamodelgen.test.xmlmapped;
-import java.lang.reflect.Field;
-import java.lang.reflect.ParameterizedType;
-
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
-import static junit.framework.Assert.assertTrue;
-import static org.hibernate.jpamodelgen.test.util.TestUtil.assertClassGenerated;
-import static org.hibernate.jpamodelgen.test.util.TestUtil.assertPresenceOfField;
-import static org.hibernate.jpamodelgen.test.util.TestUtil.assertSuperClass;
-import static org.hibernate.jpamodelgen.test.util.TestUtil.getField;
+import static org.hibernate.jpamodelgen.test.util.TestUtil.assertFieldTypeInMetaModelFor;
+import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassGeneratedFor;
+import static org.hibernate.jpamodelgen.test.util.TestUtil.assertPresenceOfFieldInMetamodelFor;
+import static org.hibernate.jpamodelgen.test.util.TestUtil.assertSuperClassRelationShipInMetamodel;
/**
* @author Hardy Ferentschik
*/
public class XmlMappingTest extends CompilationTest {
@Test
- public void testXmlConfiguredEmbeddedClassGenerated() throws Exception {
- assertClassGenerated( Address.class.getName() + "_" );
+ public void testXmlConfiguredEmbeddedClassGenerated() {
+ assertMetamodelClassGeneratedFor( Address.class );
}
@Test
- public void testXmlConfiguredMappedSuperclassGenerated() throws Exception {
- assertClassGenerated( Building.class.getName() + "_" );
- assertPresenceOfField(
- Building.class.getName() + "_", "address", "address field should exist"
+ public void testXmlConfiguredMappedSuperclassGenerated() {
+ assertMetamodelClassGeneratedFor( Building.class );
+ assertPresenceOfFieldInMetamodelFor( Building.class, "address", "address field should exist" );
+ }
+
+ /**
+ * METAGEN-17
+ */
+ @Test
+ public void testTargetEntityOnOneToOne() {
+ assertMetamodelClassGeneratedFor( Boy.class );
+ assertPresenceOfFieldInMetamodelFor( Boy.class, "favoriteSuperhero", "favoriteSuperhero field should exist" );
+ assertFieldTypeInMetaModelFor(
+ Boy.class, "favoriteSuperhero", FakeHero.class, "target entity overridden in xml"
);
}
+ /**
+ * METAGEN-17
+ */
@Test
- public void testXmlConfiguredElementCollection() throws Exception {
- assertClassGenerated( Boy.class.getName() + "_" );
- assertPresenceOfField(
- Boy.class.getName() + "_", "nickNames", "nickNames field should exist"
+ public void testTargetEntityOnOneToMany() {
+ assertMetamodelClassGeneratedFor( Boy.class );
+ assertPresenceOfFieldInMetamodelFor( Boy.class, "knowsHeros", "knowsHeros field should exist" );
+ assertFieldTypeInMetaModelFor(
+ Boy.class, "knowsHeros", FakeHero.class, "target entity overridden in xml"
);
- Field field = getField( Boy.class.getName() + "_", "nickNames" );
- ParameterizedType type = ( ParameterizedType ) field.getGenericType();
- assertTrue( "Wrong target type", type.getActualTypeArguments()[1].equals( Integer.class ) );
}
+ /**
+ * METAGEN-17
+ */
@Test
- public void testClassHierarchy() throws Exception {
- assertClassGenerated( Mammal.class.getName() + "_" );
- assertClassGenerated( LivingBeing.class.getName() + "_" );
- assertSuperClass( Mammal.class.getName() + "_", LivingBeing.class.getName() + "_" );
+ public void testTargetEntityOnManyToMany() {
+ assertMetamodelClassGeneratedFor( Boy.class );
+ assertPresenceOfFieldInMetamodelFor( Boy.class, "savedBy", "savedBy field should exist" );
+ assertFieldTypeInMetaModelFor(
+ Boy.class, "savedBy", FakeHero.class, "target entity overridden in xml"
+ );
}
+ @Test
+ public void testXmlConfiguredElementCollection() {
+ assertMetamodelClassGeneratedFor( Boy.class );
+ assertPresenceOfFieldInMetamodelFor( Boy.class, "nickNames", "nickNames field should exist" );
+ assertFieldTypeInMetaModelFor( Boy.class, "nickNames", Integer.class, "target class overridden in xml" );
+ }
+
+
+ @Test
+ public void testClassHierarchy() {
+ assertMetamodelClassGeneratedFor( Mammal.class );
+ assertMetamodelClassGeneratedFor( LivingBeing.class );
+ assertSuperClassRelationShipInMetamodel( Mammal.class, LivingBeing.class );
+ }
+
@Test(expectedExceptions = ClassNotFoundException.class)
public void testNonExistentMappedClassesGetIgnored() throws Exception {
Class.forName( "org.hibernate.jpamodelgen.test.model.Dummy_" );
Modified: jpamodelgen/trunk/src/test/resources/org/hibernate/jpamodelgen/test/xmlmapped/boy.xml
===================================================================
--- jpamodelgen/trunk/src/test/resources/org/hibernate/jpamodelgen/test/xmlmapped/boy.xml 2010-01-28 09:35:59 UTC (rev 18663)
+++ jpamodelgen/trunk/src/test/resources/org/hibernate/jpamodelgen/test/xmlmapped/boy.xml 2010-01-28 16:56:51 UTC (rev 18664)
@@ -10,6 +10,9 @@
<attributes>
<id name="id"/>
<basic name="name"/>
+ <one-to-many name="knowsHeros" target-entity="org.hibernate.jpamodelgen.test.xmlmapped.FakeHero"/>
+ <one-to-one name="favoriteSuperhero" target-entity="org.hibernate.jpamodelgen.test.xmlmapped.FakeHero"/>
+ <many-to-many name="savedBy" target-entity="org.hibernate.jpamodelgen.test.xmlmapped.FakeHero"/>
<element-collection name="nickNames" target-class="java.lang.Integer"/>
</attributes>
</entity>
Modified: jpamodelgen/trunk/src/test/suite/unit-tests.xml
===================================================================
--- jpamodelgen/trunk/src/test/suite/unit-tests.xml 2010-01-28 09:35:59 UTC (rev 18663)
+++ jpamodelgen/trunk/src/test/suite/unit-tests.xml 2010-01-28 16:56:51 UTC (rev 18664)
@@ -6,7 +6,9 @@
<package name="org.hibernate.jpamodelgen.test.accesstype"/>
<package name="org.hibernate.jpamodelgen.test.arraytype"/>
<package name="org.hibernate.jpamodelgen.test.elementcollection"/>
+ <package name="org.hibernate.jpamodelgen.test.generics"/>
<package name="org.hibernate.jpamodelgen.test.inheritance"/>
+ <package name="org.hibernate.jpamodelgen.test.rawTypes"/>
<package name="org.hibernate.jpamodelgen.test.xmlmapped"/>
</packages>
</test>
14 years, 10 months
Hibernate SVN: r18663 - search/trunk/src/main/docbook/en-US/modules.
by hibernate-commits@lists.jboss.org
Author: sannegrinovero
Date: 2010-01-28 04:35:59 -0500 (Thu, 28 Jan 2010)
New Revision: 18663
Modified:
search/trunk/src/main/docbook/en-US/modules/configuration.xml
search/trunk/src/main/docbook/en-US/modules/getting-started.xml
search/trunk/src/main/docbook/en-US/modules/query.xml
Log:
HSEARCH-450 and other minor doc fixes
Modified: search/trunk/src/main/docbook/en-US/modules/configuration.xml
===================================================================
--- search/trunk/src/main/docbook/en-US/modules/configuration.xml 2010-01-28 01:31:45 UTC (rev 18662)
+++ search/trunk/src/main/docbook/en-US/modules/configuration.xml 2010-01-28 09:35:59 UTC (rev 18663)
@@ -748,7 +748,7 @@
disable it, set
<literal>hibernate.search.autoregister_listeners</literal> to false.
Note that there is no performance penalty when the listeners are enabled
- even though no entities are indexed.</para>
+ but no entities are annotated as indexed.</para>
<para>To enable Hibernate Search in Hibernate Core (ie. if you don't use
Hibernate Annotations), add the
Modified: search/trunk/src/main/docbook/en-US/modules/getting-started.xml
===================================================================
--- search/trunk/src/main/docbook/en-US/modules/getting-started.xml 2010-01-28 01:31:45 UTC (rev 18662)
+++ search/trunk/src/main/docbook/en-US/modules/getting-started.xml 2010-01-28 09:35:59 UTC (rev 18663)
@@ -477,7 +477,7 @@
<programlisting>
EntityManager em = entityManagerFactory.createEntityManager();
FullTextEntityManager fullTextEntityManager =
- org.hibernate.hibernate.search.jpa.Search.getFullTextEntityManager(em);
+ org.hibernate.search.jpa.Search.getFullTextEntityManager(em);
em.getTransaction().begin();
// create native Lucene query
Modified: search/trunk/src/main/docbook/en-US/modules/query.xml
===================================================================
--- search/trunk/src/main/docbook/en-US/modules/query.xml 2010-01-28 01:31:45 UTC (rev 18662)
+++ search/trunk/src/main/docbook/en-US/modules/query.xml 2010-01-28 09:35:59 UTC (rev 18663)
@@ -101,7 +101,7 @@
<programlisting>EntityManager em = entityManagerFactory.createEntityManager();
FullTextEntityManager fullTextEntityManager =
- org.hibernate.hibernate.search.jpa.Search.getFullTextEntityManager(em);
+ org.hibernate.search.jpa.Search.getFullTextEntityManager(em);
...
org.apache.lucene.queryParser.QueryParser parser =
14 years, 10 months
Hibernate SVN: r18662 - in core/trunk: annotations/src/test/java/org/hibernate/test/annotations/quote/resultsetmappings and 1 other directories.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2010-01-27 20:31:45 -0500 (Wed, 27 Jan 2010)
New Revision: 18662
Added:
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/quote/resultsetmappings/
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/quote/resultsetmappings/ExplicitSqlResultSetMappingTest.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/quote/resultsetmappings/MyEntity.java
Modified:
core/trunk/core/src/main/java/org/hibernate/loader/custom/CustomLoader.java
Log:
HHH-4862 - column name quoting not properly handled for javax.persistence.ColumnResult
Added: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/quote/resultsetmappings/ExplicitSqlResultSetMappingTest.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/quote/resultsetmappings/ExplicitSqlResultSetMappingTest.java (rev 0)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/quote/resultsetmappings/ExplicitSqlResultSetMappingTest.java 2010-01-28 01:31:45 UTC (rev 18662)
@@ -0,0 +1,60 @@
+/*
+ * 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.quote.resultsetmappings;
+
+import org.hibernate.Session;
+import org.hibernate.test.annotations.TestCase;
+
+/**
+ * TODO : javadoc
+ *
+ * @author Steve Ebersole
+ */
+public class ExplicitSqlResultSetMappingTest extends TestCase {
+ private String queryString = "select t.\"NAME\" as \"QuotEd_nAMe\" from \"MY_ENTITY_TABLE_NAME\" t";
+
+ @Override
+ protected Class<?>[] getAnnotatedClasses() {
+ return new Class<?>[] { MyEntity.class };
+ }
+
+ public void testCompleteAutoDiscovery() {
+ Session s = openSession();
+ s.beginTransaction();
+ s.createSQLQuery( queryString )
+ .list();
+ s.getTransaction().commit();
+ s.close();
+ }
+
+ public void testPartialAutoDiscovery() {
+ Session s = openSession();
+ s.beginTransaction();
+ s.createSQLQuery( queryString )
+ .setResultSetMapping( "explicitResultSetMapping" )
+ .list();
+ s.getTransaction().commit();
+ s.close();
+ }
+}
Added: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/quote/resultsetmappings/MyEntity.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/quote/resultsetmappings/MyEntity.java (rev 0)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/quote/resultsetmappings/MyEntity.java 2010-01-28 01:31:45 UTC (rev 18662)
@@ -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.quote.resultsetmappings;
+
+import javax.persistence.Column;
+import javax.persistence.ColumnResult;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.SqlResultSetMapping;
+import javax.persistence.Table;
+
+/**
+ * TODO : javadoc
+ *
+ * @author Steve Ebersole
+ */
+@SqlResultSetMapping(
+ name="explicitResultSetMapping",
+ columns={ @ColumnResult(name="`QuotEd_nAMe`") }
+)
+@Entity
+@Table( name = "MY_ENTITY_TABLE_NAME" )
+public class MyEntity {
+ private Long id;
+ private String name;
+
+ @Id
+ @GeneratedValue
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ @Column( name = "NAME" )
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Modified: core/trunk/core/src/main/java/org/hibernate/loader/custom/CustomLoader.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/loader/custom/CustomLoader.java 2010-01-28 00:00:50 UTC (rev 18661)
+++ core/trunk/core/src/main/java/org/hibernate/loader/custom/CustomLoader.java 2010-01-28 01:31:45 UTC (rev 18662)
@@ -56,6 +56,7 @@
import org.hibernate.type.EntityType;
import org.hibernate.type.CollectionType;
import org.hibernate.util.ArrayHelper;
+import org.hibernate.util.StringHelper;
/**
* Extension point for loaders which use a SQL result set with "unexpected" column aliases.
@@ -125,7 +126,7 @@
specifiedAliases.add( scalarRtn.getColumnAlias() );
resultColumnProcessors.add(
new ScalarResultColumnProcessor(
- scalarRtn.getColumnAlias(),
+ StringHelper.unquote( scalarRtn.getColumnAlias() ),
scalarRtn.getType()
)
);
14 years, 10 months
Hibernate SVN: r18661 - in core/trunk/entitymanager/src: test/java/org/hibernate/ejb/test/metadata and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2010-01-27 19:00:50 -0500 (Wed, 27 Jan 2010)
New Revision: 18661
Added:
core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata/SimpleMedicalHistory.java
core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata/SimplePerson.java
Modified:
core/trunk/entitymanager/src/main/java/org/hibernate/ejb/metamodel/MetadataContext.java
core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata/SecondMetadataTest.java
Log:
HHH-4859 fix NPE on true embedded ids (ie no property) when building the metamodel
Modified: core/trunk/entitymanager/src/main/java/org/hibernate/ejb/metamodel/MetadataContext.java
===================================================================
--- core/trunk/entitymanager/src/main/java/org/hibernate/ejb/metamodel/MetadataContext.java 2010-01-27 23:59:29 UTC (rev 18660)
+++ core/trunk/entitymanager/src/main/java/org/hibernate/ejb/metamodel/MetadataContext.java 2010-01-28 00:00:50 UTC (rev 18661)
@@ -37,6 +37,8 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.hibernate.mapping.Component;
+import org.hibernate.mapping.KeyValue;
import org.hibernate.mapping.MappedSuperclass;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property;
@@ -221,9 +223,26 @@
);
}
}
- else {
+ else if ( persistentClass.hasIdentifierMapper() ) {
jpaEntityType.getBuilder().applyIdClassAttributes( buildIdClassAttributes( jpaEntityType, persistentClass ) );
}
+ else {
+ final KeyValue value = persistentClass.getIdentifier();
+ if (value instanceof Component ) {
+ final Component component = ( Component ) value;
+ if ( component.getPropertySpan() > 1 ) {
+ //FIXME we are an Hibernate embedded id (ie not type)
+ }
+ else {
+ //FIXME take care of declared vs non declared property
+ jpaEntityType.getBuilder().applyIdAttribute(
+ attributeFactory.buildIdAttribute(
+ jpaEntityType,
+ (Property) component.getPropertyIterator().next() )
+ );
+ }
+ }
+ }
}
private <X> void applyIdMetadata(MappedSuperclass mappingType, MappedSuperclassTypeImpl<X> jpaMappingType) {
Modified: core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata/SecondMetadataTest.java
===================================================================
--- core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata/SecondMetadataTest.java 2010-01-27 23:59:29 UTC (rev 18660)
+++ core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata/SecondMetadataTest.java 2010-01-28 00:00:50 UTC (rev 18661)
@@ -14,13 +14,17 @@
assertNotNull( emf.getMetamodel() );
assertNotNull( emf.getMetamodel().entity( DeskWithRawType.class ) );
assertNotNull( emf.getMetamodel().entity( EmployeeWithRawType.class ) );
+ assertNotNull( emf.getMetamodel().entity( SimpleMedicalHistory.class ) );
+ assertNotNull( emf.getMetamodel().entity( SimplePerson.class ) );
}
@Override
public Class[] getAnnotatedClasses() {
return new Class[] {
DeskWithRawType.class,
- EmployeeWithRawType.class
+ EmployeeWithRawType.class,
+ SimpleMedicalHistory.class,
+ SimplePerson.class
};
}
}
Added: core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata/SimpleMedicalHistory.java
===================================================================
--- core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata/SimpleMedicalHistory.java (rev 0)
+++ core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata/SimpleMedicalHistory.java 2010-01-28 00:00:50 UTC (rev 18661)
@@ -0,0 +1,25 @@
+package org.hibernate.ejb.test.metadata;
+
+import java.io.Serializable;
+import java.util.Date;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.OneToOne;
+import javax.persistence.Temporal;
+import javax.persistence.TemporalType;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class SimpleMedicalHistory implements Serializable {
+
+ @Temporal(TemporalType.DATE)
+ Date lastupdate;
+
+ @Id
+ @JoinColumn(name = "FK")
+ @OneToOne
+ SimplePerson patient;
+}
Added: core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata/SimplePerson.java
===================================================================
--- core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata/SimplePerson.java (rev 0)
+++ core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/metadata/SimplePerson.java 2010-01-28 00:00:50 UTC (rev 18661)
@@ -0,0 +1,13 @@
+package org.hibernate.ejb.test.metadata;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class SimplePerson {
+ @Id
+ String ssn;
+}
14 years, 10 months
Hibernate SVN: r18660 - in core/trunk: core/src/main/java/org/hibernate/impl and 2 other directories.
by hibernate-commits@lists.jboss.org
Author: gbadner
Date: 2010-01-27 18:59:29 -0500 (Wed, 27 Jan 2010)
New Revision: 18660
Modified:
core/trunk/core/src/main/java/org/hibernate/hql/classic/QueryTranslatorImpl.java
core/trunk/core/src/main/java/org/hibernate/impl/IteratorImpl.java
core/trunk/core/src/main/java/org/hibernate/loader/hql/QueryLoader.java
core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlySessionTest.java
Log:
HHH-4828 : Entities returned by Query...setReadOnly(true)...iterate() should be read-only
Modified: core/trunk/core/src/main/java/org/hibernate/hql/classic/QueryTranslatorImpl.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/hql/classic/QueryTranslatorImpl.java 2010-01-27 23:29:24 UTC (rev 18659)
+++ core/trunk/core/src/main/java/org/hibernate/hql/classic/QueryTranslatorImpl.java 2010-01-27 23:59:29 UTC (rev 18660)
@@ -951,7 +951,7 @@
PreparedStatement st = prepareQueryStatement( queryParameters, false, session );
ResultSet rs = getResultSet( st, queryParameters.hasAutoDiscoverScalarTypes(), false, queryParameters.getRowSelection(), session );
HolderInstantiator hi = HolderInstantiator.createClassicHolderInstantiator(holderConstructor, queryParameters.getResultTransformer());
- Iterator result = new IteratorImpl( rs, st, session, returnTypes, getColumnNames(), hi );
+ Iterator result = new IteratorImpl( rs, st, session, queryParameters.isReadOnly( session ), returnTypes, getColumnNames(), hi );
if ( stats ) {
session.getFactory().getStatisticsImplementor().queryExecuted(
Modified: core/trunk/core/src/main/java/org/hibernate/impl/IteratorImpl.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/impl/IteratorImpl.java 2010-01-27 23:29:24 UTC (rev 18659)
+++ core/trunk/core/src/main/java/org/hibernate/impl/IteratorImpl.java 2010-01-27 23:59:29 UTC (rev 18660)
@@ -51,6 +51,7 @@
private ResultSet rs;
private final EventSource session;
+ private boolean readOnly;
private final Type[] types;
private final boolean single;
private Object currentResult;
@@ -63,6 +64,7 @@
ResultSet rs,
PreparedStatement ps,
EventSource sess,
+ boolean readOnly,
Type[] types,
String[][] columnNames,
HolderInstantiator holderInstantiator)
@@ -71,6 +73,7 @@
this.rs=rs;
this.ps=ps;
this.session = sess;
+ this.readOnly = readOnly;
this.types = types;
this.names = columnNames;
this.holderInstantiator = holderInstantiator;
@@ -127,6 +130,8 @@
public Object next() throws HibernateException {
if ( !hasNext ) throw new NoSuchElementException("No more results");
+ boolean sessionDefaultReadOnlyOrig = session.isDefaultReadOnly();
+ session.setDefaultReadOnly( readOnly );
try {
boolean isHolder = holderInstantiator.isRequired();
@@ -159,6 +164,9 @@
"could not get next iterator result"
);
}
+ finally {
+ session.setDefaultReadOnly( sessionDefaultReadOnlyOrig );
+ }
}
public void remove() {
Modified: core/trunk/core/src/main/java/org/hibernate/loader/hql/QueryLoader.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/loader/hql/QueryLoader.java 2010-01-27 23:29:24 UTC (rev 18659)
+++ core/trunk/core/src/main/java/org/hibernate/loader/hql/QueryLoader.java 2010-01-27 23:59:29 UTC (rev 18660)
@@ -442,6 +442,7 @@
rs,
st,
session,
+ queryParameters.isReadOnly( session ),
queryReturnTypes,
queryTranslator.getColumnNames(),
buildHolderInstantiator( queryParameters.getResultTransformer() )
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlySessionTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlySessionTest.java 2010-01-27 23:29:24 UTC (rev 18659)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/readonly/ReadOnlySessionTest.java 2010-01-27 23:59:29 UTC (rev 18660)
@@ -26,12 +26,14 @@
package org.hibernate.test.readonly;
import java.math.BigDecimal;
+import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import org.hibernate.CacheMode;
import org.hibernate.Hibernate;
+import org.hibernate.Query;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
@@ -107,7 +109,7 @@
s.close();
}
- public void testReadOnlyMode() {
+ public void testReadOnlySessionDefaultQueryScroll() {
Session s = openSession();
s.setCacheMode(CacheMode.IGNORE);
@@ -128,6 +130,7 @@
int i = 0;
ScrollableResults sr = s.createQuery("from DataPoint dp order by dp.x asc")
.scroll(ScrollMode.FORWARD_ONLY);
+ s.setDefaultReadOnly( false );
while ( sr.next() ) {
DataPoint dp = (DataPoint) sr.get(0);
if (++i==50) {
@@ -139,13 +142,13 @@
s.clear();
t = s.beginTransaction();
List single = s.createQuery("from DataPoint where description='done!'").list();
- assertEquals( single.size(), 1 );
+ assertEquals( 1, single.size() );
s.createQuery("delete from DataPoint").executeUpdate();
t.commit();
s.close();
}
- public void testReadOnlyQueryScrollChangeToModifiableBeforeIterate() {
+ public void testReadOnlySessionModifiableQueryScroll() {
Session s = openSession();
s.setCacheMode(CacheMode.IGNORE);
@@ -165,8 +168,87 @@
s.setDefaultReadOnly( true );
int i = 0;
ScrollableResults sr = s.createQuery("from DataPoint dp order by dp.x asc")
+ .setReadOnly( false )
.scroll(ScrollMode.FORWARD_ONLY);
+ while ( sr.next() ) {
+ DataPoint dp = (DataPoint) sr.get(0);
+ if (++i==50) {
+ s.setReadOnly(dp, true);
+ }
+ dp.setDescription("done!");
+ }
+ t.commit();
+ s.clear();
+ t = s.beginTransaction();
+ List list = s.createQuery("from DataPoint where description='done!'").list();
+ assertEquals( 99, list.size() );
+ s.createQuery("delete from DataPoint").executeUpdate();
+ t.commit();
+ s.close();
+ }
+
+ public void testModifiableSessionReadOnlyQueryScroll() {
+
+ Session s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ for ( int i=0; i<100; i++ ) {
+ DataPoint dp = new DataPoint();
+ dp.setX( new BigDecimal(i * 0.1d).setScale(19, BigDecimal.ROUND_DOWN) );
+ dp.setY( new BigDecimal( Math.cos( dp.getX().doubleValue() ) ).setScale(19, BigDecimal.ROUND_DOWN) );
+ s.save(dp);
+ }
+ t.commit();
+ s.close();
+
+ s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ t = s.beginTransaction();
+ assertFalse( s.isDefaultReadOnly() );
+ int i = 0;
+ ScrollableResults sr = s.createQuery("from DataPoint dp order by dp.x asc")
+ .setReadOnly( true )
+ .scroll(ScrollMode.FORWARD_ONLY);
+ while ( sr.next() ) {
+ DataPoint dp = (DataPoint) sr.get(0);
+ if (++i==50) {
+ s.setReadOnly(dp, false);
+ }
+ dp.setDescription("done!");
+ }
+ t.commit();
+ s.clear();
+ t = s.beginTransaction();
+ List single = s.createQuery("from DataPoint where description='done!'").list();
+ assertEquals( 1, single.size() );
+ s.createQuery("delete from DataPoint").executeUpdate();
+ t.commit();
+ s.close();
+ }
+
+ public void testModifiableSessionDefaultQueryReadOnlySessionScroll() {
+
+ Session s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ for ( int i=0; i<100; i++ ) {
+ DataPoint dp = new DataPoint();
+ dp.setX( new BigDecimal(i * 0.1d).setScale(19, BigDecimal.ROUND_DOWN) );
+ dp.setY( new BigDecimal( Math.cos( dp.getX().doubleValue() ) ).setScale(19, BigDecimal.ROUND_DOWN) );
+ s.save(dp);
+ }
+ t.commit();
+ s.close();
+
+ s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ t = s.beginTransaction();
s.setDefaultReadOnly( false );
+ int i = 0;
+ Query query = s.createQuery("from DataPoint dp order by dp.x asc");
+ s.setDefaultReadOnly( true );
+ ScrollableResults sr = query.scroll(ScrollMode.FORWARD_ONLY);
+ s.setDefaultReadOnly( false );
while ( sr.next() ) {
DataPoint dp = (DataPoint) sr.get(0);
if (++i==50) {
@@ -184,6 +266,466 @@
s.close();
}
+ public void testQueryReadOnlyScroll() {
+
+ Session s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ DataPoint dp = null;
+ for ( int i=0; i<100; i++ ) {
+ dp = new DataPoint();
+ dp.setX( new BigDecimal(i * 0.1d).setScale(19, BigDecimal.ROUND_DOWN) );
+ dp.setY( new BigDecimal( Math.cos( dp.getX().doubleValue() ) ).setScale(19, BigDecimal.ROUND_DOWN) );
+ s.save(dp);
+ }
+ t.commit();
+ s.close();
+
+ s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ t = s.beginTransaction();
+ s.setDefaultReadOnly( false );
+ int i = 0;
+ Query query = s.createQuery("from DataPoint dp order by dp.x asc");
+ assertFalse( query.isReadOnly() );
+ s.setDefaultReadOnly( true );
+ assertTrue( query.isReadOnly() );
+ s.setDefaultReadOnly( false );
+ assertFalse( query.isReadOnly() );
+ query.setReadOnly( true );
+ assertTrue( query.isReadOnly() );
+ s.setDefaultReadOnly( true );
+ assertTrue( query.isReadOnly() );
+ s.setDefaultReadOnly( false );
+ assertTrue( query.isReadOnly() );
+ query.setReadOnly( false );
+ assertFalse( query.isReadOnly() );
+ s.setDefaultReadOnly( true );
+ assertFalse( query.isReadOnly() );
+ query.setReadOnly( true );
+ assertTrue( query.isReadOnly() );
+ s.setDefaultReadOnly( false );
+ assertFalse( s.isDefaultReadOnly() );
+ ScrollableResults sr = query.scroll(ScrollMode.FORWARD_ONLY);
+ assertFalse( s.isDefaultReadOnly() );
+ assertTrue( query.isReadOnly() );
+ DataPoint dpLast = ( DataPoint ) s.get( DataPoint.class, dp.getId() );
+ assertFalse( s.isReadOnly( dpLast ) );
+ query.setReadOnly( false );
+ assertFalse( query.isReadOnly() );
+ int nExpectedChanges = 0;
+ assertFalse( s.isDefaultReadOnly() );
+ while ( sr.next() ) {
+ assertFalse( s.isDefaultReadOnly() );
+ dp = (DataPoint) sr.get(0);
+ if ( dp.getId() == dpLast.getId() ) {
+ //dpLast existed in the session before executing the read-only query
+ assertFalse( s.isReadOnly( dp ) );
+ }
+ else {
+ assertTrue( s.isReadOnly( dp ) );
+ }
+ if (++i==50) {
+ s.setReadOnly(dp, false);
+ nExpectedChanges = ( dp == dpLast ? 1 : 2 );
+ }
+ dp.setDescription("done!");
+ }
+ assertFalse( s.isDefaultReadOnly() );
+ t.commit();
+ s.clear();
+ t = s.beginTransaction();
+ List list = s.createQuery("from DataPoint where description='done!'").list();
+ assertEquals( nExpectedChanges, list.size() );
+ s.createQuery("delete from DataPoint").executeUpdate();
+ t.commit();
+ s.close();
+ }
+
+ public void testQueryModifiableScroll() {
+
+ Session s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ DataPoint dp = null;
+ for ( int i=0; i<100; i++ ) {
+ dp = new DataPoint();
+ dp.setX( new BigDecimal(i * 0.1d).setScale(19, BigDecimal.ROUND_DOWN) );
+ dp.setY( new BigDecimal( Math.cos( dp.getX().doubleValue() ) ).setScale(19, BigDecimal.ROUND_DOWN) );
+ s.save(dp);
+ }
+ t.commit();
+ s.close();
+
+ s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ t = s.beginTransaction();
+ s.setDefaultReadOnly( true );
+ int i = 0;
+ Query query = s.createQuery("from DataPoint dp order by dp.x asc");
+ assertTrue( query.isReadOnly() );
+ s.setDefaultReadOnly( false );
+ assertFalse( query.isReadOnly() );
+ s.setDefaultReadOnly( true );
+ assertTrue( query.isReadOnly() );
+ query.setReadOnly( false );
+ assertFalse( query.isReadOnly() );
+ s.setDefaultReadOnly( false );
+ assertFalse( query.isReadOnly() );
+ s.setDefaultReadOnly( true );
+ assertFalse( query.isReadOnly() );
+ query.setReadOnly( true );
+ assertTrue( query.isReadOnly() );
+ s.setDefaultReadOnly( false );
+ assertTrue( query.isReadOnly() );
+ query.setReadOnly( false );
+ assertFalse( query.isReadOnly() );
+ s.setDefaultReadOnly( true );
+ assertTrue( s.isDefaultReadOnly() );
+ ScrollableResults sr = query.scroll(ScrollMode.FORWARD_ONLY);
+ assertFalse( query.isReadOnly() );
+ DataPoint dpLast = ( DataPoint ) s.get( DataPoint.class, dp.getId() );
+ assertTrue( s.isReadOnly( dpLast ) );
+ query.setReadOnly( true );
+ assertTrue( query.isReadOnly() );
+ int nExpectedChanges = 0;
+ assertTrue( s.isDefaultReadOnly() );
+ while ( sr.next() ) {
+ assertTrue( s.isDefaultReadOnly() );
+ dp = (DataPoint) sr.get(0);
+ if ( dp.getId() == dpLast.getId() ) {
+ //dpLast existed in the session before executing the read-only query
+ assertTrue( s.isReadOnly( dp ) );
+ }
+ else {
+ assertFalse( s.isReadOnly( dp ) );
+ }
+ if (++i==50) {
+ s.setReadOnly(dp, true);
+ nExpectedChanges = ( dp == dpLast ? 99 : 98 );
+ }
+ dp.setDescription("done!");
+ }
+ assertTrue( s.isDefaultReadOnly() );
+ t.commit();
+ s.clear();
+ t = s.beginTransaction();
+ List list = s.createQuery("from DataPoint where description='done!'").list();
+ assertEquals( nExpectedChanges, list.size() );
+ s.createQuery("delete from DataPoint").executeUpdate();
+ t.commit();
+ s.close();
+ }
+
+ public void testReadOnlySessionDefaultQueryIterate() {
+
+ Session s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ for ( int i=0; i<100; i++ ) {
+ DataPoint dp = new DataPoint();
+ dp.setX( new BigDecimal(i * 0.1d).setScale(19, BigDecimal.ROUND_DOWN) );
+ dp.setY( new BigDecimal( Math.cos( dp.getX().doubleValue() ) ).setScale(19, BigDecimal.ROUND_DOWN) );
+ s.save(dp);
+ }
+ t.commit();
+ s.close();
+
+ s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ t = s.beginTransaction();
+ s.setDefaultReadOnly( true );
+ int i = 0;
+ Iterator it = s.createQuery("from DataPoint dp order by dp.x asc")
+ .iterate();
+ s.setDefaultReadOnly( false );
+ while ( it.hasNext() ) {
+ DataPoint dp = (DataPoint) it.next();
+ if (++i==50) {
+ s.setReadOnly(dp, false);
+ }
+ dp.setDescription("done!");
+ }
+ t.commit();
+ s.clear();
+ t = s.beginTransaction();
+ List single = s.createQuery("from DataPoint where description='done!'").list();
+ assertEquals( 1, single.size() );
+ s.createQuery("delete from DataPoint").executeUpdate();
+ t.commit();
+ s.close();
+ }
+
+ public void testReadOnlySessionModifiableQueryIterate() {
+
+ Session s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ for ( int i=0; i<100; i++ ) {
+ DataPoint dp = new DataPoint();
+ dp.setX( new BigDecimal(i * 0.1d).setScale(19, BigDecimal.ROUND_DOWN) );
+ dp.setY( new BigDecimal( Math.cos( dp.getX().doubleValue() ) ).setScale(19, BigDecimal.ROUND_DOWN) );
+ s.save(dp);
+ }
+ t.commit();
+ s.close();
+
+ s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ t = s.beginTransaction();
+ s.setDefaultReadOnly( true );
+ int i = 0;
+ Iterator it = s.createQuery("from DataPoint dp order by dp.x asc")
+ .setReadOnly( false )
+ .iterate();
+ while ( it.hasNext() ) {
+ DataPoint dp = (DataPoint) it.next();
+ if (++i==50) {
+ s.setReadOnly(dp, true);
+ }
+ dp.setDescription("done!");
+ }
+ t.commit();
+ s.clear();
+ t = s.beginTransaction();
+ List list = s.createQuery("from DataPoint where description='done!'").list();
+ assertEquals( 99, list.size() );
+ s.createQuery("delete from DataPoint").executeUpdate();
+ t.commit();
+ s.close();
+ }
+
+ public void testModifiableSessionReadOnlyQueryIterate() {
+
+ Session s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ for ( int i=0; i<100; i++ ) {
+ DataPoint dp = new DataPoint();
+ dp.setX( new BigDecimal(i * 0.1d).setScale(19, BigDecimal.ROUND_DOWN) );
+ dp.setY( new BigDecimal( Math.cos( dp.getX().doubleValue() ) ).setScale(19, BigDecimal.ROUND_DOWN) );
+ s.save(dp);
+ }
+ t.commit();
+ s.close();
+
+ s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ t = s.beginTransaction();
+ assertFalse( s.isDefaultReadOnly() );
+ int i = 0;
+ Iterator it = s.createQuery("from DataPoint dp order by dp.x asc")
+ .setReadOnly( true )
+ .iterate();
+ while ( it.hasNext() ) {
+ DataPoint dp = (DataPoint) it.next();
+ if (++i==50) {
+ s.setReadOnly(dp, false);
+ }
+ dp.setDescription("done!");
+ }
+ t.commit();
+ s.clear();
+ t = s.beginTransaction();
+ List single = s.createQuery("from DataPoint where description='done!'").list();
+ assertEquals( 1, single.size() );
+ s.createQuery("delete from DataPoint").executeUpdate();
+ t.commit();
+ s.close();
+ }
+
+ public void testModifiableSessionDefaultQueryReadOnlySessionIterate() {
+
+ Session s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ for ( int i=0; i<100; i++ ) {
+ DataPoint dp = new DataPoint();
+ dp.setX( new BigDecimal(i * 0.1d).setScale(19, BigDecimal.ROUND_DOWN) );
+ dp.setY( new BigDecimal( Math.cos( dp.getX().doubleValue() ) ).setScale(19, BigDecimal.ROUND_DOWN) );
+ s.save(dp);
+ }
+ t.commit();
+ s.close();
+
+ s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ t = s.beginTransaction();
+ s.setDefaultReadOnly( false );
+ int i = 0;
+ Query query = s.createQuery("from DataPoint dp order by dp.x asc");
+ s.setDefaultReadOnly( true );
+ Iterator it = query.iterate();
+ s.setDefaultReadOnly( false );
+ while ( it.hasNext() ) {
+ DataPoint dp = (DataPoint) it.next();
+ if (++i==50) {
+ s.setReadOnly(dp, false);
+ }
+ dp.setDescription("done!");
+ }
+ t.commit();
+ s.clear();
+ t = s.beginTransaction();
+ List single = s.createQuery("from DataPoint where description='done!'").list();
+ assertEquals( 1, single.size() );
+ s.createQuery("delete from DataPoint").executeUpdate();
+ t.commit();
+ s.close();
+ }
+
+ public void testQueryReadOnlyIterate() {
+
+ Session s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ DataPoint dp = null;
+ for ( int i=0; i<100; i++ ) {
+ dp = new DataPoint();
+ dp.setX( new BigDecimal(i * 0.1d).setScale(19, BigDecimal.ROUND_DOWN) );
+ dp.setY( new BigDecimal( Math.cos( dp.getX().doubleValue() ) ).setScale(19, BigDecimal.ROUND_DOWN) );
+ s.save(dp);
+ }
+ t.commit();
+ s.close();
+
+ s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ t = s.beginTransaction();
+ s.setDefaultReadOnly( false );
+ int i = 0;
+ Query query = s.createQuery("from DataPoint dp order by dp.x asc");
+ assertFalse( query.isReadOnly() );
+ s.setDefaultReadOnly( true );
+ assertTrue( query.isReadOnly() );
+ s.setDefaultReadOnly( false );
+ assertFalse( query.isReadOnly() );
+ query.setReadOnly( true );
+ assertTrue( query.isReadOnly() );
+ s.setDefaultReadOnly( true );
+ assertTrue( query.isReadOnly() );
+ s.setDefaultReadOnly( false );
+ assertTrue( query.isReadOnly() );
+ query.setReadOnly( false );
+ assertFalse( query.isReadOnly() );
+ s.setDefaultReadOnly( true );
+ assertFalse( query.isReadOnly() );
+ query.setReadOnly( true );
+ assertTrue( query.isReadOnly() );
+ s.setDefaultReadOnly( false );
+ assertFalse( s.isDefaultReadOnly() );
+ Iterator it = query.iterate();
+ assertTrue( query.isReadOnly() );
+ DataPoint dpLast = ( DataPoint ) s.get( DataPoint.class, dp.getId() );
+ assertFalse( s.isReadOnly( dpLast ) );
+ query.setReadOnly( false );
+ assertFalse( query.isReadOnly() );
+ int nExpectedChanges = 0;
+ assertFalse( s.isDefaultReadOnly() );
+ while ( it.hasNext() ) {
+ assertFalse( s.isDefaultReadOnly() );
+ dp = (DataPoint) it.next();
+ assertFalse( s.isDefaultReadOnly() );
+ if ( dp.getId() == dpLast.getId() ) {
+ //dpLast existed in the session before executing the read-only query
+ assertFalse( s.isReadOnly( dp ) );
+ }
+ else {
+ assertTrue( s.isReadOnly( dp ) );
+ }
+ if (++i==50) {
+ s.setReadOnly(dp, false);
+ nExpectedChanges = ( dp == dpLast ? 1 : 2 );
+ }
+ dp.setDescription("done!");
+ }
+ assertFalse( s.isDefaultReadOnly() );
+ t.commit();
+ s.clear();
+ t = s.beginTransaction();
+ List list = s.createQuery("from DataPoint where description='done!'").list();
+ assertEquals( nExpectedChanges, list.size() );
+ s.createQuery("delete from DataPoint").executeUpdate();
+ t.commit();
+ s.close();
+ }
+
+ public void testQueryModifiableIterate() {
+
+ Session s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ Transaction t = s.beginTransaction();
+ DataPoint dp = null;
+ for ( int i=0; i<100; i++ ) {
+ dp = new DataPoint();
+ dp.setX( new BigDecimal(i * 0.1d).setScale(19, BigDecimal.ROUND_DOWN) );
+ dp.setY( new BigDecimal( Math.cos( dp.getX().doubleValue() ) ).setScale(19, BigDecimal.ROUND_DOWN) );
+ s.save(dp);
+ }
+ t.commit();
+ s.close();
+
+ s = openSession();
+ s.setCacheMode(CacheMode.IGNORE);
+ t = s.beginTransaction();
+ s.setDefaultReadOnly( true );
+ int i = 0;
+ Query query = s.createQuery("from DataPoint dp order by dp.x asc");
+ assertTrue( query.isReadOnly() );
+ s.setDefaultReadOnly( false );
+ assertFalse( query.isReadOnly() );
+ s.setDefaultReadOnly( true );
+ assertTrue( query.isReadOnly() );
+ query.setReadOnly( false );
+ assertFalse( query.isReadOnly() );
+ s.setDefaultReadOnly( false );
+ assertFalse( query.isReadOnly() );
+ s.setDefaultReadOnly( true );
+ assertFalse( query.isReadOnly() );
+ query.setReadOnly( true );
+ assertTrue( query.isReadOnly() );
+ s.setDefaultReadOnly( false );
+ assertTrue( query.isReadOnly() );
+ query.setReadOnly( false );
+ assertFalse( query.isReadOnly() );
+ s.setDefaultReadOnly( true );
+ assertTrue( s.isDefaultReadOnly() );
+ Iterator it = query.iterate();
+ assertFalse( query.isReadOnly() );
+ DataPoint dpLast = ( DataPoint ) s.get( DataPoint.class, dp.getId() );
+ assertTrue( s.isReadOnly( dpLast ) );
+ query.setReadOnly( true );
+ assertTrue( query.isReadOnly() );
+ int nExpectedChanges = 0;
+ assertTrue( s.isDefaultReadOnly() );
+ while ( it.hasNext() ) {
+ assertTrue( s.isDefaultReadOnly() );
+ dp = (DataPoint) it.next();
+ assertTrue( s.isDefaultReadOnly() );
+ if ( dp.getId() == dpLast.getId() ) {
+ //dpLast existed in the session before executing the read-only query
+ assertTrue( s.isReadOnly( dp ) );
+ }
+ else {
+ assertFalse( s.isReadOnly( dp ) );
+ }
+ if (++i==50) {
+ s.setReadOnly(dp, true);
+ nExpectedChanges = ( dp == dpLast ? 99 : 98 );
+ }
+ dp.setDescription("done!");
+ }
+ assertTrue( s.isDefaultReadOnly() );
+ t.commit();
+ s.clear();
+ t = s.beginTransaction();
+ List list = s.createQuery("from DataPoint where description='done!'").list();
+ assertEquals( nExpectedChanges, list.size() );
+ s.createQuery("delete from DataPoint").executeUpdate();
+ t.commit();
+ s.close();
+ }
+
public void testReadOnlyRefresh() {
Session s = openSession();
@@ -675,4 +1217,4 @@
s.close();
}
-}
\ No newline at end of file
+}
14 years, 10 months
Hibernate SVN: r18659 - in core/trunk/annotations/src: main/java/org/hibernate/cfg/annotations and 1 other directories.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2010-01-27 18:29:24 -0500 (Wed, 27 Jan 2010)
New Revision: 18659
Modified:
core/trunk/annotations/src/main/java/org/hibernate/cfg/CopyIdentifierComponentSecondPass.java
core/trunk/annotations/src/main/java/org/hibernate/cfg/Ejb3JoinColumn.java
core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/SimpleValueBinder.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e2/b/Dependent.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e2/b/DerivedIdentityIdClassParentEmbeddedIdDepTest.java
Log:
HHH-4849 honor default join column names for @MapsId propertie including on ids with multiple columns
Modified: core/trunk/annotations/src/main/java/org/hibernate/cfg/CopyIdentifierComponentSecondPass.java
===================================================================
--- core/trunk/annotations/src/main/java/org/hibernate/cfg/CopyIdentifierComponentSecondPass.java 2010-01-27 23:06:38 UTC (rev 18658)
+++ core/trunk/annotations/src/main/java/org/hibernate/cfg/CopyIdentifierComponentSecondPass.java 2010-01-27 23:29:24 UTC (rev 18659)
@@ -12,7 +12,6 @@
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property;
import org.hibernate.mapping.SimpleValue;
-import org.hibernate.mapping.Value;
/**
* @author Emmanuel Bernard
@@ -46,12 +45,13 @@
Component referencedComponent = (Component) referencedPersistentClass.getIdentifier();
Iterator<Property> properties = referencedComponent.getPropertyIterator();
+
//prepare column name structure
boolean isExplicitReference = true;
Map<String, Ejb3JoinColumn> columnByReferencedName = new HashMap<String, Ejb3JoinColumn>(joinColumns.length);
for (Ejb3JoinColumn joinColumn : joinColumns) {
final String referencedColumnName = joinColumn.getReferencedColumn();
- if ( BinderHelper.isDefault( referencedColumnName ) ) {
+ if ( referencedColumnName == null || BinderHelper.isDefault( referencedColumnName ) ) {
break;
}
columnByReferencedName.put( referencedColumnName, joinColumn );
@@ -87,29 +87,40 @@
value.setTypeName( referencedValue.getTypeName() );
value.setTypeParameters( referencedValue.getTypeParameters() );
final Iterator<Column> columns = referencedValue.getColumnIterator();
- //FIXME take care of Formula
- while ( columns.hasNext() ) {
- Column column = columns.next();
- final Ejb3JoinColumn joinColumn;
- String logicalColumnName = null;
- if ( isExplicitReference ) {
- final String columnName = column.getName();
- logicalColumnName = mappings.getLogicalColumnName( columnName, referencedPersistentClass.getTable() );
- joinColumn = columnByReferencedName.get( logicalColumnName );
+
+ if ( joinColumns[0].isNameDeferred() ) {
+ joinColumns[0].copyReferencedStructureAndCreateDefaultJoinColumns(
+ referencedPersistentClass,
+ columns,
+ value);
+ }
+ else {
+ //FIXME take care of Formula
+ while ( columns.hasNext() ) {
+ Column column = columns.next();
+ final Ejb3JoinColumn joinColumn;
+ String logicalColumnName = null;
+ if ( isExplicitReference ) {
+ final String columnName = column.getName();
+ logicalColumnName = mappings.getLogicalColumnName( columnName, referencedPersistentClass.getTable() );
+ joinColumn = columnByReferencedName.get( logicalColumnName );
+ }
+ else {
+ joinColumn = columnByReferencedName.get( "" + index );
+ index++;
+ }
+ if ( joinColumn == null && ! joinColumns[0].isNameDeferred() ) {
+ throw new AnnotationException(
+ isExplicitReference ?
+ "Unable to find column reference in the @MapsId mapping: " + logicalColumnName :
+ "Implicit column reference in the @MapsId mapping fails, try to use explicit referenceColumnNames: " + referencedEntityName
+ );
+ }
+ final String columnName = joinColumn == null || joinColumn.isNameDeferred() ? "tata_" + column.getName() : joinColumn
+ .getName();
+ value.addColumn( new Column( columnName ) );
+ column.setValue( value );
}
- else {
- joinColumn = columnByReferencedName.get( "" + index );
- index++;
- }
- if (joinColumn == null) {
- throw new AnnotationException(
- isExplicitReference ?
- "Unable to find column reference in the @MapsId mapping: " + logicalColumnName :
- "Implicit column reference in the @MapsId mapping fails, try to use explicit referenceColumnNames: " + referencedEntityName
- );
- }
- value.addColumn( new Column( joinColumn.getName() ) );
- column.setValue( value );
}
component.addProperty( property );
}
Modified: core/trunk/annotations/src/main/java/org/hibernate/cfg/Ejb3JoinColumn.java
===================================================================
--- core/trunk/annotations/src/main/java/org/hibernate/cfg/Ejb3JoinColumn.java 2010-01-27 23:06:38 UTC (rev 18658)
+++ core/trunk/annotations/src/main/java/org/hibernate/cfg/Ejb3JoinColumn.java 2010-01-27 23:29:24 UTC (rev 18659)
@@ -31,6 +31,7 @@
import javax.persistence.PrimaryKeyJoinColumn;
import org.hibernate.AnnotationException;
+import org.hibernate.AssertionFailure;
import org.hibernate.MappingException;
import org.hibernate.util.StringHelper;
import org.hibernate.annotations.JoinColumnOrFormula;
@@ -386,6 +387,22 @@
}
}
+
+
+ public void copyReferencedStructureAndCreateDefaultJoinColumns(
+ PersistentClass referencedEntity, Iterator columnIterator, SimpleValue value
+ ) {
+ if ( !isNameDeferred() ) {
+ throw new AssertionFailure( "Building implicit column but the column is not implicit" );
+ }
+ while ( columnIterator.hasNext() ) {
+ Column synthCol = (Column) columnIterator.next();
+ this.linkValueUsingDefaultColumnNaming( synthCol, referencedEntity, value );
+ }
+ //reset for the future
+ setMappingColumn( null );
+ }
+
public void linkValueUsingDefaultColumnNaming(
Column referencedColumn, PersistentClass referencedEntity, SimpleValue value
) {
Modified: core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/SimpleValueBinder.java
===================================================================
--- core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/SimpleValueBinder.java 2010-01-27 23:06:38 UTC (rev 18658)
+++ core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/SimpleValueBinder.java 2010-01-27 23:29:24 UTC (rev 18659)
@@ -27,7 +27,6 @@
import java.sql.Types;
import java.util.Calendar;
import java.util.Date;
-import java.util.Map;
import java.util.Properties;
import javax.persistence.Enumerated;
import javax.persistence.Lob;
@@ -36,6 +35,9 @@
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
import org.hibernate.AnnotationException;
import org.hibernate.AssertionFailure;
import org.hibernate.Hibernate;
@@ -49,7 +51,6 @@
import org.hibernate.cfg.ExtendedMappings;
import org.hibernate.cfg.NotYetImplementedException;
import org.hibernate.cfg.PkDrivenByDefaultMapsIdSecondPass;
-import org.hibernate.cfg.SecondPass;
import org.hibernate.cfg.SetSimpleValueTypeSecondPass;
import org.hibernate.mapping.SimpleValue;
import org.hibernate.mapping.Table;
@@ -59,8 +60,6 @@
import org.hibernate.type.SerializableToBlobType;
import org.hibernate.type.WrappedMaterializedBlobType;
import org.hibernate.util.StringHelper;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
/**
* @author Emmanuel Bernard
Modified: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e2/b/Dependent.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e2/b/Dependent.java 2010-01-27 23:06:38 UTC (rev 18658)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e2/b/Dependent.java 2010-01-27 23:29:24 UTC (rev 18659)
@@ -16,10 +16,10 @@
DependentId id;
@MapsId("empPK")
- @JoinColumns({
- @JoinColumn(name = "FK1", referencedColumnName = "firstName"),
- @JoinColumn(name = "FK2", referencedColumnName = "lastName")
- })
+// @JoinColumns({
+// @JoinColumn(name = "FK1", referencedColumnName = "firstName"),
+// @JoinColumn(name = "FK2", referencedColumnName = "lastName")
+// })
@ManyToOne
Employee emp;
}
Modified: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e2/b/DerivedIdentityIdClassParentEmbeddedIdDepTest.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e2/b/DerivedIdentityIdClassParentEmbeddedIdDepTest.java 2010-01-27 23:06:38 UTC (rev 18658)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e2/b/DerivedIdentityIdClassParentEmbeddedIdDepTest.java 2010-01-27 23:29:24 UTC (rev 18659)
@@ -10,8 +10,8 @@
public class DerivedIdentityIdClassParentEmbeddedIdDepTest extends TestCase {
public void testManyToOne() throws Exception {
- assertTrue( SchemaUtil.isColumnPresent( "Dependent", "FK1", getCfg() ) );
- assertTrue( SchemaUtil.isColumnPresent( "Dependent", "FK2", getCfg() ) );
+ assertTrue( SchemaUtil.isColumnPresent( "Dependent", "emp_firstName", getCfg() ) );
+ assertTrue( SchemaUtil.isColumnPresent( "Dependent", "emp_lastName", getCfg() ) );
assertTrue( SchemaUtil.isColumnPresent( "Dependent", "name", getCfg() ) );
assertTrue( ! SchemaUtil.isColumnPresent( "Dependent", "firstName", getCfg() ) );
assertTrue( ! SchemaUtil.isColumnPresent( "Dependent", "lastName", getCfg() ) );
@@ -42,8 +42,9 @@
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class<?>[] {
- Dependent.class,
- Employee.class
+ Employee.class,
+ Dependent.class
+
};
}
}
14 years, 10 months
Hibernate SVN: r18658 - in core/trunk: testsuite/src/test/java/org/hibernate/test/criteria and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: stliu
Date: 2010-01-27 18:06:38 -0500 (Wed, 27 Jan 2010)
New Revision: 18658
Added:
core/trunk/testsuite/src/test/java/org/hibernate/test/criteria/AbstractFoo.java
core/trunk/testsuite/src/test/java/org/hibernate/test/criteria/Bar.java
core/trunk/testsuite/src/test/java/org/hibernate/test/criteria/Foo.hbm.xml
core/trunk/testsuite/src/test/java/org/hibernate/test/criteria/GreatFoo.java
Modified:
core/trunk/core/src/main/java/org/hibernate/loader/criteria/CriteriaQueryTranslator.java
core/trunk/testsuite/src/test/java/org/hibernate/test/criteria/CriteriaQueryTest.java
Log:
HHH-3828 Criteria: Restriction whith class does not work
Modified: core/trunk/core/src/main/java/org/hibernate/loader/criteria/CriteriaQueryTranslator.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/loader/criteria/CriteriaQueryTranslator.java 2010-01-27 19:16:39 UTC (rev 18657)
+++ core/trunk/core/src/main/java/org/hibernate/loader/criteria/CriteriaQueryTranslator.java 2010-01-27 23:06:38 UTC (rev 18658)
@@ -531,6 +531,14 @@
if ( q != null ) {
Type type = q.getDiscriminatorType();
String stringValue = q.getDiscriminatorSQLValue();
+ if (stringValue != null && stringValue.length() > 2
+ && stringValue.startsWith("'")
+ && stringValue.endsWith("'")) { // remove the single
+ // quotes
+ stringValue = stringValue.substring(1,
+ stringValue.length() - 1);
+ }
+
// Convert the string value into the proper type.
if ( type instanceof NullableType ) {
NullableType nullableType = ( NullableType ) type;
Added: core/trunk/testsuite/src/test/java/org/hibernate/test/criteria/AbstractFoo.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/criteria/AbstractFoo.java (rev 0)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/criteria/AbstractFoo.java 2010-01-27 23:06:38 UTC (rev 18658)
@@ -0,0 +1,39 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ *
+ */
+package org.hibernate.test.criteria;
+
+
+public abstract class AbstractFoo {
+
+ private Integer id;
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+}
Added: core/trunk/testsuite/src/test/java/org/hibernate/test/criteria/Bar.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/criteria/Bar.java (rev 0)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/criteria/Bar.java 2010-01-27 23:06:38 UTC (rev 18658)
@@ -0,0 +1,47 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ *
+ */
+package org.hibernate.test.criteria;
+
+public class Bar {
+ private Integer id;
+
+ AbstractFoo myFoo;
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public AbstractFoo getMyFoo() {
+ return myFoo;
+ }
+
+ public void setMyFoo(AbstractFoo myFoo) {
+ this.myFoo = myFoo;
+ }
+}
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/criteria/CriteriaQueryTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/criteria/CriteriaQueryTest.java 2010-01-27 19:16:39 UTC (rev 18657)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/criteria/CriteriaQueryTest.java 2010-01-27 23:06:38 UTC (rev 18658)
@@ -41,7 +41,7 @@
}
public String[] getMappings() {
- return new String[] { "criteria/Enrolment.hbm.xml", "hql/Animal.hbm.xml" };
+ return new String[] { "criteria/Enrolment.hbm.xml","criteria/Foo.hbm.xml", "hql/Animal.hbm.xml" };
}
public void configure(Configuration cfg) {
@@ -707,6 +707,32 @@
s.close();
}
+ public void testClassProperty2() {
+ Session session = openSession();
+ Transaction t = session.beginTransaction();
+ GreatFoo foo = new GreatFoo();
+ Bar b = new Bar();
+ b.setMyFoo(foo);
+ foo.setId(1);
+ b.setId(1);
+ session.persist(b);
+ session.flush();
+ t.commit();
+ session=openSession();
+ t=session.beginTransaction();
+ // OK, one BAR in DB
+ assertEquals(1, session.createCriteria(Bar.class).list().size());
+ Criteria crit = session.createCriteria(Bar.class, "b").createAlias(
+ "myFoo", "m").add(
+ Property.forName("m.class").eq(GreatFoo.class));
+ assertEquals(1, crit.list().size());
+ crit = session.createCriteria(Bar.class, "b").createAlias("myFoo", "m")
+ .add(Restrictions.eq("m.class", GreatFoo.class));
+ assertEquals(1, crit.list().size());
+ t.commit();
+ session.close();
+ }
+
public void testProjectedId() {
Session s = openSession();
Transaction t = s.beginTransaction();
Added: core/trunk/testsuite/src/test/java/org/hibernate/test/criteria/Foo.hbm.xml
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/criteria/Foo.hbm.xml (rev 0)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/criteria/Foo.hbm.xml 2010-01-27 23:06:38 UTC (rev 18658)
@@ -0,0 +1,22 @@
+<?xml version="1.0"?>
+<!DOCTYPE hibernate-mapping PUBLIC
+ "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+ "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
+
+<hibernate-mapping package="org.hibernate.test.criteria">
+
+ <class name="AbstractFoo">
+ <id name="id">
+ </id>
+ <discriminator type="string" column="subtype" />
+ <subclass name="GreatFoo" discriminator-value="KAPUT">
+ </subclass>
+ </class>
+
+ <class name="Bar">
+ <id name="id">
+ </id>
+
+ <one-to-one name="myFoo" cascade="all" />
+ </class>
+</hibernate-mapping>
Property changes on: core/trunk/testsuite/src/test/java/org/hibernate/test/criteria/Foo.hbm.xml
___________________________________________________________________
Name: svn:executable
+ *
Added: core/trunk/testsuite/src/test/java/org/hibernate/test/criteria/GreatFoo.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/criteria/GreatFoo.java (rev 0)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/criteria/GreatFoo.java 2010-01-27 23:06:38 UTC (rev 18658)
@@ -0,0 +1,29 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ *
+ */
+package org.hibernate.test.criteria;
+
+public class GreatFoo extends AbstractFoo {
+
+}
14 years, 10 months
Hibernate SVN: r18657 - core/trunk/core/src/test/java/org/hibernate/util.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2010-01-27 14:16:39 -0500 (Wed, 27 Jan 2010)
New Revision: 18657
Added:
core/trunk/core/src/test/java/org/hibernate/util/SerializableThing.java
core/trunk/core/src/test/java/org/hibernate/util/SerializationHelperTest.java
Log:
HHH-4799 - Create a *unit* test that asserts SerializationHelper's ability to deser a class using an "isolated classloader" (aka a TCCL)
Added: core/trunk/core/src/test/java/org/hibernate/util/SerializableThing.java
===================================================================
--- core/trunk/core/src/test/java/org/hibernate/util/SerializableThing.java (rev 0)
+++ core/trunk/core/src/test/java/org/hibernate/util/SerializableThing.java 2010-01-27 19:16:39 UTC (rev 18657)
@@ -0,0 +1,34 @@
+/*
+ * 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.util;
+
+import java.io.Serializable;
+
+/**
+ * TODO : javadoc
+ *
+ * @author Steve Ebersole
+ */
+public class SerializableThing implements Serializable {
+}
Added: core/trunk/core/src/test/java/org/hibernate/util/SerializationHelperTest.java
===================================================================
--- core/trunk/core/src/test/java/org/hibernate/util/SerializationHelperTest.java (rev 0)
+++ core/trunk/core/src/test/java/org/hibernate/util/SerializationHelperTest.java 2010-01-27 19:16:39 UTC (rev 18657)
@@ -0,0 +1,100 @@
+/*
+ * 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.util;
+
+import java.io.InputStream;
+import java.io.Serializable;
+
+import junit.framework.TestCase;
+
+import org.hibernate.bytecode.util.ByteCodeHelper;
+
+/**
+ * This is basically a test to assert the expectations of {@link org.hibernate.type.SerializableType}
+ * in regards to deserializing bytes from second level caches.
+ *
+ * @author Steve Ebersole
+ */
+public class SerializationHelperTest extends TestCase {
+ private ClassLoader original;
+ private CustomClassLoader custom;
+
+ protected void setUp() throws Exception {
+ original = Thread.currentThread().getContextClassLoader();
+ custom = new CustomClassLoader( original );
+ Thread.currentThread().setContextClassLoader( custom );
+
+ }
+
+ protected void tearDown() throws Exception {
+ Thread.currentThread().setContextClassLoader( original );
+ }
+
+ public void testSerializeDeserialize() throws Exception {
+ Class clazz = Thread.currentThread().getContextClassLoader().loadClass( "org.hibernate.util.SerializableThing" );
+ Object instance = clazz.newInstance();
+
+ // SerializableType.toBytes() logic, as called from SerializableType.disassemble()
+ byte[] bytes = SerializationHelper.serialize( (Serializable) instance );
+
+ // SerializableType.fromBytes() logic, as called from SerializableType.assemble
+ // NOTE : specifically we use Serializable.class.getClassLoader for the CL in many cases
+ // which are the problematic cases
+ Object instance2 = SerializationHelper.deserialize( bytes, Serializable.class.getClassLoader() );
+
+ assertEquals( instance.getClass(), instance2.getClass() );
+ assertEquals( instance.getClass().getClassLoader(), instance2.getClass().getClassLoader() );
+ assertEquals( custom, instance2.getClass().getClassLoader() );
+ }
+
+ public static class CustomClassLoader extends ClassLoader {
+ public CustomClassLoader(ClassLoader parent) {
+ super( parent );
+ }
+
+ public Class loadClass(String name) throws ClassNotFoundException {
+ if ( ! name.equals( "org.hibernate.util.SerializableThing" ) ) {
+ return getParent().loadClass( name );
+ }
+
+ Class c = findLoadedClass( name );
+ if ( c != null ) {
+ return c;
+ }
+
+ InputStream is = this.getResourceAsStream( name.replace( '.', '/' ) + ".class" );
+ if ( is == null ) {
+ throw new ClassNotFoundException( name + " not found" );
+ }
+
+ try {
+ byte[] bytecode = ByteCodeHelper.readByteCode( is );
+ return defineClass( name, bytecode, 0, bytecode.length );
+ }
+ catch( Throwable t ) {
+ throw new ClassNotFoundException( name + " not found", t );
+ }
+ }
+ }
+}
14 years, 10 months
Hibernate SVN: r18656 - in core/trunk/annotations/src: test/java/org/hibernate/test/annotations/derivedidentities/e1/b and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2010-01-27 13:58:28 -0500 (Wed, 27 Jan 2010)
New Revision: 18656
Modified:
core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationBinder.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/b/DerivedIdentitySimpleParentEmbeddedIdDepTest.java
Log:
HHH-4858 add implicit PERSIST cascade when @MapsId is present
Modified: core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationBinder.java
===================================================================
--- core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationBinder.java 2010-01-27 18:46:51 UTC (rev 18655)
+++ core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationBinder.java 2010-01-27 18:58:28 UTC (rev 18656)
@@ -1328,479 +1328,482 @@
( (SimpleValue) rootClass.getVersion().getValue() ).getNullValue()
);
}
- else if ( property.isAnnotationPresent( ManyToOne.class ) ) {
- ManyToOne ann = property.getAnnotation( ManyToOne.class );
+ else {
+ final boolean isMapsId = property.isAnnotationPresent( MapsId.class );
+ if ( property.isAnnotationPresent( ManyToOne.class ) ) {
+ ManyToOne ann = property.getAnnotation( ManyToOne.class );
- //check validity
- if ( property.isAnnotationPresent( Column.class )
- || property.isAnnotationPresent( Columns.class ) ) {
- throw new AnnotationException( "@Column(s) not allowed on a @ManyToOne property: "
- + BinderHelper.getPath( propertyHolder, inferredData ) );
- }
+ //check validity
+ if ( property.isAnnotationPresent( Column.class )
+ || property.isAnnotationPresent( Columns.class ) ) {
+ throw new AnnotationException( "@Column(s) not allowed on a @ManyToOne property: "
+ + BinderHelper.getPath( propertyHolder, inferredData ) );
+ }
- Cascade hibernateCascade = property.getAnnotation( Cascade.class );
- NotFound notFound = property.getAnnotation( NotFound.class );
- boolean ignoreNotFound = notFound != null && notFound.action().equals( NotFoundAction.IGNORE );
- OnDelete onDeleteAnn = property.getAnnotation( OnDelete.class );
- boolean onDeleteCascade = onDeleteAnn != null && OnDeleteAction.CASCADE.equals( onDeleteAnn.action() );
- JoinTable assocTable = propertyHolder.getJoinTable( property );
- if ( assocTable != null ) {
- Join join = propertyHolder.addJoin( assocTable, false );
- for (Ejb3JoinColumn joinColumn : joinColumns) {
- joinColumn.setSecondaryTableName( join.getTable().getName() );
+ Cascade hibernateCascade = property.getAnnotation( Cascade.class );
+ NotFound notFound = property.getAnnotation( NotFound.class );
+ boolean ignoreNotFound = notFound != null && notFound.action().equals( NotFoundAction.IGNORE );
+ OnDelete onDeleteAnn = property.getAnnotation( OnDelete.class );
+ boolean onDeleteCascade = onDeleteAnn != null && OnDeleteAction.CASCADE.equals( onDeleteAnn.action() );
+ JoinTable assocTable = propertyHolder.getJoinTable( property );
+ if ( assocTable != null ) {
+ Join join = propertyHolder.addJoin( assocTable, false );
+ for (Ejb3JoinColumn joinColumn : joinColumns) {
+ joinColumn.setSecondaryTableName( join.getTable().getName() );
+ }
}
+ final boolean mandatory = !ann.optional() || isMapsId;
+ bindManyToOne(
+ getCascadeStrategy( ann.cascade(), hibernateCascade, false, isMapsId),
+ joinColumns,
+ !mandatory,
+ ignoreNotFound, onDeleteCascade,
+ ToOneBinder.getTargetEntity( inferredData, mappings ),
+ propertyHolder,
+ inferredData, false, isIdentifierMapper,
+ inSecondPass, propertyBinder, mappings
+ );
}
- final boolean mandatory = !ann.optional() || property.isAnnotationPresent( MapsId.class );
- bindManyToOne(
- getCascadeStrategy( ann.cascade(), hibernateCascade, false),
- joinColumns,
- !mandatory,
- ignoreNotFound, onDeleteCascade,
- ToOneBinder.getTargetEntity( inferredData, mappings ),
- propertyHolder,
- inferredData, false, isIdentifierMapper,
- inSecondPass, propertyBinder, mappings
- );
- }
- else if ( property.isAnnotationPresent( OneToOne.class ) ) {
- OneToOne ann = property.getAnnotation( OneToOne.class );
+ else if ( property.isAnnotationPresent( OneToOne.class ) ) {
+ OneToOne ann = property.getAnnotation( OneToOne.class );
- //check validity
- if ( property.isAnnotationPresent( Column.class )
- || property.isAnnotationPresent( Columns.class ) ) {
- throw new AnnotationException( "@Column(s) not allowed on a @OneToOne property: "
- + BinderHelper.getPath( propertyHolder, inferredData ) );
- }
-
- //FIXME support a proper PKJCs
- boolean trueOneToOne = property.isAnnotationPresent( PrimaryKeyJoinColumn.class )
- || property.isAnnotationPresent( PrimaryKeyJoinColumns.class );
- Cascade hibernateCascade = property.getAnnotation( Cascade.class );
- NotFound notFound = property.getAnnotation( NotFound.class );
- boolean ignoreNotFound = notFound != null && notFound.action().equals( NotFoundAction.IGNORE );
- OnDelete onDeleteAnn = property.getAnnotation( OnDelete.class );
- boolean onDeleteCascade = onDeleteAnn != null && OnDeleteAction.CASCADE.equals( onDeleteAnn.action() );
- JoinTable assocTable = propertyHolder.getJoinTable( property );
- if ( assocTable != null ) {
- Join join = propertyHolder.addJoin( assocTable, false );
- for (Ejb3JoinColumn joinColumn : joinColumns) {
- joinColumn.setSecondaryTableName( join.getTable().getName() );
+ //check validity
+ if ( property.isAnnotationPresent( Column.class )
+ || property.isAnnotationPresent( Columns.class ) ) {
+ throw new AnnotationException( "@Column(s) not allowed on a @OneToOne property: "
+ + BinderHelper.getPath( propertyHolder, inferredData ) );
}
- }
- //MapsId means the columns belong to the pk => not null
- final boolean mandatory = !ann.optional() || property.isAnnotationPresent( MapsId.class );
- bindOneToOne(
- getCascadeStrategy( ann.cascade(), hibernateCascade, ann.orphanRemoval()),
- joinColumns,
- !mandatory,
- getFetchMode( ann.fetch() ),
- ignoreNotFound, onDeleteCascade,
- ToOneBinder.getTargetEntity( inferredData, mappings ),
- propertyHolder,
- inferredData,
- ann.mappedBy(),
- trueOneToOne,
- isIdentifierMapper,
- inSecondPass,
- propertyBinder,
- mappings
- );
- }
- else if ( property.isAnnotationPresent( org.hibernate.annotations.Any.class ) ) {
- //check validity
- if ( property.isAnnotationPresent( Column.class )
- || property.isAnnotationPresent( Columns.class ) ) {
- throw new AnnotationException( "@Column(s) not allowed on a @Any property: "
- + BinderHelper.getPath( propertyHolder, inferredData ) );
- }
-
- Cascade hibernateCascade = property.getAnnotation( Cascade.class );
- OnDelete onDeleteAnn = property.getAnnotation( OnDelete.class );
- boolean onDeleteCascade = onDeleteAnn != null && OnDeleteAction.CASCADE.equals( onDeleteAnn.action() );
- JoinTable assocTable = propertyHolder.getJoinTable( property );
- if ( assocTable != null ) {
- Join join = propertyHolder.addJoin( assocTable, false );
- for (Ejb3JoinColumn joinColumn : joinColumns) {
- joinColumn.setSecondaryTableName( join.getTable().getName() );
+ //FIXME support a proper PKJCs
+ boolean trueOneToOne = property.isAnnotationPresent( PrimaryKeyJoinColumn.class )
+ || property.isAnnotationPresent( PrimaryKeyJoinColumns.class );
+ Cascade hibernateCascade = property.getAnnotation( Cascade.class );
+ NotFound notFound = property.getAnnotation( NotFound.class );
+ boolean ignoreNotFound = notFound != null && notFound.action().equals( NotFoundAction.IGNORE );
+ OnDelete onDeleteAnn = property.getAnnotation( OnDelete.class );
+ boolean onDeleteCascade = onDeleteAnn != null && OnDeleteAction.CASCADE.equals( onDeleteAnn.action() );
+ JoinTable assocTable = propertyHolder.getJoinTable( property );
+ if ( assocTable != null ) {
+ Join join = propertyHolder.addJoin( assocTable, false );
+ for (Ejb3JoinColumn joinColumn : joinColumns) {
+ joinColumn.setSecondaryTableName( join.getTable().getName() );
+ }
}
- }
- bindAny( getCascadeStrategy( null, hibernateCascade, false), //@Any has not cascade attribute
- joinColumns, onDeleteCascade, nullability,
- propertyHolder, inferredData, entityBinder,
- isIdentifierMapper, mappings );
- }
- else if ( property.isAnnotationPresent( OneToMany.class )
- || property.isAnnotationPresent( ManyToMany.class )
- || property.isAnnotationPresent( CollectionOfElements.class ) //legacy Hibernate
- || property.isAnnotationPresent( ElementCollection.class )
- || property.isAnnotationPresent( ManyToAny.class ) ) {
- OneToMany oneToManyAnn = property.getAnnotation( OneToMany.class );
- ManyToMany manyToManyAnn = property.getAnnotation( ManyToMany.class );
- ElementCollection elementCollectionAnn = property.getAnnotation( ElementCollection.class );
- CollectionOfElements collectionOfElementsAnn = property.getAnnotation( CollectionOfElements.class ); //legacy hibernate
-
- final IndexColumn indexColumn;
-
- if ( property.isAnnotationPresent( OrderColumn.class ) ) {
- indexColumn = IndexColumn.buildColumnFromAnnotation(
- property.getAnnotation(OrderColumn.class),
+ //MapsId means the columns belong to the pk => not null
+ final boolean mandatory = !ann.optional() || isMapsId;
+ bindOneToOne(
+ getCascadeStrategy( ann.cascade(), hibernateCascade, ann.orphanRemoval(), isMapsId),
+ joinColumns,
+ !mandatory,
+ getFetchMode( ann.fetch() ),
+ ignoreNotFound, onDeleteCascade,
+ ToOneBinder.getTargetEntity( inferredData, mappings ),
propertyHolder,
inferredData,
- entityBinder.getSecondaryTables(),
+ ann.mappedBy(),
+ trueOneToOne,
+ isIdentifierMapper,
+ inSecondPass,
+ propertyBinder,
mappings
);
}
- else {
- //if @IndexColumn is not there, the generated IndexColumn is an implicit column and not used.
- //so we can leave the legacy processing as the default
- indexColumn = IndexColumn.buildColumnFromAnnotation(
- property.getAnnotation(org.hibernate.annotations.IndexColumn.class),
- propertyHolder,
- inferredData,
- mappings
- );
- }
- CollectionBinder collectionBinder = CollectionBinder.getCollectionBinder(
- propertyHolder.getEntityName(),
- property,
- !indexColumn.isImplicit(),
- property.isAnnotationPresent( CollectionOfElements.class )
- || property.isAnnotationPresent( org.hibernate.annotations.MapKey.class )
- // || property.isAnnotationPresent( ManyToAny.class )
- );
- collectionBinder.setIndexColumn( indexColumn );
- MapKey mapKeyAnn = property.getAnnotation( MapKey.class );
- collectionBinder.setMapKey( mapKeyAnn );
- collectionBinder.setPropertyName( inferredData.getPropertyName() );
- BatchSize batchAnn = property.getAnnotation( BatchSize.class );
- collectionBinder.setBatchSize( batchAnn );
- javax.persistence.OrderBy ejb3OrderByAnn = property.getAnnotation( javax.persistence.OrderBy.class );
- OrderBy orderByAnn = property.getAnnotation( OrderBy.class );
- collectionBinder.setEjb3OrderBy( ejb3OrderByAnn );
- collectionBinder.setSqlOrderBy( orderByAnn );
- Sort sortAnn = property.getAnnotation( Sort.class );
- collectionBinder.setSort( sortAnn );
- Cache cachAnn = property.getAnnotation( Cache.class );
- collectionBinder.setCache( cachAnn );
- collectionBinder.setPropertyHolder( propertyHolder );
- Cascade hibernateCascade = property.getAnnotation( Cascade.class );
- NotFound notFound = property.getAnnotation( NotFound.class );
- boolean ignoreNotFound = notFound != null && notFound.action().equals( NotFoundAction.IGNORE );
- collectionBinder.setIgnoreNotFound( ignoreNotFound );
- collectionBinder.setCollectionType( inferredData.getProperty().getElementClass() );
- collectionBinder.setMappings( mappings );
- collectionBinder.setAccessType( inferredData.getDefaultAccess() );
+ else if ( property.isAnnotationPresent( org.hibernate.annotations.Any.class ) ) {
- Ejb3Column[] elementColumns;
- //do not use "element" if you are a JPA 2 @ElementCollection only for legacy Hibernate mappings
- boolean isJPA2ForValueMapping = property.isAnnotationPresent( ElementCollection.class );
- PropertyData virtualProperty = isJPA2ForValueMapping ? inferredData : new WrappedInferredData( inferredData, "element" );
- if ( property.isAnnotationPresent( Column.class ) || property.isAnnotationPresent(
- Formula.class
- ) ) {
- Column ann = property.getAnnotation( Column.class );
- Formula formulaAnn = property.getAnnotation( Formula.class );
- elementColumns = Ejb3Column.buildColumnFromAnnotation(
- new Column[] { ann },
- formulaAnn,
- nullability,
- propertyHolder,
- virtualProperty,
- entityBinder.getSecondaryTables(),
- mappings
- );
- }
- else if ( property.isAnnotationPresent( Columns.class ) ) {
- Columns anns = property.getAnnotation( Columns.class );
- elementColumns = Ejb3Column.buildColumnFromAnnotation(
- anns.columns(), null, nullability, propertyHolder, virtualProperty,
- entityBinder.getSecondaryTables(), mappings
- );
- }
- else {
- elementColumns = Ejb3Column.buildColumnFromAnnotation(
- null,
- null,
- nullability,
- propertyHolder,
- virtualProperty,
- entityBinder.getSecondaryTables(),
- mappings
- );
- }
- {
- Column[] keyColumns = null;
- //JPA 2 has priority and has different default column values, differenciate legacy from JPA 2
- Boolean isJPA2 = null;
- if ( property.isAnnotationPresent( MapKeyColumn.class ) ) {
- isJPA2 = Boolean.TRUE;
- keyColumns = new Column[] { new MapKeyColumnDelegator( property.getAnnotation( MapKeyColumn.class ) ) };
+ //check validity
+ if ( property.isAnnotationPresent( Column.class )
+ || property.isAnnotationPresent( Columns.class ) ) {
+ throw new AnnotationException( "@Column(s) not allowed on a @Any property: "
+ + BinderHelper.getPath( propertyHolder, inferredData ) );
}
- else if ( property.isAnnotationPresent( org.hibernate.annotations.MapKey.class ) ) {
- if ( isJPA2 == null) {
- isJPA2 = Boolean.FALSE;
+
+ Cascade hibernateCascade = property.getAnnotation( Cascade.class );
+ OnDelete onDeleteAnn = property.getAnnotation( OnDelete.class );
+ boolean onDeleteCascade = onDeleteAnn != null && OnDeleteAction.CASCADE.equals( onDeleteAnn.action() );
+ JoinTable assocTable = propertyHolder.getJoinTable( property );
+ if ( assocTable != null ) {
+ Join join = propertyHolder.addJoin( assocTable, false );
+ for (Ejb3JoinColumn joinColumn : joinColumns) {
+ joinColumn.setSecondaryTableName( join.getTable().getName() );
}
- keyColumns = property.getAnnotation( org.hibernate.annotations.MapKey.class ).columns();
}
+ bindAny( getCascadeStrategy( null, hibernateCascade, false, isMapsId), //@Any has not cascade attribute
+ joinColumns, onDeleteCascade, nullability,
+ propertyHolder, inferredData, entityBinder,
+ isIdentifierMapper, mappings );
+ }
+ else if ( property.isAnnotationPresent( OneToMany.class )
+ || property.isAnnotationPresent( ManyToMany.class )
+ || property.isAnnotationPresent( CollectionOfElements.class ) //legacy Hibernate
+ || property.isAnnotationPresent( ElementCollection.class )
+ || property.isAnnotationPresent( ManyToAny.class ) ) {
+ OneToMany oneToManyAnn = property.getAnnotation( OneToMany.class );
+ ManyToMany manyToManyAnn = property.getAnnotation( ManyToMany.class );
+ ElementCollection elementCollectionAnn = property.getAnnotation( ElementCollection.class );
+ CollectionOfElements collectionOfElementsAnn = property.getAnnotation( CollectionOfElements.class ); //legacy hibernate
- //not explicitly legacy
- if ( isJPA2 == null) {
- isJPA2 = Boolean.TRUE;
+ final IndexColumn indexColumn;
+
+ if ( property.isAnnotationPresent( OrderColumn.class ) ) {
+ indexColumn = IndexColumn.buildColumnFromAnnotation(
+ property.getAnnotation(OrderColumn.class),
+ propertyHolder,
+ inferredData,
+ entityBinder.getSecondaryTables(),
+ mappings
+ );
}
+ else {
+ //if @IndexColumn is not there, the generated IndexColumn is an implicit column and not used.
+ //so we can leave the legacy processing as the default
+ indexColumn = IndexColumn.buildColumnFromAnnotation(
+ property.getAnnotation(org.hibernate.annotations.IndexColumn.class),
+ propertyHolder,
+ inferredData,
+ mappings
+ );
+ }
+ CollectionBinder collectionBinder = CollectionBinder.getCollectionBinder(
+ propertyHolder.getEntityName(),
+ property,
+ !indexColumn.isImplicit(),
+ property.isAnnotationPresent( CollectionOfElements.class )
+ || property.isAnnotationPresent( org.hibernate.annotations.MapKey.class )
+ // || property.isAnnotationPresent( ManyToAny.class )
+ );
+ collectionBinder.setIndexColumn( indexColumn );
+ MapKey mapKeyAnn = property.getAnnotation( MapKey.class );
+ collectionBinder.setMapKey( mapKeyAnn );
+ collectionBinder.setPropertyName( inferredData.getPropertyName() );
+ BatchSize batchAnn = property.getAnnotation( BatchSize.class );
+ collectionBinder.setBatchSize( batchAnn );
+ javax.persistence.OrderBy ejb3OrderByAnn = property.getAnnotation( javax.persistence.OrderBy.class );
+ OrderBy orderByAnn = property.getAnnotation( OrderBy.class );
+ collectionBinder.setEjb3OrderBy( ejb3OrderByAnn );
+ collectionBinder.setSqlOrderBy( orderByAnn );
+ Sort sortAnn = property.getAnnotation( Sort.class );
+ collectionBinder.setSort( sortAnn );
+ Cache cachAnn = property.getAnnotation( Cache.class );
+ collectionBinder.setCache( cachAnn );
+ collectionBinder.setPropertyHolder( propertyHolder );
+ Cascade hibernateCascade = property.getAnnotation( Cascade.class );
+ NotFound notFound = property.getAnnotation( NotFound.class );
+ boolean ignoreNotFound = notFound != null && notFound.action().equals( NotFoundAction.IGNORE );
+ collectionBinder.setIgnoreNotFound( ignoreNotFound );
+ collectionBinder.setCollectionType( inferredData.getProperty().getElementClass() );
+ collectionBinder.setMappings( mappings );
+ collectionBinder.setAccessType( inferredData.getDefaultAccess() );
- //nullify empty array
- keyColumns = keyColumns != null && keyColumns.length > 0 ? keyColumns : null;
-
- //"mapkey" is the legacy column name of the key column pre JPA 2
- PropertyData mapKeyVirtualProperty = new WrappedInferredData( inferredData, "mapkey" );
- Ejb3Column[] mapColumns = Ejb3Column.buildColumnFromAnnotation(
- keyColumns,
- null,
- Nullability.FORCED_NOT_NULL,
- propertyHolder,
- isJPA2 ? inferredData : mapKeyVirtualProperty,
- isJPA2 ? "_KEY" : null,
- entityBinder.getSecondaryTables(),
- mappings
- );
- collectionBinder.setMapKeyColumns( mapColumns );
- }
- {
- JoinColumn[] joinKeyColumns = null;
- //JPA 2 has priority and has different default column values, differenciate legacy from JPA 2
- Boolean isJPA2 = null;
- if ( property.isAnnotationPresent( MapKeyJoinColumns.class ) ) {
- isJPA2 = Boolean.TRUE;
- final MapKeyJoinColumn[] mapKeyJoinColumns = property.getAnnotation( MapKeyJoinColumns.class ).value();
- joinKeyColumns = new JoinColumn[mapKeyJoinColumns.length];
- int index = 0;
- for ( MapKeyJoinColumn joinColumn : mapKeyJoinColumns ) {
- joinKeyColumns[index] = new MapKeyJoinColumnDelegator( joinColumn );
- index++;
+ Ejb3Column[] elementColumns;
+ //do not use "element" if you are a JPA 2 @ElementCollection only for legacy Hibernate mappings
+ boolean isJPA2ForValueMapping = property.isAnnotationPresent( ElementCollection.class );
+ PropertyData virtualProperty = isJPA2ForValueMapping ? inferredData : new WrappedInferredData( inferredData, "element" );
+ if ( property.isAnnotationPresent( Column.class ) || property.isAnnotationPresent(
+ Formula.class
+ ) ) {
+ Column ann = property.getAnnotation( Column.class );
+ Formula formulaAnn = property.getAnnotation( Formula.class );
+ elementColumns = Ejb3Column.buildColumnFromAnnotation(
+ new Column[] { ann },
+ formulaAnn,
+ nullability,
+ propertyHolder,
+ virtualProperty,
+ entityBinder.getSecondaryTables(),
+ mappings
+ );
+ }
+ else if ( property.isAnnotationPresent( Columns.class ) ) {
+ Columns anns = property.getAnnotation( Columns.class );
+ elementColumns = Ejb3Column.buildColumnFromAnnotation(
+ anns.columns(), null, nullability, propertyHolder, virtualProperty,
+ entityBinder.getSecondaryTables(), mappings
+ );
+ }
+ else {
+ elementColumns = Ejb3Column.buildColumnFromAnnotation(
+ null,
+ null,
+ nullability,
+ propertyHolder,
+ virtualProperty,
+ entityBinder.getSecondaryTables(),
+ mappings
+ );
+ }
+ {
+ Column[] keyColumns = null;
+ //JPA 2 has priority and has different default column values, differenciate legacy from JPA 2
+ Boolean isJPA2 = null;
+ if ( property.isAnnotationPresent( MapKeyColumn.class ) ) {
+ isJPA2 = Boolean.TRUE;
+ keyColumns = new Column[] { new MapKeyColumnDelegator( property.getAnnotation( MapKeyColumn.class ) ) };
}
- if ( joinKeyColumns != null ) {
- throw new AnnotationException( "@MapKeyJoinColumn and @MapKeyJoinColumns used on the same property: "
- + BinderHelper.getPath( propertyHolder, inferredData ) );
+ else if ( property.isAnnotationPresent( org.hibernate.annotations.MapKey.class ) ) {
+ if ( isJPA2 == null) {
+ isJPA2 = Boolean.FALSE;
+ }
+ keyColumns = property.getAnnotation( org.hibernate.annotations.MapKey.class ).columns();
}
- }
- else if ( property.isAnnotationPresent( MapKeyJoinColumn.class ) ) {
- isJPA2 = Boolean.TRUE;
- joinKeyColumns = new JoinColumn[] { new MapKeyJoinColumnDelegator( property.getAnnotation( MapKeyJoinColumn.class ) ) };
- }
- else if ( property.isAnnotationPresent( org.hibernate.annotations.MapKeyManyToMany.class ) ) {
+
+ //not explicitly legacy
if ( isJPA2 == null) {
- isJPA2 = Boolean.FALSE;
+ isJPA2 = Boolean.TRUE;
}
- joinKeyColumns = property.getAnnotation( org.hibernate.annotations.MapKeyManyToMany.class ).joinColumns();
- }
- //not explicitly legacy
- if ( isJPA2 == null) {
- isJPA2 = Boolean.TRUE;
- }
+ //nullify empty array
+ keyColumns = keyColumns != null && keyColumns.length > 0 ? keyColumns : null;
- PropertyData mapKeyVirtualProperty = new WrappedInferredData( inferredData, "mapkey" );
- Ejb3JoinColumn[] mapJoinColumns = Ejb3JoinColumn.buildJoinColumnsWithDefaultColumnSuffix(
- joinKeyColumns,
- null,
- entityBinder.getSecondaryTables(),
- propertyHolder,
- isJPA2 ? inferredData.getPropertyName() : mapKeyVirtualProperty.getPropertyName(),
- isJPA2 ? "_KEY" : null,
- mappings
- );
- collectionBinder.setMapKeyManyToManyColumns( mapJoinColumns );
- }
-
- //potential element
- collectionBinder.setEmbedded( property.isAnnotationPresent( Embedded.class ) );
- collectionBinder.setElementColumns( elementColumns );
- collectionBinder.setProperty( property );
-
- //TODO enhance exception with @ManyToAny and @CollectionOfElements
- if ( oneToManyAnn != null && manyToManyAnn != null ) {
- throw new AnnotationException(
- "@OneToMany and @ManyToMany on the same property is not allowed: "
- + propertyHolder.getEntityName() + "." + inferredData.getPropertyName()
- );
- }
- String mappedBy = null;
- if ( oneToManyAnn != null ) {
- for (Ejb3JoinColumn column : joinColumns) {
- if ( column.isSecondary() ) {
- throw new NotYetImplementedException( "Collections having FK in secondary table" );
- }
+ //"mapkey" is the legacy column name of the key column pre JPA 2
+ PropertyData mapKeyVirtualProperty = new WrappedInferredData( inferredData, "mapkey" );
+ Ejb3Column[] mapColumns = Ejb3Column.buildColumnFromAnnotation(
+ keyColumns,
+ null,
+ Nullability.FORCED_NOT_NULL,
+ propertyHolder,
+ isJPA2 ? inferredData : mapKeyVirtualProperty,
+ isJPA2 ? "_KEY" : null,
+ entityBinder.getSecondaryTables(),
+ mappings
+ );
+ collectionBinder.setMapKeyColumns( mapColumns );
}
- collectionBinder.setFkJoinColumns( joinColumns );
- mappedBy = oneToManyAnn.mappedBy();
- collectionBinder.setTargetEntity(
- mappings.getReflectionManager().toXClass( oneToManyAnn.targetEntity() )
- );
- collectionBinder.setCascadeStrategy(
- getCascadeStrategy( oneToManyAnn.cascade(), hibernateCascade, oneToManyAnn.orphanRemoval()) );
- collectionBinder.setOneToMany( true );
- }
- else if ( elementCollectionAnn != null
- || collectionOfElementsAnn != null //Hibernate legacy
- ) {
- for (Ejb3JoinColumn column : joinColumns) {
- if ( column.isSecondary() ) {
- throw new NotYetImplementedException( "Collections having FK in secondary table" );
+ {
+ JoinColumn[] joinKeyColumns = null;
+ //JPA 2 has priority and has different default column values, differenciate legacy from JPA 2
+ Boolean isJPA2 = null;
+ if ( property.isAnnotationPresent( MapKeyJoinColumns.class ) ) {
+ isJPA2 = Boolean.TRUE;
+ final MapKeyJoinColumn[] mapKeyJoinColumns = property.getAnnotation( MapKeyJoinColumns.class ).value();
+ joinKeyColumns = new JoinColumn[mapKeyJoinColumns.length];
+ int index = 0;
+ for ( MapKeyJoinColumn joinColumn : mapKeyJoinColumns ) {
+ joinKeyColumns[index] = new MapKeyJoinColumnDelegator( joinColumn );
+ index++;
+ }
+ if ( joinKeyColumns != null ) {
+ throw new AnnotationException( "@MapKeyJoinColumn and @MapKeyJoinColumns used on the same property: "
+ + BinderHelper.getPath( propertyHolder, inferredData ) );
+ }
}
- }
- collectionBinder.setFkJoinColumns( joinColumns );
- mappedBy = "";
- final Class<?> targetElement = elementCollectionAnn != null ?
- elementCollectionAnn.targetClass() :
- collectionOfElementsAnn.targetElement();
- collectionBinder.setTargetEntity(
- mappings.getReflectionManager().toXClass( targetElement )
- );
- //collectionBinder.setCascadeStrategy( getCascadeStrategy( embeddedCollectionAnn.cascade(), hibernateCascade ) );
- collectionBinder.setOneToMany( true );
- }
- else if ( manyToManyAnn != null ) {
- mappedBy = manyToManyAnn.mappedBy();
- collectionBinder.setTargetEntity(
- mappings.getReflectionManager().toXClass( manyToManyAnn.targetEntity() )
- );
- collectionBinder.setCascadeStrategy( getCascadeStrategy( manyToManyAnn.cascade(), hibernateCascade, false) );
- collectionBinder.setOneToMany( false );
- }
- else if ( property.isAnnotationPresent( ManyToAny.class ) ) {
- mappedBy = "";
- collectionBinder.setTargetEntity(
- mappings.getReflectionManager().toXClass( void.class )
- );
- collectionBinder.setCascadeStrategy( getCascadeStrategy( null, hibernateCascade, false) );
- collectionBinder.setOneToMany( false );
- }
- collectionBinder.setMappedBy( mappedBy );
+ else if ( property.isAnnotationPresent( MapKeyJoinColumn.class ) ) {
+ isJPA2 = Boolean.TRUE;
+ joinKeyColumns = new JoinColumn[] { new MapKeyJoinColumnDelegator( property.getAnnotation( MapKeyJoinColumn.class ) ) };
+ }
+ else if ( property.isAnnotationPresent( org.hibernate.annotations.MapKeyManyToMany.class ) ) {
+ if ( isJPA2 == null) {
+ isJPA2 = Boolean.FALSE;
+ }
+ joinKeyColumns = property.getAnnotation( org.hibernate.annotations.MapKeyManyToMany.class ).joinColumns();
+ }
- bindJoinedTableAssociation(
- property, mappings, entityBinder, collectionBinder, propertyHolder, inferredData, mappedBy
- );
+ //not explicitly legacy
+ if ( isJPA2 == null) {
+ isJPA2 = Boolean.TRUE;
+ }
- OnDelete onDeleteAnn = property.getAnnotation( OnDelete.class );
- boolean onDeleteCascade = onDeleteAnn != null && OnDeleteAction.CASCADE.equals( onDeleteAnn.action() );
- collectionBinder.setCascadeDeleteEnabled( onDeleteCascade );
- if ( isIdentifierMapper ) {
- collectionBinder.setInsertable( false );
- collectionBinder.setUpdatable( false );
- }
- if ( property.isAnnotationPresent( CollectionId.class ) ) { //do not compute the generators unless necessary
- HashMap<String, IdGenerator> localGenerators = (HashMap<String, IdGenerator>) classGenerators.clone();
- localGenerators.putAll( buildLocalGenerators( property, mappings ) );
- collectionBinder.setLocalGenerators( localGenerators );
+ PropertyData mapKeyVirtualProperty = new WrappedInferredData( inferredData, "mapkey" );
+ Ejb3JoinColumn[] mapJoinColumns = Ejb3JoinColumn.buildJoinColumnsWithDefaultColumnSuffix(
+ joinKeyColumns,
+ null,
+ entityBinder.getSecondaryTables(),
+ propertyHolder,
+ isJPA2 ? inferredData.getPropertyName() : mapKeyVirtualProperty.getPropertyName(),
+ isJPA2 ? "_KEY" : null,
+ mappings
+ );
+ collectionBinder.setMapKeyManyToManyColumns( mapJoinColumns );
+ }
- }
- collectionBinder.setInheritanceStatePerClass( inheritanceStatePerClass );
- collectionBinder.setDeclaringClass( inferredData.getDeclaringClass() );
- collectionBinder.bind();
+ //potential element
+ collectionBinder.setEmbedded( property.isAnnotationPresent( Embedded.class ) );
+ collectionBinder.setElementColumns( elementColumns );
+ collectionBinder.setProperty( property );
- }
- //Either a regular property or a basic @Id or @EmbeddedId while not ignoring id annotations
- else if ( !isId || !entityBinder.isIgnoreIdAnnotations() ) {
- //define whether the type is a component or not
- boolean isComponent;
- isComponent = property.isAnnotationPresent( Embedded.class )
- || property.isAnnotationPresent( EmbeddedId.class )
- || returnedClass.isAnnotationPresent( Embeddable.class );
-
- //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() ) {
- Ejb3Column[] oldColumns = columns;
- columns = columnsBuilder.overrideColumnFromMapsIdProperty(isId);
- isOverridden = oldColumns != columns;
- }
- if ( isComponent ) {
- String referencedEntityName = null;
- if (isOverridden) {
- final PropertyData mapsIdProperty = BinderHelper.getPropertyAnnotatedWithMapsId(
- isId, propertyHolder, property.getName(), mappings
+ //TODO enhance exception with @ManyToAny and @CollectionOfElements
+ if ( oneToManyAnn != null && manyToManyAnn != null ) {
+ throw new AnnotationException(
+ "@OneToMany and @ManyToMany on the same property is not allowed: "
+ + propertyHolder.getEntityName() + "." + inferredData.getPropertyName()
);
- referencedEntityName = mapsIdProperty.getClassOrElementName();
}
- AccessType propertyAccessor = entityBinder.getPropertyAccessor( property );
- propertyBinder = bindComponent(
- inferredData,
- propertyHolder,
- propertyAccessor,
- entityBinder,
- isIdentifierMapper,
- mappings,
- isComponentEmbedded,
- isId,
- inheritanceStatePerClass,
- referencedEntityName,
- isOverridden ? (Ejb3JoinColumn[]) columns : null
- );
- }
- else {
- //provide the basic property mapping
- boolean optional = true;
- boolean lazy = false;
- if ( property.isAnnotationPresent( Basic.class ) ) {
- Basic ann = property.getAnnotation( Basic.class );
- optional = ann.optional();
- lazy = ann.fetch() == FetchType.LAZY;
+ String mappedBy = null;
+ if ( oneToManyAnn != null ) {
+ for (Ejb3JoinColumn column : joinColumns) {
+ if ( column.isSecondary() ) {
+ throw new NotYetImplementedException( "Collections having FK in secondary table" );
+ }
+ }
+ collectionBinder.setFkJoinColumns( joinColumns );
+ mappedBy = oneToManyAnn.mappedBy();
+ collectionBinder.setTargetEntity(
+ mappings.getReflectionManager().toXClass( oneToManyAnn.targetEntity() )
+ );
+ collectionBinder.setCascadeStrategy(
+ getCascadeStrategy( oneToManyAnn.cascade(), hibernateCascade, oneToManyAnn.orphanRemoval(), false) );
+ collectionBinder.setOneToMany( true );
}
- //implicit type will check basic types and Serializable classes
- if ( isId || ( !optional && nullability != Nullability.FORCED_NULL ) ) {
- //force columns to not null
- for (Ejb3Column col : columns) {
- col.forceNotNull();
+ else if ( elementCollectionAnn != null
+ || collectionOfElementsAnn != null //Hibernate legacy
+ ) {
+ for (Ejb3JoinColumn column : joinColumns) {
+ if ( column.isSecondary() ) {
+ throw new NotYetImplementedException( "Collections having FK in secondary table" );
+ }
}
+ collectionBinder.setFkJoinColumns( joinColumns );
+ mappedBy = "";
+ final Class<?> targetElement = elementCollectionAnn != null ?
+ elementCollectionAnn.targetClass() :
+ collectionOfElementsAnn.targetElement();
+ collectionBinder.setTargetEntity(
+ mappings.getReflectionManager().toXClass( targetElement )
+ );
+ //collectionBinder.setCascadeStrategy( getCascadeStrategy( embeddedCollectionAnn.cascade(), hibernateCascade ) );
+ collectionBinder.setOneToMany( true );
}
-
- propertyBinder.setLazy( lazy );
- propertyBinder.setColumns( columns );
- if (isOverridden) {
- final PropertyData mapsIdProperty = BinderHelper.getPropertyAnnotatedWithMapsId(
- isId, propertyHolder, property.getName(), mappings
+ else if ( manyToManyAnn != null ) {
+ mappedBy = manyToManyAnn.mappedBy();
+ collectionBinder.setTargetEntity(
+ mappings.getReflectionManager().toXClass( manyToManyAnn.targetEntity() )
);
- propertyBinder.setReferencedEntityName( mapsIdProperty.getClassOrElementName() );
+ collectionBinder.setCascadeStrategy( getCascadeStrategy( manyToManyAnn.cascade(), hibernateCascade, false, false) );
+ collectionBinder.setOneToMany( false );
}
+ else if ( property.isAnnotationPresent( ManyToAny.class ) ) {
+ mappedBy = "";
+ collectionBinder.setTargetEntity(
+ mappings.getReflectionManager().toXClass( void.class )
+ );
+ collectionBinder.setCascadeStrategy( getCascadeStrategy( null, hibernateCascade, false, false) );
+ collectionBinder.setOneToMany( false );
+ }
+ collectionBinder.setMappedBy( mappedBy );
- propertyBinder.makePropertyValueAndBind();
+ bindJoinedTableAssociation(
+ property, mappings, entityBinder, collectionBinder, propertyHolder, inferredData, mappedBy
+ );
- }
- if (isOverridden) {
- final PropertyData mapsIdProperty = BinderHelper.getPropertyAnnotatedWithMapsId(
- isId, propertyHolder, property.getName(), mappings
- );
+ OnDelete onDeleteAnn = property.getAnnotation( OnDelete.class );
+ boolean onDeleteCascade = onDeleteAnn != null && OnDeleteAction.CASCADE.equals( onDeleteAnn.action() );
+ collectionBinder.setCascadeDeleteEnabled( onDeleteCascade );
+ if ( isIdentifierMapper ) {
+ collectionBinder.setInsertable( false );
+ collectionBinder.setUpdatable( false );
+ }
+ if ( property.isAnnotationPresent( CollectionId.class ) ) { //do not compute the generators unless necessary
HashMap<String, IdGenerator> localGenerators = (HashMap<String, IdGenerator>) classGenerators.clone();
- final IdGenerator foreignGenerator = new IdGenerator();
- foreignGenerator.setIdentifierGeneratorStrategy( "assigned" );
- foreignGenerator.setName( "Hibernate-local--foreign generator" );
- foreignGenerator.setIdentifierGeneratorStrategy( "foreign" );
- foreignGenerator.addParam( "property", mapsIdProperty.getPropertyName() );
- localGenerators.put( foreignGenerator.getName(), foreignGenerator );
+ localGenerators.putAll( buildLocalGenerators( property, mappings ) );
+ collectionBinder.setLocalGenerators( localGenerators );
- BinderHelper.makeIdGenerator(
- (SimpleValue) propertyBinder.getValue(),
- foreignGenerator.getIdentifierGeneratorStrategy(),
- foreignGenerator.getName(),
- mappings,
- localGenerators
- );
}
- if (isId) {
- //components and regular basic types create SimpleValue objects
- final SimpleValue value = ( SimpleValue ) propertyBinder.getValue();
- if ( !isOverridden ) {
- processId(
+ collectionBinder.setInheritanceStatePerClass( inheritanceStatePerClass );
+ collectionBinder.setDeclaringClass( inferredData.getDeclaringClass() );
+ collectionBinder.bind();
+
+ }
+ //Either a regular property or a basic @Id or @EmbeddedId while not ignoring id annotations
+ else if ( !isId || !entityBinder.isIgnoreIdAnnotations() ) {
+ //define whether the type is a component or not
+ boolean isComponent;
+ isComponent = property.isAnnotationPresent( Embedded.class )
+ || property.isAnnotationPresent( EmbeddedId.class )
+ || returnedClass.isAnnotationPresent( Embeddable.class );
+
+ //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() ) {
+ Ejb3Column[] oldColumns = columns;
+ columns = columnsBuilder.overrideColumnFromMapsIdProperty(isId);
+ isOverridden = oldColumns != columns;
+ }
+ if ( isComponent ) {
+ String referencedEntityName = null;
+ if (isOverridden) {
+ final PropertyData mapsIdProperty = BinderHelper.getPropertyAnnotatedWithMapsId(
+ isId, propertyHolder, property.getName(), mappings
+ );
+ referencedEntityName = mapsIdProperty.getClassOrElementName();
+ }
+ AccessType propertyAccessor = entityBinder.getPropertyAccessor( property );
+ propertyBinder = bindComponent(
+ inferredData,
propertyHolder,
- inferredData,
- value,
- classGenerators,
+ propertyAccessor,
+ entityBinder,
isIdentifierMapper,
- mappings
+ mappings,
+ isComponentEmbedded,
+ isId,
+ inheritanceStatePerClass,
+ referencedEntityName,
+ isOverridden ? (Ejb3JoinColumn[]) columns : null
);
}
+ else {
+ //provide the basic property mapping
+ boolean optional = true;
+ boolean lazy = false;
+ if ( property.isAnnotationPresent( Basic.class ) ) {
+ Basic ann = property.getAnnotation( Basic.class );
+ optional = ann.optional();
+ lazy = ann.fetch() == FetchType.LAZY;
+ }
+ //implicit type will check basic types and Serializable classes
+ if ( isId || ( !optional && nullability != Nullability.FORCED_NULL ) ) {
+ //force columns to not null
+ for (Ejb3Column col : columns) {
+ col.forceNotNull();
+ }
+ }
+
+ propertyBinder.setLazy( lazy );
+ propertyBinder.setColumns( columns );
+ if (isOverridden) {
+ final PropertyData mapsIdProperty = BinderHelper.getPropertyAnnotatedWithMapsId(
+ isId, propertyHolder, property.getName(), mappings
+ );
+ propertyBinder.setReferencedEntityName( mapsIdProperty.getClassOrElementName() );
+ }
+
+ propertyBinder.makePropertyValueAndBind();
+
+ }
+ if (isOverridden) {
+ final PropertyData mapsIdProperty = BinderHelper.getPropertyAnnotatedWithMapsId(
+ isId, propertyHolder, property.getName(), mappings
+ );
+ HashMap<String, IdGenerator> localGenerators = (HashMap<String, IdGenerator>) classGenerators.clone();
+ final IdGenerator foreignGenerator = new IdGenerator();
+ foreignGenerator.setIdentifierGeneratorStrategy( "assigned" );
+ foreignGenerator.setName( "Hibernate-local--foreign generator" );
+ foreignGenerator.setIdentifierGeneratorStrategy( "foreign" );
+ foreignGenerator.addParam( "property", mapsIdProperty.getPropertyName() );
+ localGenerators.put( foreignGenerator.getName(), foreignGenerator );
+
+ BinderHelper.makeIdGenerator(
+ (SimpleValue) propertyBinder.getValue(),
+ foreignGenerator.getIdentifierGeneratorStrategy(),
+ foreignGenerator.getName(),
+ mappings,
+ localGenerators
+ );
+ }
+ if (isId) {
+ //components and regular basic types create SimpleValue objects
+ final SimpleValue value = ( SimpleValue ) propertyBinder.getValue();
+ if ( !isOverridden ) {
+ processId(
+ propertyHolder,
+ inferredData,
+ value,
+ classGenerators,
+ isIdentifierMapper,
+ mappings
+ );
+ }
+ }
}
}
//init index
@@ -2507,7 +2510,7 @@
private static String getCascadeStrategy(
javax.persistence.CascadeType[] ejbCascades, Cascade hibernateCascadeAnnotation,
- boolean orphanRemoval) {
+ boolean orphanRemoval, boolean mapsId) {
EnumSet<CascadeType> hibernateCascadeSet = convertToHibernateCascadeType( ejbCascades );
CascadeType[] hibernateCascades = hibernateCascadeAnnotation == null ?
null :
@@ -2521,6 +2524,9 @@
hibernateCascadeSet.add(CascadeType.DELETE_ORPHAN);
hibernateCascadeSet.add(CascadeType.REMOVE);
}
+ if (mapsId) {
+ hibernateCascadeSet.add(CascadeType.PERSIST);
+ }
StringBuilder cascade = new StringBuilder();
for ( CascadeType aHibernateCascadeSet : hibernateCascadeSet ) {
Modified: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/b/DerivedIdentitySimpleParentEmbeddedIdDepTest.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/b/DerivedIdentitySimpleParentEmbeddedIdDepTest.java 2010-01-27 18:46:51 UTC (rev 18655)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/b/DerivedIdentitySimpleParentEmbeddedIdDepTest.java 2010-01-27 18:58:28 UTC (rev 18656)
@@ -23,8 +23,8 @@
d.emp = e;
d.id = new DependentId();
d.id.name = "Doggy";
+ s.persist( d );
s.persist( e );
- s.persist( d );
s.flush();
s.clear();
d = (Dependent) s.get( Dependent.class, d.id );
14 years, 10 months
Hibernate SVN: r18655 - in core/trunk/annotations/src: main/java/org/hibernate/cfg/annotations and 1 other directories.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2010-01-27 13:46:51 -0500 (Wed, 27 Jan 2010)
New Revision: 18655
Added:
core/trunk/annotations/src/main/java/org/hibernate/cfg/PkDrivenByDefaultMapsIdSecondPass.java
Modified:
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/ColumnsBuilder.java
core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/PropertyBinder.java
core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/SimpleValueBinder.java
core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/TableBinder.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/b/Dependent.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/b/DerivedIdentitySimpleParentEmbeddedIdDepTest.java
Log:
HHH-4849 honor default join column names for @MapsId properties
Modified: core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationBinder.java
===================================================================
--- core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationBinder.java 2010-01-27 18:23:11 UTC (rev 18654)
+++ core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationBinder.java 2010-01-27 18:46:51 UTC (rev 18655)
@@ -1758,6 +1758,12 @@
propertyBinder.setLazy( lazy );
propertyBinder.setColumns( columns );
+ if (isOverridden) {
+ final PropertyData mapsIdProperty = BinderHelper.getPropertyAnnotatedWithMapsId(
+ isId, propertyHolder, property.getName(), mappings
+ );
+ propertyBinder.setReferencedEntityName( mapsIdProperty.getClassOrElementName() );
+ }
propertyBinder.makePropertyValueAndBind();
Modified: core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationConfiguration.java
===================================================================
--- core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationConfiguration.java 2010-01-27 18:23:11 UTC (rev 18654)
+++ core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationConfiguration.java 2010-01-27 18:46:51 UTC (rev 18655)
@@ -365,6 +365,7 @@
caches.clear();
try {
inSecondPass = true;
+ processSecondPassesOfType( PkDrivenByDefaultMapsIdSecondPass.class );
processSecondPassesOfType( SetSimpleValueTypeSecondPass.class );
processSecondPassesOfType( CopyIdentifierComponentSecondPass.class );
processFkSecondPassInOrder();
Modified: core/trunk/annotations/src/main/java/org/hibernate/cfg/ColumnsBuilder.java
===================================================================
--- core/trunk/annotations/src/main/java/org/hibernate/cfg/ColumnsBuilder.java 2010-01-27 18:23:11 UTC (rev 18654)
+++ core/trunk/annotations/src/main/java/org/hibernate/cfg/ColumnsBuilder.java 2010-01-27 18:46:51 UTC (rev 18655)
@@ -189,9 +189,9 @@
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() );
+ result = buildDefaultJoinColumnsForXToOne( annotatedWithMapsId.getProperty(), annotatedWithMapsId);
+// throw new UnsupportedOperationException( "Implicit @JoinColumn is not supported on @MapsId properties: "
+// + annotatedWithMapsId.getDeclaringClass() + " " + annotatedWithMapsId.getPropertyName() );
}
}
return result;
Added: core/trunk/annotations/src/main/java/org/hibernate/cfg/PkDrivenByDefaultMapsIdSecondPass.java
===================================================================
--- core/trunk/annotations/src/main/java/org/hibernate/cfg/PkDrivenByDefaultMapsIdSecondPass.java (rev 0)
+++ core/trunk/annotations/src/main/java/org/hibernate/cfg/PkDrivenByDefaultMapsIdSecondPass.java 2010-01-27 18:46:51 UTC (rev 18655)
@@ -0,0 +1,38 @@
+package org.hibernate.cfg;
+
+import java.util.Map;
+
+import org.hibernate.AnnotationException;
+import org.hibernate.MappingException;
+import org.hibernate.cfg.annotations.TableBinder;
+import org.hibernate.mapping.PersistentClass;
+import org.hibernate.mapping.SimpleValue;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class PkDrivenByDefaultMapsIdSecondPass implements SecondPass {
+ private final String referencedEntityName;
+ private final Ejb3JoinColumn[] columns;
+ private final SimpleValue value;
+
+ public PkDrivenByDefaultMapsIdSecondPass(String referencedEntityName, Ejb3JoinColumn[] columns, SimpleValue value) {
+ this.referencedEntityName = referencedEntityName;
+ this.columns = columns;
+ this.value = value;
+ }
+
+ public void doSecondPass(Map persistentClasses) throws MappingException {
+ PersistentClass referencedEntity = (PersistentClass) persistentClasses.get( referencedEntityName );
+ if ( referencedEntity == null ) {
+ throw new AnnotationException(
+ "Unknown entity name: " + referencedEntityName
+ );
+ };
+ TableBinder.linkJoinColumnWithValueOverridingNameIfImplicit(
+ referencedEntity,
+ referencedEntity.getKey().getColumnIterator(),
+ columns,
+ value);
+ }
+}
Modified: core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/PropertyBinder.java
===================================================================
--- core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/PropertyBinder.java 2010-01-27 18:23:11 UTC (rev 18654)
+++ core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/PropertyBinder.java 2010-01-27 18:46:51 UTC (rev 18655)
@@ -78,7 +78,12 @@
private boolean embedded;
private EntityBinder entityBinder;
private boolean isXToMany;
+ private String referencedEntityName;
+ public void setReferencedEntityName(String referencedEntityName) {
+ this.referencedEntityName = referencedEntityName;
+ }
+
public void setEmbedded(boolean embedded) {
this.embedded = embedded;
}
@@ -179,6 +184,7 @@
simpleValueBinder.setPersistentClassName( containerClassName );
simpleValueBinder.setType( property, returnedClass );
simpleValueBinder.setMappings( mappings );
+ simpleValueBinder.setReferencedEntityName( referencedEntityName );
SimpleValue propertyValue = simpleValueBinder.make();
setValue( propertyValue );
return makeProperty();
Modified: core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/SimpleValueBinder.java
===================================================================
--- core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/SimpleValueBinder.java 2010-01-27 18:23:11 UTC (rev 18654)
+++ core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/SimpleValueBinder.java 2010-01-27 18:46:51 UTC (rev 18655)
@@ -45,8 +45,10 @@
import org.hibernate.annotations.common.reflection.XProperty;
import org.hibernate.cfg.BinderHelper;
import org.hibernate.cfg.Ejb3Column;
+import org.hibernate.cfg.Ejb3JoinColumn;
import org.hibernate.cfg.ExtendedMappings;
import org.hibernate.cfg.NotYetImplementedException;
+import org.hibernate.cfg.PkDrivenByDefaultMapsIdSecondPass;
import org.hibernate.cfg.SecondPass;
import org.hibernate.cfg.SetSimpleValueTypeSecondPass;
import org.hibernate.mapping.SimpleValue;
@@ -77,7 +79,12 @@
private boolean isVersion;
//is a Map key
private boolean key;
+ private String referencedEntityName;
+ public void setReferencedEntityName(String referencedEntityName) {
+ this.referencedEntityName = referencedEntityName;
+ }
+
public boolean isVersion() {
return isVersion;
}
@@ -307,9 +314,16 @@
}
public void linkWithValue() {
- for ( Ejb3Column column : columns) {
- column.linkWithValue( simpleValue );
+ if ( columns[0].isNameDeferred() && ! mappings.isInSecondPass() && referencedEntityName != null) {
+ mappings.addSecondPass(
+ new PkDrivenByDefaultMapsIdSecondPass( referencedEntityName, ( Ejb3JoinColumn[]) columns, simpleValue)
+ );
}
+ else {
+ for ( Ejb3Column column : columns) {
+ column.linkWithValue( simpleValue );
+ }
+ }
}
public void fillSimpleValue() {
Modified: core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/TableBinder.java
===================================================================
--- core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/TableBinder.java 2010-01-27 18:23:11 UTC (rev 18654)
+++ core/trunk/annotations/src/main/java/org/hibernate/cfg/annotations/TableBinder.java 2010-01-27 18:46:51 UTC (rev 18655)
@@ -474,7 +474,7 @@
}
}
- private static void linkJoinColumnWithValueOverridingNameIfImplicit(
+ public static void linkJoinColumnWithValueOverridingNameIfImplicit(
PersistentClass referencedEntity, Iterator columnIterator, Ejb3JoinColumn[] columns, SimpleValue value
) {
for (Ejb3JoinColumn joinCol : columns) {
Modified: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/b/Dependent.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/b/Dependent.java 2010-01-27 18:23:11 UTC (rev 18654)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/b/Dependent.java 2010-01-27 18:46:51 UTC (rev 18655)
@@ -14,7 +14,7 @@
@EmbeddedId
DependentId id;
- @JoinColumn(name="FK") // id attribute mapped by join column default
+ //@JoinColumn(name="FK") // id attribute mapped by join column default
@MapsId("empPK") // maps empPK attribute of embedded id
@ManyToOne
Employee emp;
Modified: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/b/DerivedIdentitySimpleParentEmbeddedIdDepTest.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/b/DerivedIdentitySimpleParentEmbeddedIdDepTest.java 2010-01-27 18:23:11 UTC (rev 18654)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/derivedidentities/e1/b/DerivedIdentitySimpleParentEmbeddedIdDepTest.java 2010-01-27 18:46:51 UTC (rev 18655)
@@ -11,19 +11,19 @@
DerivedIdentitySimpleParentEmbeddedIdDepTest extends TestCase {
public void testManyToOne() throws Exception {
- assertTrue( SchemaUtil.isColumnPresent( "Dependent", "FK", getCfg() ) );
+ assertTrue( SchemaUtil.isColumnPresent( "Dependent", "emp_empId", 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.id = new DependentId();
d.id.name = "Doggy";
- //d.id.empPK = e.empId; //FIXME not needed when foreign is enabled
+ s.persist( e );
s.persist( d );
s.flush();
s.clear();
14 years, 10 months