HHH-9104 removing test's o.h.metamodel.* (stale and fails on jdk8)

This commit is contained in:
Brett Meyer 2014-04-07 14:17:21 -04:00
parent f0e08a10e4
commit 5359d82b71
72 changed files with 0 additions and 7570 deletions

View File

@ -1,206 +0,0 @@
/*
* 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.metamodel.binding;
import java.sql.Types;
import java.util.Iterator;
import java.util.Set;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.hibernate.metamodel.MetadataSources;
import org.hibernate.metamodel.domain.BasicType;
import org.hibernate.metamodel.domain.SingularAttribute;
import org.hibernate.metamodel.relational.Column;
import org.hibernate.metamodel.relational.Datatype;
import org.hibernate.metamodel.relational.SimpleValue;
import org.hibernate.metamodel.source.MetadataImplementor;
import org.hibernate.metamodel.source.internal.MetadataImpl;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.service.internal.StandardServiceRegistryImpl;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.type.LongType;
import org.hibernate.type.StringType;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
/**
* Basic tests of {@code hbm.xml} and annotation binding code
*
* @author Steve Ebersole
*/
public abstract class AbstractBasicBindingTests extends BaseUnitTestCase {
private StandardServiceRegistryImpl serviceRegistry;
@Before
public void setUp() {
serviceRegistry = (StandardServiceRegistryImpl) new ServiceRegistryBuilder().buildServiceRegistry();
}
@After
public void tearDown() {
serviceRegistry.destroy();
}
protected ServiceRegistry basicServiceRegistry() {
return serviceRegistry;
}
@Test
public void testSimpleEntityMapping() {
MetadataSources sources = new MetadataSources( serviceRegistry );
addSourcesForSimpleEntityBinding( sources );
MetadataImpl metadata = (MetadataImpl) sources.buildMetadata();
EntityBinding entityBinding = metadata.getEntityBinding( SimpleEntity.class.getName() );
assertRoot( metadata, entityBinding );
assertIdAndSimpleProperty( entityBinding );
assertNull( entityBinding.getHierarchyDetails().getVersioningAttributeBinding() );
}
@Test
public void testSimpleVersionedEntityMapping() {
MetadataSources sources = new MetadataSources( serviceRegistry );
addSourcesForSimpleVersionedEntityBinding( sources );
MetadataImpl metadata = (MetadataImpl) sources.buildMetadata();
EntityBinding entityBinding = metadata.getEntityBinding( SimpleVersionedEntity.class.getName() );
assertIdAndSimpleProperty( entityBinding );
assertNotNull( entityBinding.getHierarchyDetails().getVersioningAttributeBinding() );
assertNotNull( entityBinding.getHierarchyDetails().getVersioningAttributeBinding().getAttribute() );
}
@Test
public void testEntityWithManyToOneMapping() {
MetadataSources sources = new MetadataSources( serviceRegistry );
addSourcesForSimpleEntityBinding( sources );
addSourcesForManyToOne( sources );
MetadataImpl metadata = (MetadataImpl) sources.buildMetadata();
EntityBinding simpleEntityBinding = metadata.getEntityBinding( SimpleEntity.class.getName() );
assertIdAndSimpleProperty( simpleEntityBinding );
Set<SingularAssociationAttributeBinding> referenceBindings = simpleEntityBinding.locateAttributeBinding( "id" )
.getEntityReferencingAttributeBindings();
assertEquals( "There should be only one reference binding", 1, referenceBindings.size() );
SingularAssociationAttributeBinding referenceBinding = referenceBindings.iterator().next();
EntityBinding referencedEntityBinding = referenceBinding.getReferencedEntityBinding();
// TODO - Is this assertion correct (HF)?
assertEquals( "Should be the same entity binding", referencedEntityBinding, simpleEntityBinding );
EntityBinding entityWithManyToOneBinding = metadata.getEntityBinding( ManyToOneEntity.class.getName() );
Iterator<SingularAssociationAttributeBinding> it = entityWithManyToOneBinding.getEntityReferencingAttributeBindings()
.iterator();
assertTrue( it.hasNext() );
assertSame( entityWithManyToOneBinding.locateAttributeBinding( "simpleEntity" ), it.next() );
assertFalse( it.hasNext() );
}
@Test
public void testSimpleEntityWithSimpleComponentMapping() {
MetadataSources sources = new MetadataSources( serviceRegistry );
addSourcesForComponentBinding( sources );
MetadataImpl metadata = (MetadataImpl) sources.buildMetadata();
EntityBinding entityBinding = metadata.getEntityBinding( SimpleEntityWithSimpleComponent.class.getName() );
assertRoot( metadata, entityBinding );
assertIdAndSimpleProperty( entityBinding );
ComponentAttributeBinding componentAttributeBinding = (ComponentAttributeBinding) entityBinding.locateAttributeBinding( "simpleComponent" );
assertNotNull( componentAttributeBinding );
assertSame( componentAttributeBinding.getAttribute().getSingularAttributeType(), componentAttributeBinding.getAttributeContainer() );
assertEquals( SimpleEntityWithSimpleComponent.class.getName() + ".simpleComponent", componentAttributeBinding.getPathBase() );
assertSame( entityBinding, componentAttributeBinding.seekEntityBinding() );
assertNotNull( componentAttributeBinding.getComponent() );
}
public abstract void addSourcesForSimpleVersionedEntityBinding(MetadataSources sources);
public abstract void addSourcesForSimpleEntityBinding(MetadataSources sources);
public abstract void addSourcesForManyToOne(MetadataSources sources);
public abstract void addSourcesForComponentBinding(MetadataSources sources);
protected void assertIdAndSimpleProperty(EntityBinding entityBinding) {
assertNotNull( entityBinding );
assertNotNull( entityBinding.getHierarchyDetails().getEntityIdentifier() );
assertNotNull( entityBinding.getHierarchyDetails().getEntityIdentifier().getValueBinding() );
AttributeBinding idAttributeBinding = entityBinding.locateAttributeBinding( "id" );
assertNotNull( idAttributeBinding );
assertSame( idAttributeBinding, entityBinding.getHierarchyDetails().getEntityIdentifier().getValueBinding() );
assertSame( LongType.INSTANCE, idAttributeBinding.getHibernateTypeDescriptor().getResolvedTypeMapping() );
assertTrue( idAttributeBinding.getAttribute().isSingular() );
assertNotNull( idAttributeBinding.getAttribute() );
SingularAttributeBinding singularIdAttributeBinding = (SingularAttributeBinding) idAttributeBinding;
assertFalse( singularIdAttributeBinding.isNullable() );
SingularAttribute singularIdAttribute = ( SingularAttribute ) idAttributeBinding.getAttribute();
BasicType basicIdAttributeType = ( BasicType ) singularIdAttribute.getSingularAttributeType();
assertSame( Long.class, basicIdAttributeType.getClassReference() );
assertNotNull( singularIdAttributeBinding.getValue() );
assertTrue( singularIdAttributeBinding.getValue() instanceof Column );
Datatype idDataType = ( (Column) singularIdAttributeBinding.getValue() ).getDatatype();
assertSame( Long.class, idDataType.getJavaType() );
assertSame( Types.BIGINT, idDataType.getTypeCode() );
assertSame( LongType.INSTANCE.getName(), idDataType.getTypeName() );
assertNotNull( entityBinding.locateAttributeBinding( "name" ) );
assertNotNull( entityBinding.locateAttributeBinding( "name" ).getAttribute() );
assertTrue( entityBinding.locateAttributeBinding( "name" ).getAttribute().isSingular() );
SingularAttributeBinding nameBinding = (SingularAttributeBinding) entityBinding.locateAttributeBinding( "name" );
assertTrue( nameBinding.isNullable() );
assertSame( StringType.INSTANCE, nameBinding.getHibernateTypeDescriptor().getResolvedTypeMapping() );
assertNotNull( nameBinding.getAttribute() );
assertNotNull( nameBinding.getValue() );
SingularAttribute singularNameAttribute = ( SingularAttribute ) nameBinding.getAttribute();
BasicType basicNameAttributeType = ( BasicType ) singularNameAttribute.getSingularAttributeType();
assertSame( String.class, basicNameAttributeType.getClassReference() );
assertNotNull( nameBinding.getValue() );
SimpleValue nameValue = (SimpleValue) nameBinding.getValue();
assertTrue( nameValue instanceof Column );
Datatype nameDataType = nameValue.getDatatype();
assertSame( String.class, nameDataType.getJavaType() );
assertSame( Types.VARCHAR, nameDataType.getTypeCode() );
assertSame( StringType.INSTANCE.getName(), nameDataType.getTypeName() );
}
protected void assertRoot(MetadataImplementor metadata, EntityBinding entityBinding) {
assertTrue( entityBinding.isRoot() );
assertSame( entityBinding, metadata.getRootEntityBinding( entityBinding.getEntity().getName() ) );
}
}

View File

@ -1,54 +0,0 @@
/*
* 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.metamodel.binding;
import org.hibernate.metamodel.MetadataSources;
/**
* Basic tests of annotation based binding code
*
* @author Hardy Ferentschik
*/
public class BasicAnnotationBindingTests extends AbstractBasicBindingTests {
@Override
public void addSourcesForSimpleEntityBinding(MetadataSources sources) {
sources.addAnnotatedClass( SimpleEntity.class );
}
@Override
public void addSourcesForSimpleVersionedEntityBinding(MetadataSources sources) {
sources.addAnnotatedClass( SimpleVersionedEntity.class );
}
@Override
public void addSourcesForManyToOne(MetadataSources sources) {
sources.addAnnotatedClass( ManyToOneEntity.class );
}
@Override
public void addSourcesForComponentBinding(MetadataSources sources) {
sources.addAnnotatedClass( SimpleEntityWithSimpleComponent.class );
sources.addAnnotatedClass( SimpleEntityWithSimpleComponent.SimpleComponent.class );
}
}

View File

@ -1,90 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.binding;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.hibernate.metamodel.MetadataSourceProcessingOrder;
import org.hibernate.metamodel.MetadataSources;
import org.hibernate.metamodel.source.internal.MetadataImpl;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.service.internal.StandardServiceRegistryImpl;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
/**
* @author Steve Ebersole
*/
public class BasicCollectionBindingTests extends BaseUnitTestCase {
private StandardServiceRegistryImpl serviceRegistry;
@Before
public void setUp() {
serviceRegistry = (StandardServiceRegistryImpl) new ServiceRegistryBuilder().buildServiceRegistry();
}
@After
public void tearDown() {
serviceRegistry.destroy();
}
// @Test
// public void testAnnotations() {
// doTest( MetadataSourceProcessingOrder.ANNOTATIONS_FIRST );
// }
@Test
public void testHbm() {
doTest( MetadataSourceProcessingOrder.HBM_FIRST );
}
private void doTest(MetadataSourceProcessingOrder processingOrder) {
MetadataSources sources = new MetadataSources( serviceRegistry );
// sources.addAnnotatedClass( EntityWithBasicCollections.class );
sources.addResource( "org/hibernate/metamodel/binding/EntityWithBasicCollections.hbm.xml" );
MetadataImpl metadata = (MetadataImpl) sources.getMetadataBuilder().with( processingOrder ).buildMetadata();
final EntityBinding entityBinding = metadata.getEntityBinding( EntityWithBasicCollections.class.getName() );
assertNotNull( entityBinding );
PluralAttributeBinding bagBinding = metadata.getCollection( EntityWithBasicCollections.class.getName() + ".theBag" );
assertNotNull( bagBinding );
assertSame( bagBinding, entityBinding.locateAttributeBinding( "theBag" ) );
assertNotNull( bagBinding.getCollectionTable() );
assertEquals( CollectionElementNature.BASIC, bagBinding.getCollectionElement().getCollectionElementNature() );
assertEquals( String.class.getName(), ( (BasicCollectionElement) bagBinding.getCollectionElement() ).getHibernateTypeDescriptor().getJavaTypeName() );
PluralAttributeBinding setBinding = metadata.getCollection( EntityWithBasicCollections.class.getName() + ".theSet" );
assertNotNull( setBinding );
assertSame( setBinding, entityBinding.locateAttributeBinding( "theSet" ) );
assertNotNull( setBinding.getCollectionTable() );
assertEquals( CollectionElementNature.BASIC, setBinding.getCollectionElement().getCollectionElementNature() );
assertEquals( String.class.getName(), ( (BasicCollectionElement) setBinding.getCollectionElement() ).getHibernateTypeDescriptor().getJavaTypeName() );
}
}

View File

@ -1,56 +0,0 @@
/*
* 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.metamodel.binding;
import org.junit.Test;
import org.hibernate.metamodel.MetadataSources;
/**
* Basic tests of {@code hbm.xml} binding code
*
* @author Steve Ebersole
*/
public class BasicHbmBindingTests extends AbstractBasicBindingTests {
public void addSourcesForSimpleEntityBinding(MetadataSources sources) {
sources.addResource( "org/hibernate/metamodel/binding/SimpleEntity.hbm.xml" );
}
public void addSourcesForSimpleVersionedEntityBinding(MetadataSources sources) {
sources.addResource( "org/hibernate/metamodel/binding/SimpleVersionedEntity.hbm.xml" );
}
public void addSourcesForManyToOne(MetadataSources sources) {
sources.addResource( "org/hibernate/metamodel/binding/ManyToOneEntity.hbm.xml" );
}
public void addSourcesForComponentBinding(MetadataSources sources) {
sources.addResource( "org/hibernate/metamodel/binding/SimpleEntityWithSimpleComponent.hbm.xml" );
}
@Test
public void testSimpleEntityWithSimpleComponentMapping() {
super.testSimpleEntityWithSimpleComponentMapping();
}
}

View File

@ -1,24 +0,0 @@
<?xml version="1.0"?>
<hibernate-mapping
xmlns="http://www.hibernate.org/xsd/hibernate-mapping"
package="org.hibernate.metamodel.binding" >
<class name="EntityWithBasicCollections">
<id name="id">
<generator class="increment"/>
</id>
<property name="name"/>
<bag name="theBag">
<key column="owner_id"/>
<element column="bag_stuff" type="string"/>
</bag>
<set name="theSet">
<key column="pid"/>
<element column="set_stuff" type="string"/>
</set>
</class>
</hibernate-mapping>

View File

@ -1,86 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.binding;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.Id;
/**
* @author Gail Badner
* @author Steve Ebersole
*/
@Entity
public class EntityWithBasicCollections {
private Long id;
private String name;
private Collection<String> theBag = new ArrayList<String>();
private Set<String> theSet = new HashSet<String>();
public EntityWithBasicCollections() {
}
public EntityWithBasicCollections(String name) {
this.name = name;
}
@Id
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;
}
@ElementCollection
public Collection<String> getTheBag() {
return theBag;
}
public void setTheBag(Collection<String> theBag) {
this.theBag = theBag;
}
@ElementCollection
public Set<String> getTheSet() {
return theSet;
}
public void setTheSet(Set<String> theSet) {
this.theSet = theSet;
}
}

View File

@ -1,15 +0,0 @@
<?xml version="1.0"?>
<hibernate-mapping package="org.hibernate.metamodel.binding"
xmlns="http://www.hibernate.org/xsd/hibernate-mapping"
xsi:schemaLocation="http://www.hibernate.org/xsd/hibernate-mapping hibernate-mapping-4.0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<class name="ManyToOneEntity">
<id name="id">
<generator class="increment"/>
</id>
<property name="name"/>
<many-to-one name="simpleEntity"/>
</class>
</hibernate-mapping>

View File

@ -1,82 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.binding;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
/**
* @author Gail Badner
*/
@Entity
public class ManyToOneEntity {
@Id
private Long id;
private String theName;
@ManyToOne
SimpleEntity simpleEntity;
public ManyToOneEntity() {
}
public ManyToOneEntity(String name) {
this.theName = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return theName;
}
public void setName(String name) {
this.theName = name;
}
public SimpleEntity getSimpleEntity() {
return simpleEntity;
}
public void setSimpleEntity(SimpleEntity simpleEntity) {
this.simpleEntity = simpleEntity;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append( "EntityWithManyToOne" );
sb.append( "{id=" ).append( id );
sb.append( ", theName='" ).append( theName ).append( '\'' );
sb.append( ", simpleEntity=" ).append( simpleEntity );
sb.append( '}' );
return sb.toString();
}
}

View File

@ -1,14 +0,0 @@
<?xml version="1.0"?>
<hibernate-mapping package="org.hibernate.metamodel.binding" xmlns="http://www.hibernate.org/xsd/hibernate-mapping"
xsi:schemaLocation="http://www.hibernate.org/xsd/hibernate-mapping hibernate-mapping-4.0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<class name="SimpleEntity">
<id name="id">
<generator class="increment"/>
</id>
<property name="name"/>
</class>
</hibernate-mapping>

View File

@ -1,60 +0,0 @@
/*
* 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.metamodel.binding;
import javax.persistence.Entity;
import javax.persistence.Id;
/**
* @author Steve Ebersole
*/
@Entity
public class SimpleEntity {
@Id
private Long id;
private String name;
public SimpleEntity() {
}
public SimpleEntity(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -1,36 +0,0 @@
/*
* 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.metamodel.binding;
import javax.persistence.Entity;
/**
* @author Steve Ebersole
*/
@Entity
public class SimpleEntitySubClass extends SimpleEntity {
public SimpleEntitySubClass() {
}
}

View File

@ -1,19 +0,0 @@
<?xml version="1.0"?>
<hibernate-mapping
xmlns="http://www.hibernate.org/xsd/hibernate-mapping"
xsi:schemaLocation="http://www.hibernate.org/xsd/hibernate-mapping hibernate-mapping-4.0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
package="org.hibernate.metamodel.binding">
<class name="SimpleEntityWithSimpleComponent">
<id name="id">
<generator class="increment"/>
</id>
<property name="name"/>
<component name="simpleComponent" class="SimpleEntityWithSimpleComponent$SimpleComponent">
<property name="value1"/>
<property name="value2"/>
</component>
</class>
</hibernate-mapping>

View File

@ -1,94 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.binding;
import javax.persistence.Embeddable;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;
/**
* @author Steve Ebersole
*/
@Entity
public class SimpleEntityWithSimpleComponent {
@Id
private Long id;
private String name;
@Embedded
private SimpleComponent simpleComponent;
public SimpleEntityWithSimpleComponent() {
}
public SimpleEntityWithSimpleComponent(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public SimpleComponent getSimpleComponent() {
return simpleComponent;
}
public void setSimpleComponent(SimpleComponent simpleComponent) {
this.simpleComponent = simpleComponent;
}
@Embeddable
public static class SimpleComponent {
private String value1;
private String value2;
public String getValue1() {
return value1;
}
public void setValue1(String value1) {
this.value1 = value1;
}
public String getValue2() {
return value2;
}
public void setValue2(String value2) {
this.value2 = value2;
}
}
}

View File

@ -1,92 +0,0 @@
/*
* 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.metamodel.binding;
import java.sql.Types;
import org.junit.Test;
import org.hibernate.EntityMode;
import org.hibernate.internal.util.ValueHolder;
import org.hibernate.metamodel.domain.Entity;
import org.hibernate.metamodel.domain.SingularAttribute;
import org.hibernate.metamodel.relational.Column;
import org.hibernate.metamodel.relational.Datatype;
import org.hibernate.metamodel.relational.Schema;
import org.hibernate.metamodel.relational.Size;
import org.hibernate.metamodel.relational.Table;
import org.hibernate.service.classloading.spi.ClassLoadingException;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import static org.junit.Assert.assertSame;
/**
* Basic binding "smoke" tests
*
* @author Steve Ebersole
*/
public class SimpleValueBindingTests extends BaseUnitTestCase {
public static final Datatype BIGINT = new Datatype( Types.BIGINT, "BIGINT", Long.class );
public static final Datatype VARCHAR = new Datatype( Types.VARCHAR, "VARCHAR", String.class );
@Test
public void testBasicMiddleOutBuilding() {
Table table = new Table( new Schema( null, null ), "the_table" );
Entity entity = new Entity( "TheEntity", "NoSuchClass", makeJavaType( "NoSuchClass" ), null );
EntityBinding entityBinding = new EntityBinding( InheritanceType.NO_INHERITANCE, EntityMode.POJO );
entityBinding.setEntity( entity );
entityBinding.setPrimaryTable( table );
SingularAttribute idAttribute = entity.createSingularAttribute( "id" );
BasicAttributeBinding attributeBinding = entityBinding.makeBasicAttributeBinding( idAttribute );
attributeBinding.getHibernateTypeDescriptor().setExplicitTypeName( "long" );
assertSame( idAttribute, attributeBinding.getAttribute() );
entityBinding.getHierarchyDetails().getEntityIdentifier().setValueBinding( attributeBinding );
Column idColumn = table.locateOrCreateColumn( "id" );
idColumn.setDatatype( BIGINT );
idColumn.setSize( Size.precision( 18, 0 ) );
table.getPrimaryKey().addColumn( idColumn );
table.getPrimaryKey().setName( "my_table_pk" );
//attributeBinding.setValue( idColumn );
}
ValueHolder<Class<?>> makeJavaType(final String name) {
return new ValueHolder<Class<?>>(
new ValueHolder.DeferredInitializer<Class<?>>() {
@Override
public Class<?> initialize() {
try {
return Class.forName( name );
}
catch ( Exception e ) {
throw new ClassLoadingException( "Could not load class : " + name, e );
}
}
}
);
}
}

View File

@ -1,38 +0,0 @@
<?xml version="1.0"?>
<!--
~ 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
-->
<hibernate-mapping package="org.hibernate.metamodel.binding" xmlns="http://www.hibernate.org/xsd/hibernate-mapping"
xsi:schemaLocation="http://www.hibernate.org/xsd/hibernate-mapping hibernate-mapping-4.0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<class name="SimpleVersionedEntity">
<id name="id">
<generator class="increment"/>
</id>
<version name="version"/>
<property name="name"/>
</class>
</hibernate-mapping>

View File

@ -1,72 +0,0 @@
/*
* 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.metamodel.binding;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Version;
/**
* @author Steve Ebersole
* @author Hardy Ferentschik
*/
@Entity
public class SimpleVersionedEntity {
private Long id;
private String name;
private long version;
public SimpleVersionedEntity() {
}
public SimpleVersionedEntity(String name) {
this.name = name;
}
@Id
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;
}
@Version
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
}

View File

@ -1,38 +0,0 @@
<?xml version="1.0"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ Copyright (c) 2011, 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
-->
<hibernate-mapping package="org.hibernate.metamodel.binding" xmlns="http://www.hibernate.org/xsd/hibernate-mapping"
xsi:schemaLocation="http://www.hibernate.org/xsd/hibernate-mapping hibernate-mapping-4.0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<class name="SimpleVersionedEntity">
<id name="id">
<generator class="increment"/>
</id>
<version name="version"/>
<property name="name"/>
</class>
</hibernate-mapping>

View File

@ -1,4 +0,0 @@
@GenericGenerator(name = "myGenerator", strategy = "sequence")
package org.hibernate.metamodel.binding;
import org.hibernate.annotations.GenericGenerator;

View File

@ -1,72 +0,0 @@
/*
* 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.metamodel.relational;
import org.junit.Test;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
/**
* @author Steve Ebersole
*/
public class ObjectNameTests extends BaseUnitTestCase {
@Test
public void testMissingName() {
try {
new ObjectName( (String)null, null, null );
fail();
}
catch ( IllegalIdentifierException ignore ) {
}
try {
new ObjectName( "schema", "catalog", null );
fail();
}
catch ( IllegalIdentifierException ignore ) {
}
}
@Test
public void testIdentifierBuilding() {
Dialect dialect = new H2Dialect();
ObjectName on = new ObjectName( "schema", "catalog", "name" );
assertEquals( "schema.catalog.name", on.toText() );
on = new ObjectName( "schema", null, "name" );
assertEquals( "schema.name", on.toText() );
assertEquals( "schema.name", on.toText( dialect ) );
on = new ObjectName( "`schema`", "`catalog`", "`name`" );
assertEquals( "`schema`.`catalog`.`name`", on.toText() );
assertEquals( "\"schema\".\"catalog\".\"name\"", on.toText( dialect ) );
on = new ObjectName( "`schema`", null, "`name`" );
assertEquals( "`schema`.`name`", on.toText() );
assertEquals( "\"schema\".\"name\"", on.toText( dialect ) );
}
}

View File

@ -1,151 +0,0 @@
/*
* 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.metamodel.relational;
import java.sql.Types;
import org.junit.Test;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* @author Steve Ebersole
*/
public class TableManipulationTests extends BaseUnitTestCase {
public static final Datatype VARCHAR = new Datatype( Types.VARCHAR, "VARCHAR", String.class );
public static final Datatype INTEGER = new Datatype( Types.INTEGER, "INTEGER", Long.class );
@Test
public void testTableCreation() {
Schema schema = new Schema( null, null );
Table table = schema.createTable( Identifier.toIdentifier( "my_table" ) );
assertNull( table.getSchema().getName().getSchema() );
assertNull( table.getSchema().getName().getCatalog() );
assertEquals( "my_table", table.getTableName().toString() );
assertEquals( "my_table", table.getExportIdentifier() );
assertNull( table.getPrimaryKey().getName() );
assertFalse( table.values().iterator().hasNext() );
Column idColumn = table.locateOrCreateColumn( "id" );
idColumn.setDatatype( INTEGER );
idColumn.setSize( Size.precision( 18, 0 ) );
table.getPrimaryKey().addColumn( idColumn );
table.getPrimaryKey().setName( "my_table_pk" );
assertEquals( "my_table_pk", table.getPrimaryKey().getName() );
assertEquals( "my_table.PK", table.getPrimaryKey().getExportIdentifier() );
Column col_1 = table.locateOrCreateColumn( "col_1" );
col_1.setDatatype( VARCHAR );
col_1.setSize( Size.length( 512 ) );
for ( Value value : table.values() ) {
assertTrue( Column.class.isInstance( value ) );
Column column = ( Column ) value;
if ( column.getColumnName().getName().equals( "id" ) ) {
assertEquals( INTEGER, column.getDatatype() );
assertEquals( 18, column.getSize().getPrecision() );
assertEquals( 0, column.getSize().getScale() );
assertEquals( -1, column.getSize().getLength() );
assertNull( column.getSize().getLobMultiplier() );
}
else {
assertEquals( "col_1", column.getColumnName().getName() );
assertEquals( VARCHAR, column.getDatatype() );
assertEquals( -1, column.getSize().getPrecision() );
assertEquals( -1, column.getSize().getScale() );
assertEquals( 512, column.getSize().getLength() );
assertNull( column.getSize().getLobMultiplier() );
}
}
}
@Test
public void testTableSpecificationCounter() {
Schema schema = new Schema( null, null );
Table table = schema.createTable( Identifier.toIdentifier( "my_table" ) );
InLineView inLineView = schema.createInLineView( "my_inlineview", "subselect" );
InLineView otherInLineView = schema.createInLineView( "my_other_inlineview", "other subselect" );
Table otherTable = schema.createTable( Identifier.toIdentifier( "my_other_table" ) );
int firstTableNumber = table.getTableNumber();
assertEquals( firstTableNumber, table.getTableNumber() );
assertEquals( firstTableNumber + 1, inLineView.getTableNumber() );
assertEquals( firstTableNumber + 2, otherInLineView.getTableNumber() );
assertEquals( firstTableNumber + 3, otherTable.getTableNumber() );
}
@Test
public void testBasicForeignKeyDefinition() {
Schema schema = new Schema( null, null );
Table book = schema.createTable( Identifier.toIdentifier( "BOOK" ) );
Column bookId = book.locateOrCreateColumn( "id" );
bookId.setDatatype( INTEGER );
bookId.setSize( Size.precision( 18, 0 ) );
book.getPrimaryKey().addColumn( bookId );
book.getPrimaryKey().setName( "BOOK_PK" );
Table page = schema.createTable( Identifier.toIdentifier( "PAGE" ) );
Column pageId = page.locateOrCreateColumn( "id" );
pageId.setDatatype( INTEGER );
pageId.setSize( Size.precision( 18, 0 ) );
page.getPrimaryKey().addColumn( pageId );
page.getPrimaryKey().setName( "PAGE_PK" );
Column pageBookId = page.locateOrCreateColumn( "BOOK_ID" );
pageId.setDatatype( INTEGER );
pageId.setSize( Size.precision( 18, 0 ) );
ForeignKey pageBookFk = page.createForeignKey( book, "PAGE_BOOK_FK" );
pageBookFk.addColumn( pageBookId );
assertEquals( page, pageBookFk.getSourceTable() );
assertEquals( book, pageBookFk.getTargetTable() );
}
@Test
public void testQualifiedName() {
Dialect dialect = new H2Dialect();
Schema schema = new Schema( Identifier.toIdentifier( "schema" ), Identifier.toIdentifier( "`catalog`" ) );
Table table = schema.createTable( Identifier.toIdentifier( "my_table" ) );
assertEquals( "my_table", table.getTableName().getName() );
assertEquals( "my_table", table.getTableName().toString() );
assertEquals( "schema.\"catalog\".my_table", table.getQualifiedName( dialect ) );
table = schema.createTable( Identifier.toIdentifier( "`my_table`" ) );
assertEquals( "my_table", table.getTableName().getName() );
assertEquals( "`my_table`", table.getTableName().toString() );
assertEquals( "schema.\"catalog\".\"my_table\"", table.getQualifiedName( dialect ) );
InLineView inLineView = schema.createInLineView( "my_inlineview", "select ..." );
assertEquals( "( select ... )", inLineView.getQualifiedName( dialect ) );
}
}

View File

@ -1,153 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.entity;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.junit.Test;
import org.hibernate.AnnotationException;
import org.hibernate.metamodel.binding.EntityBinding;
import static junit.framework.Assert.assertEquals;
/**
* Tests for different types of attribute access
*
* @author Hardy Ferentschik
*/
public class AccessBindingTest extends BaseAnnotationBindingTestCase {
@Entity
class FieldAccess {
@Id
private int id;
}
@Test
@Resources(annotatedClasses = { FieldAccess.class })
public void testDefaultFieldAccess() {
EntityBinding binding = getEntityBinding( FieldAccess.class );
assertEquals( "Wrong access type", "field", binding.locateAttributeBinding( "id" ).getPropertyAccessorName() );
}
@Entity
class PropertyAccess {
private int id;
@Id
public int getId() {
return id;
}
}
@Test
@Resources(annotatedClasses = { PropertyAccess.class })
public void testDefaultPropertyAccess() {
EntityBinding binding = getEntityBinding( PropertyAccess.class );
assertEquals( "Wrong access type", "property", binding.locateAttributeBinding( "id" ).getPropertyAccessorName() );
}
@Entity
class NoAccess {
private int id;
public int getId() {
return id;
}
}
@Test(expected = AnnotationException.class)
@Resources(annotatedClasses = { NoAccess.class })
public void testNoAccess() {
// actual error happens when the binding gets created
}
@Entity
class MixedAccess {
@Id
private int id;
private String name;
@Access(AccessType.PROPERTY)
public String getName() {
return name;
}
}
@Test
@Resources(annotatedClasses = { MixedAccess.class })
public void testMixedAccess() {
EntityBinding binding = getEntityBinding( MixedAccess.class );
assertEquals( "Wrong access type", "field", binding.locateAttributeBinding( "id" ).getPropertyAccessorName() );
assertEquals(
"Wrong access type",
"property",
binding.locateAttributeBinding( "name" ).getPropertyAccessorName()
);
}
@Entity
class Base {
@Id
int id;
}
@Entity
@Access(AccessType.PROPERTY)
class ClassConfiguredAccess extends Base {
private String name;
public String getName() {
return name;
}
}
@Test
@Resources(annotatedClasses = { ClassConfiguredAccess.class, Base.class })
public void testExplicitClassConfiguredAccess() {
EntityBinding binding = getEntityBinding( Base.class );
assertEquals(
"Wrong access type",
"field",
binding.locateAttributeBinding( "id" ).getPropertyAccessorName()
);
binding = getEntityBinding( ClassConfiguredAccess.class );
assertEquals(
"Wrong access type",
"property",
binding.locateAttributeBinding( "name" ).getPropertyAccessorName()
);
}
}

View File

@ -1,128 +0,0 @@
/*
* 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.metamodel.source.annotations.entity;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.MethodRule;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;
import org.hibernate.metamodel.MetadataSources;
import org.hibernate.metamodel.binding.EntityBinding;
import org.hibernate.metamodel.source.internal.MetadataImpl;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.testing.junit4.BaseUnitTestCase;
/**
* @author Hardy Ferentschik
*/
public abstract class BaseAnnotationBindingTestCase extends BaseUnitTestCase {
protected MetadataSources sources;
protected MetadataImpl meta;
@Rule
public MethodRule buildMetaData = new MethodRule() {
@Override
public Statement apply(final Statement statement, FrameworkMethod frameworkMethod, Object o) {
return new KeepSetupFailureStatement( statement, frameworkMethod );
}
};
@After
public void tearDown() {
sources = null;
meta = null;
}
public EntityBinding getEntityBinding(Class<?> clazz) {
return meta.getEntityBinding( clazz.getName() );
}
public EntityBinding getRootEntityBinding(Class<?> clazz) {
return meta.getRootEntityBinding( clazz.getName() );
}
class KeepSetupFailureStatement extends Statement {
private final Statement origStatement;
private final FrameworkMethod origFrameworkMethod;
private Throwable setupError;
private boolean expectedException;
KeepSetupFailureStatement(Statement statement, FrameworkMethod frameworkMethod) {
this.origStatement = statement;
this.origFrameworkMethod = frameworkMethod;
}
@Override
public void evaluate() throws Throwable {
try {
createBindings();
origStatement.evaluate();
if ( setupError != null ) {
throw setupError;
}
}
catch ( Throwable t ) {
if ( setupError == null ) {
throw t;
}
else {
if ( !expectedException ) {
throw setupError;
}
}
}
}
private void createBindings() {
try {
sources = new MetadataSources( new ServiceRegistryBuilder().buildServiceRegistry() );
Resources resourcesAnnotation = origFrameworkMethod.getAnnotation( Resources.class );
if ( resourcesAnnotation != null ) {
sources.getMetadataBuilder().with( resourcesAnnotation.cacheMode() );
for ( Class<?> annotatedClass : resourcesAnnotation.annotatedClasses() ) {
sources.addAnnotatedClass( annotatedClass );
}
if ( !resourcesAnnotation.ormXmlPath().isEmpty() ) {
sources.addResource( resourcesAnnotation.ormXmlPath() );
}
}
meta = (MetadataImpl) sources.buildMetadata();
}
catch ( final Throwable t ) {
setupError = t;
Test testAnnotation = origFrameworkMethod.getAnnotation( Test.class );
Class<?> expected = testAnnotation.expected();
if ( t.getClass().equals( expected ) ) {
expectedException = true;
}
}
}
}
}

View File

@ -1,70 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.junit.Test;
import org.hibernate.annotations.BatchSize;
import org.hibernate.metamodel.binding.EntityBinding;
import static junit.framework.Assert.assertEquals;
/**
* Tests for {@code o.h.a.BatchSize}.
*
* @author Hardy Ferentschik
*/
public class BatchSizeBindingTest extends BaseAnnotationBindingTestCase {
@Test
@Resources(annotatedClasses = NoBatchSizeEntity.class)
public void testNoBatchSize() {
EntityBinding binding = getEntityBinding( NoBatchSizeEntity.class );
assertEquals( "Wrong batch size", -1, binding.getBatchSize() );
}
@Test
@Resources(annotatedClasses = BatchSizeEntity.class)
public void testBatchSize() {
EntityBinding binding = getEntityBinding( BatchSizeEntity.class );
assertEquals( "Wrong batch size", 100, binding.getBatchSize() );
}
@Entity
class NoBatchSizeEntity {
@Id
private int id;
}
@Entity
@BatchSize(size = 100)
class BatchSizeEntity {
@Id
private int id;
}
}

View File

@ -1,103 +0,0 @@
/*
* 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.metamodel.source.annotations.entity;
import javax.persistence.Cacheable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.SharedCacheMode;
import org.junit.Test;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.cache.spi.access.AccessType;
import org.hibernate.metamodel.binding.Caching;
import org.hibernate.metamodel.binding.EntityBinding;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertNull;
/**
* Tests for {@code o.h.a.Cache} and {@code j.p.Cacheable}.
*
* @author Hardy Ferentschik
*/
public class CacheBindingTest extends BaseAnnotationBindingTestCase {
@Test
@Resources(annotatedClasses = HibernateCacheEntity.class, cacheMode = SharedCacheMode.ALL)
public void testHibernateCaching() {
EntityBinding binding = getEntityBinding( HibernateCacheEntity.class );
assertNotNull( "There should be a cache binding", binding.getHierarchyDetails().getCaching() );
Caching caching = binding.getHierarchyDetails().getCaching();
assertEquals( "Wrong region", "foo", caching.getRegion() );
assertEquals( "Wrong strategy", AccessType.READ_WRITE, caching.getAccessType() );
assertEquals( "Wrong lazy properties configuration", false, caching.isCacheLazyProperties() );
}
@Test
@Resources(annotatedClasses = JpaCacheEntity.class, cacheMode = SharedCacheMode.ALL)
public void testJpaCaching() {
EntityBinding binding = getEntityBinding( JpaCacheEntity.class );
assertNotNull( "There should be a cache binding", binding.getHierarchyDetails().getCaching() );
Caching caching = binding.getHierarchyDetails().getCaching();
assertEquals(
"Wrong region",
this.getClass().getName() + "$" + JpaCacheEntity.class.getSimpleName(),
caching.getRegion()
);
assertEquals( "Wrong lazy properties configuration", true, caching.isCacheLazyProperties() );
}
@Test
@Resources(annotatedClasses = NoCacheEntity.class, cacheMode = SharedCacheMode.NONE)
public void testNoCaching() {
EntityBinding binding = getEntityBinding( NoCacheEntity.class );
assertNull( "There should be no cache binding", binding.getHierarchyDetails().getCaching() );
}
@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "foo", include = "non-lazy")
class HibernateCacheEntity {
@Id
private int id;
}
@Entity
@Cacheable
class JpaCacheEntity {
@Id
private int id;
}
@Entity
@Cacheable
class NoCacheEntity {
@Id
private int id;
}
}

View File

@ -1,113 +0,0 @@
/*
* 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.metamodel.source.annotations.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.junit.Test;
import org.hibernate.annotations.ResultCheckStyle;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.SQLDeleteAll;
import org.hibernate.annotations.SQLInsert;
import org.hibernate.annotations.SQLUpdate;
import org.hibernate.engine.spi.ExecuteUpdateResultCheckStyle;
import org.hibernate.metamodel.binding.CustomSQL;
import org.hibernate.metamodel.binding.EntityBinding;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertNull;
/**
* Tests for {@code o.h.a.SQLInsert}, {@code o.h.a.SQLUpdate}, {@code o.h.a.Delete} and {@code o.h.a.SQLDeleteAll}.
*
* @author Hardy Ferentschik
*/
public class CustomSQLBindingTest extends BaseAnnotationBindingTestCase {
@Test
@Resources(annotatedClasses = NoCustomSQLEntity.class)
public void testNoCustomSqlAnnotations() {
EntityBinding binding = getEntityBinding( NoCustomSQLEntity.class );
assertNull( binding.getCustomDelete() );
assertNull( binding.getCustomInsert() );
assertNull( binding.getCustomUpdate() );
}
@Test
@Resources(annotatedClasses = CustomSQLEntity.class)
public void testCustomSqlAnnotations() {
EntityBinding binding = getEntityBinding( CustomSQLEntity.class );
CustomSQL customSql = binding.getCustomInsert();
assertCustomSql( customSql, "INSERT INTO FOO", true, ExecuteUpdateResultCheckStyle.NONE );
customSql = binding.getCustomDelete();
assertCustomSql( customSql, "DELETE FROM FOO", false, ExecuteUpdateResultCheckStyle.COUNT );
customSql = binding.getCustomUpdate();
assertCustomSql( customSql, "UPDATE FOO", false, ExecuteUpdateResultCheckStyle.PARAM );
}
// not so sure about the validity of this one
// @Test
// public void testDeleteAllWins() {
// buildMetadataSources( CustomDeleteAllEntity.class );
// EntityBinding binding = getEntityBinding( CustomDeleteAllEntity.class );
// assertEquals( "Wrong sql", "DELETE ALL", binding.getCustomDelete().getSql() );
// }
private void assertCustomSql(CustomSQL customSql, String sql, boolean isCallable, ExecuteUpdateResultCheckStyle style) {
assertNotNull( customSql );
assertEquals( "Wrong sql", sql, customSql.getSql() );
assertEquals( isCallable, customSql.isCallable() );
assertEquals( style, customSql.getCheckStyle() );
}
@Entity
class NoCustomSQLEntity {
@Id
private int id;
}
@Entity
@SQLInsert(sql = "INSERT INTO FOO", callable = true)
@SQLDelete(sql = "DELETE FROM FOO", check = ResultCheckStyle.COUNT)
@SQLUpdate(sql = "UPDATE FOO", check = ResultCheckStyle.PARAM)
class CustomSQLEntity {
@Id
private int id;
}
@Entity
@SQLDelete(sql = "DELETE")
@SQLDeleteAll(sql = "DELETE ALL")
class CustomDeleteAllEntity {
@Id
private int id;
}
}

View File

@ -1,375 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.entity;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.junit.Test;
import org.hibernate.annotations.Parent;
import org.hibernate.annotations.Target;
import org.hibernate.metamodel.binding.BasicAttributeBinding;
import org.hibernate.metamodel.binding.ComponentAttributeBinding;
import org.hibernate.metamodel.binding.EntityBinding;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertTrue;
/**
* Tests for {@code javax.persistence.Embeddable}.
*
* @author Hardy Ferentschik
*/
public class EmbeddableBindingTest extends BaseAnnotationBindingTestCase {
@Entity
class User {
@Id
private int id;
@Embedded
private Phone phone;
}
@Embeddable
class Phone {
String countryCode;
String areaCode;
String number;
}
@Test
@Resources(annotatedClasses = { User.class, Phone.class })
public void testEmbeddable() {
EntityBinding binding = getEntityBinding( User.class );
final String componentName = "phone";
assertNotNull( binding.locateAttributeBinding( componentName ) );
assertTrue( binding.locateAttributeBinding( componentName ) instanceof ComponentAttributeBinding );
ComponentAttributeBinding componentBinding = (ComponentAttributeBinding) binding.locateAttributeBinding(
componentName
);
// todo - is this really correct? Does the path start w/ the class name
assertEquals(
"Wrong path",
"org.hibernate.metamodel.source.annotations.entity.EmbeddableBindingTest$User.phone",
componentBinding.getPathBase()
);
assertNotNull( componentBinding.locateAttributeBinding( "countryCode" ) );
assertNotNull( componentBinding.locateAttributeBinding( "areaCode" ) );
assertNotNull( componentBinding.locateAttributeBinding( "number" ) );
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@Entity
@AttributeOverride(name = "embedded.name", column = @Column(name = "FUBAR", length = 42))
class BaseEntity {
@Id
private int id;
@Embedded
private EmbeddedEntity embedded;
}
@Embeddable
class EmbeddedEntity {
String name;
}
@Test
@Resources(annotatedClasses = { BaseEntity.class, EmbeddedEntity.class })
public void testEmbeddableWithAttributeOverride() {
EntityBinding binding = getEntityBinding( BaseEntity.class );
final String componentName = "embedded";
assertNotNull( binding.locateAttributeBinding( componentName ) );
assertTrue( binding.locateAttributeBinding( componentName ) instanceof ComponentAttributeBinding );
ComponentAttributeBinding componentBinding = (ComponentAttributeBinding) binding.locateAttributeBinding(
componentName
);
assertNotNull( componentBinding.locateAttributeBinding( "name" ) );
BasicAttributeBinding nameAttribute = (BasicAttributeBinding) componentBinding.locateAttributeBinding( "name" );
org.hibernate.metamodel.relational.Column column = (org.hibernate.metamodel.relational.Column) nameAttribute.getValue();
assertEquals( "Attribute override specifies a custom column name", "FUBAR", column.getColumnName().getName() );
assertEquals( "Attribute override specifies a custom size", 42, column.getSize().getLength() );
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@Embeddable
public class Address {
protected String street;
protected String city;
protected String state;
@Embedded
protected Zipcode zipcode;
}
@Embeddable
public class Zipcode {
protected String zip;
protected String plusFour;
}
@Entity
public class Customer {
@Id
protected Integer id;
protected String name;
@AttributeOverrides( {
@AttributeOverride(name = "state",
column = @Column(name = "ADDR_STATE")),
@AttributeOverride(name = "zipcode.zip",
column = @Column(name = "ADDR_ZIP"))
})
@Embedded
protected Address address;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@Test
@Resources(annotatedClasses = { Zipcode.class, Address.class, Customer.class })
public void testNestedEmbeddable() {
EntityBinding binding = getEntityBinding( Customer.class );
final String addressComponentName = "address";
assertNotNull( binding.locateAttributeBinding( addressComponentName ) );
assertTrue( binding.locateAttributeBinding( addressComponentName ) instanceof ComponentAttributeBinding );
ComponentAttributeBinding attributeComponentBinding = (ComponentAttributeBinding) binding.locateAttributeBinding(
addressComponentName
);
assertNotNull( attributeComponentBinding.locateAttributeBinding( "street" ) );
assertNotNull( attributeComponentBinding.locateAttributeBinding( "city" ) );
assertNotNull( attributeComponentBinding.locateAttributeBinding( "state" ) );
BasicAttributeBinding stateAttribute = (BasicAttributeBinding) attributeComponentBinding.locateAttributeBinding(
"state"
);
org.hibernate.metamodel.relational.Column column = (org.hibernate.metamodel.relational.Column) stateAttribute.getValue();
assertEquals(
"Attribute override specifies a custom column name",
"ADDR_STATE",
column.getColumnName().getName()
);
final String zipComponentName = "zipcode";
assertNotNull( attributeComponentBinding.locateAttributeBinding( zipComponentName ) );
assertTrue( attributeComponentBinding.locateAttributeBinding( zipComponentName ) instanceof ComponentAttributeBinding );
ComponentAttributeBinding zipComponentBinding = (ComponentAttributeBinding) attributeComponentBinding.locateAttributeBinding(
zipComponentName
);
BasicAttributeBinding nameAttribute = (BasicAttributeBinding) zipComponentBinding.locateAttributeBinding( "zip" );
column = (org.hibernate.metamodel.relational.Column) nameAttribute.getValue();
assertEquals(
"Attribute override specifies a custom column name",
"ADDR_ZIP",
column.getColumnName().getName()
);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@Embeddable
public class A {
@Embedded
@AttributeOverrides( {
@AttributeOverride(name = "foo", column = @Column(name = "BAR")),
@AttributeOverride(name = "fubar", column = @Column(name = "A_WINS"))
})
private B b;
public B getB() {
return b;
}
}
@Embeddable
public class B {
private String foo;
private String fubar;
public String getFoo() {
return foo;
}
public String getFubar() {
return fubar;
}
}
@Entity
public class C {
@Id
int id;
@Embedded
@AttributeOverride(name = "b.fubar", column = @Column(name = "C_WINS"))
protected A a;
public int getId() {
return id;
}
public A getA() {
return a;
}
}
@Test
@Resources(annotatedClasses = { A.class, B.class, C.class })
public void testAttributeOverrideInEmbeddable() {
EntityBinding binding = getEntityBinding( C.class );
final String aComponentName = "a";
assertNotNull( binding.locateAttributeBinding( aComponentName ) );
assertTrue( binding.locateAttributeBinding( aComponentName ) instanceof ComponentAttributeBinding );
ComponentAttributeBinding aComponentBinding = (ComponentAttributeBinding) binding.locateAttributeBinding(
aComponentName
);
final String bComponentName = "b";
assertNotNull( aComponentBinding.locateAttributeBinding( bComponentName ) );
assertTrue( aComponentBinding.locateAttributeBinding( bComponentName ) instanceof ComponentAttributeBinding );
ComponentAttributeBinding bComponentBinding = (ComponentAttributeBinding) aComponentBinding.locateAttributeBinding(
bComponentName
);
BasicAttributeBinding attribute = (BasicAttributeBinding) bComponentBinding.locateAttributeBinding( "foo" );
org.hibernate.metamodel.relational.Column column = (org.hibernate.metamodel.relational.Column) attribute.getValue();
assertEquals(
"Attribute override specifies a custom column name",
"BAR",
column.getColumnName().getName()
);
attribute = (BasicAttributeBinding) bComponentBinding.locateAttributeBinding( "fubar" );
column = (org.hibernate.metamodel.relational.Column) attribute.getValue();
assertEquals(
"Attribute override specifies a custom column name",
"C_WINS",
column.getColumnName().getName()
);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@Embeddable
public class EmbeddableEntity {
private String test;
@Parent
private MainEntity parent;
}
@Entity
public class MainEntity {
@Id
private int id;
@Embedded
private EmbeddableEntity embedded;
}
@Test
@Resources(annotatedClasses = { MainEntity.class, EmbeddableEntity.class })
public void testParentReferencingAttributeName() {
EntityBinding binding = getEntityBinding( MainEntity.class );
final String componentName = "embedded";
assertNotNull( binding.locateAttributeBinding( componentName ) );
assertTrue( binding.locateAttributeBinding( componentName ) instanceof ComponentAttributeBinding );
ComponentAttributeBinding componentBinding = (ComponentAttributeBinding) binding.locateAttributeBinding(
componentName
);
assertEquals( "Wrong parent reference name", "parent", componentBinding.getParentReference().getName() );
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public interface Car {
int getHorsePower();
}
@Embeddable
public class CarImpl implements Car {
@Override
public int getHorsePower() {
return 0;
}
}
@Entity
public class Owner {
private int id;
private Car car;
@Id
public int getId() {
return id;
}
@Embedded
@Target(CarImpl.class)
public Car getCar() {
return car;
}
}
@Test
@Resources(annotatedClasses = { Owner.class, CarImpl.class, Car.class })
public void testTargetAnnotationWithEmbeddable() {
EntityBinding binding = getEntityBinding( Owner.class );
final String componentName = "car";
assertNotNull( binding.locateAttributeBinding( componentName ) );
assertTrue( binding.locateAttributeBinding( componentName ) instanceof ComponentAttributeBinding );
ComponentAttributeBinding componentBinding = (ComponentAttributeBinding) binding.locateAttributeBinding(
componentName
);
BasicAttributeBinding attribute = (BasicAttributeBinding) componentBinding.locateAttributeBinding( "horsePower" );
assertTrue( attribute.getAttribute().isTypeResolved() );
assertEquals(
"Wrong resolved type",
"int",
attribute.getAttribute().getSingularAttributeType().getClassName()
);
}
}

View File

@ -1,71 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.entity;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Embeddable;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import org.junit.Test;
import org.hibernate.metamodel.binding.EntityBinding;
import org.hibernate.metamodel.binding.EntityIdentifier;
import org.hibernate.testing.FailureExpected;
import static junit.framework.Assert.assertTrue;
/**
* @author Strong Liu
*/
@FailureExpected(jiraKey = "HHH-6447", message = "Work in progress")
public class EmbeddedIdTest extends BaseAnnotationBindingTestCase {
@Test
// @Resources(annotatedClasses = { User.class, Address.class })
public void testEmbeddable() {
EntityBinding binding = getEntityBinding( User.class );
EntityIdentifier identifier = binding.getHierarchyDetails().getEntityIdentifier();
assertTrue( identifier.isEmbedded() );
}
@Entity
@Access( AccessType.FIELD )
class User {
private String name;
@EmbeddedId
private Address address;
}
@Embeddable
class Address {
String street;
String city;
String postCode;
}
}

View File

@ -1,106 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.entity;
import java.sql.Types;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Id;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.junit.Test;
import org.hibernate.metamodel.binding.AttributeBinding;
import org.hibernate.metamodel.binding.EntityBinding;
import org.hibernate.metamodel.binding.HibernateTypeDescriptor;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
/**
* @author Strong Liu
*/
public class EnumeratedBindingTest extends BaseAnnotationBindingTestCase {
@Entity
class Item {
@Id
long id;
@Temporal(TemporalType.TIMESTAMP)
Date orderDate;
String name;
@Enumerated(EnumType.STRING)
OrderType orderType;
CustomerType customerType;
}
enum CustomerType {
PROGRAMMER, BOSS;
}
enum OrderType {
B2C, C2C, MAIL, DIRECT;
}
@Test
@Resources(annotatedClasses = Item.class)
public void testEnumeratedTypeAttribute() {
EntityBinding binding = getEntityBinding( Item.class );
AttributeBinding attributeBinding = binding.locateAttributeBinding( "customerType" );
HibernateTypeDescriptor descriptor = attributeBinding.getHibernateTypeDescriptor();
assertEquals( org.hibernate.type.EnumType.class.getName(), descriptor.getExplicitTypeName() );
assertEquals( CustomerType.class.getName(), descriptor.getJavaTypeName() );
assertNotNull( descriptor.getResolvedTypeMapping() );
assertFalse( descriptor.getTypeParameters().isEmpty() );
assertEquals(
CustomerType.class.getName(),
descriptor.getTypeParameters().get( org.hibernate.type.EnumType.ENUM )
);
assertEquals(
String.valueOf( Types.INTEGER ),
descriptor.getTypeParameters().get( org.hibernate.type.EnumType.TYPE )
);
attributeBinding = binding.locateAttributeBinding( "orderType" );
descriptor = attributeBinding.getHibernateTypeDescriptor();
assertEquals( org.hibernate.type.EnumType.class.getName(), descriptor.getExplicitTypeName() );
assertEquals( OrderType.class.getName(), descriptor.getJavaTypeName() );
assertNotNull( descriptor.getResolvedTypeMapping() );
assertFalse( descriptor.getTypeParameters().isEmpty() );
assertEquals(
OrderType.class.getName(),
descriptor.getTypeParameters().get( org.hibernate.type.EnumType.ENUM )
);
assertEquals(
String.valueOf( Types.VARCHAR ),
descriptor.getTypeParameters().get( org.hibernate.type.EnumType.TYPE )
);
}
}

View File

@ -1,188 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.junit.Test;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.id.Assigned;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.id.IdentityGenerator;
import org.hibernate.id.MultipleHiLoPerTableGenerator;
import org.hibernate.id.SequenceHiLoGenerator;
import org.hibernate.id.UUIDHexGenerator;
import org.hibernate.metamodel.MetadataSources;
import org.hibernate.metamodel.binding.EntityBinding;
import org.hibernate.metamodel.binding.EntityIdentifier;
import org.hibernate.metamodel.source.MappingException;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.testing.DialectCheck;
import org.hibernate.testing.DialectChecks;
import org.hibernate.testing.RequiresDialect;
import org.hibernate.testing.RequiresDialectFeature;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertTrue;
import static junit.framework.Assert.fail;
/**
* @author Hardy Ferentschik
*/
@RequiresDialect(H2Dialect.class)
public class IdentifierGeneratorTest extends BaseAnnotationBindingTestCase {
@Entity
class NoGenerationEntity {
@Id
private long id;
}
@Test
@Resources(annotatedClasses = NoGenerationEntity.class)
public void testNoIdGeneration() {
EntityBinding binding = getEntityBinding( NoGenerationEntity.class );
EntityIdentifier identifier = binding.getHierarchyDetails().getEntityIdentifier();
IdentifierGenerator generator =identifier.getIdentifierGenerator();
assertNotNull( generator );
assertEquals( "Wrong generator", Assigned.class, generator.getClass() );
assertFalse( identifier.isEmbedded() );
}
@Entity
class AutoEntity {
@Id
@GeneratedValue
private long id;
public long getId() {
return id;
}
}
@Test
@Resources(annotatedClasses = AutoEntity.class)
public void testAutoGenerationType() {
EntityBinding binding = getEntityBinding( AutoEntity.class );
IdentifierGenerator generator = binding.getHierarchyDetails().getEntityIdentifier().getIdentifierGenerator();
assertEquals( "Wrong generator", IdentityGenerator.class, generator.getClass() );
}
@Entity
class TableEntity {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private long id;
public long getId() {
return id;
}
}
@Test
@Resources(annotatedClasses = TableEntity.class)
public void testTableGenerationType() {
EntityBinding binding = getEntityBinding( TableEntity.class );
IdentifierGenerator generator = binding.getHierarchyDetails().getEntityIdentifier().getIdentifierGenerator();
assertEquals( "Wrong generator", MultipleHiLoPerTableGenerator.class, generator.getClass() );
}
@Entity
class SequenceEntity {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;
public long getId() {
return id;
}
}
@Test
@Resources(annotatedClasses = SequenceEntity.class)
public void testSequenceGenerationType() {
EntityBinding binding = getEntityBinding( SequenceEntity.class );
IdentifierGenerator generator = binding.getHierarchyDetails().getEntityIdentifier().getIdentifierGenerator();
assertEquals( "Wrong generator", SequenceHiLoGenerator.class, generator.getClass() );
}
@Entity
class NamedGeneratorEntity {
@Id
@GeneratedValue(generator = "my-generator")
private long id;
public long getId() {
return id;
}
}
@Test
public void testUndefinedGenerator() {
try {
sources = new MetadataSources( new ServiceRegistryBuilder().buildServiceRegistry() );
sources.addAnnotatedClass( NamedGeneratorEntity.class );
sources.buildMetadata();
fail();
}
catch ( MappingException e ) {
assertTrue( e.getMessage().startsWith( "Unable to find named generator" ) );
}
}
@Entity
@GenericGenerator(name = "my-generator", strategy = "uuid")
class NamedGeneratorEntity2 {
@Id
@GeneratedValue(generator = "my-generator")
private long id;
public long getId() {
return id;
}
}
@Test
@Resources(annotatedClasses = NamedGeneratorEntity2.class)
public void testNamedGenerator() {
EntityBinding binding = getEntityBinding( NamedGeneratorEntity2.class );
IdentifierGenerator generator = binding.getHierarchyDetails().getEntityIdentifier().getIdentifierGenerator();
assertEquals( "Wrong generator", UUIDHexGenerator.class, generator.getClass() );
}
}

View File

@ -1,526 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.entity;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.junit.Test;
import org.hibernate.annotations.DiscriminatorFormula;
import org.hibernate.annotations.DiscriminatorOptions;
import org.hibernate.metamodel.binding.AttributeBinding;
import org.hibernate.metamodel.binding.EntityBinding;
import org.hibernate.metamodel.binding.EntityDiscriminator;
import org.hibernate.metamodel.relational.DerivedValue;
import org.hibernate.metamodel.relational.SimpleValue;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertSame;
import static junit.framework.Assert.assertTrue;
/**
* @author Hardy Ferentschik
*/
public class InheritanceBindingTest extends BaseAnnotationBindingTestCase {
@Test
@Resources(annotatedClasses = SingleEntity.class)
public void testNoInheritance() {
EntityBinding entityBinding = getEntityBinding( SingleEntity.class );
assertNull( entityBinding.getHierarchyDetails().getEntityDiscriminator() );
assertFalse( entityBinding.isPolymorphic() );
}
@Test
@Resources(annotatedClasses = { RootOfSingleTableInheritance.class, SubclassOfSingleTableInheritance.class })
public void testDiscriminatorValue() {
EntityBinding entityBinding = getEntityBinding( SubclassOfSingleTableInheritance.class );
assertEquals( "Wrong discriminator value", "foo1", entityBinding.getDiscriminatorMatchValue() );
}
@Test
@Resources(annotatedClasses = { RootOfSingleTableInheritance.class, SubclassOfSingleTableInheritance.class })
public void testSubclassEntitySuperType() {
EntityBinding entityBinding = getEntityBinding( SubclassOfSingleTableInheritance.class );
assertNotNull( entityBinding.getEntity().getSuperType() );
assertSame( RootOfSingleTableInheritance.class, entityBinding.getEntity().getSuperType().getClassReference() );
assertEquals( RootOfSingleTableInheritance.class.getName(), entityBinding.getEntity().getSuperType().getClassName() );
assertNull( entityBinding.getEntity().getSuperType().getSuperType() );
}
@Test
@Resources(annotatedClasses = { RootOfSingleTableInheritance.class, SubclassOfSingleTableInheritance.class })
public void testRootEntitySuperType() {
EntityBinding entityBinding = getEntityBinding( RootOfSingleTableInheritance.class );
assertNull( entityBinding.getEntity().getSuperType() );
}
@Test
@Resources(annotatedClasses = {
SubclassOfSingleTableInheritance.class,
SingleEntity.class,
RootOfSingleTableInheritance.class
})
public void testRootEntityBinding() {
EntityBinding noInheritanceEntityBinding = getEntityBinding( SingleEntity.class );
assertTrue( "SingleEntity should be a root entity", noInheritanceEntityBinding.isRoot() );
assertSame( noInheritanceEntityBinding, getRootEntityBinding( SingleEntity.class ) );
EntityBinding subclassEntityBinding = getEntityBinding( SubclassOfSingleTableInheritance.class );
EntityBinding rootEntityBinding = getEntityBinding( RootOfSingleTableInheritance.class );
assertFalse( subclassEntityBinding.isRoot() );
assertSame( rootEntityBinding, getRootEntityBinding( SubclassOfSingleTableInheritance.class ) );
assertTrue( rootEntityBinding.isRoot() );
assertSame( rootEntityBinding, getRootEntityBinding( RootOfSingleTableInheritance.class ) );
}
@Test
@Resources(annotatedClasses = {
SubclassOfSingleTableInheritance.class,
SingleEntity.class,
RootOfSingleTableInheritance.class,
OtherSubclassOfSingleTableInheritance.class,
SubclassOfSubclassOfSingleTableInheritance.class
})
public void testNoPolymorphism() {
EntityBinding noInheritanceEntityBinding = getEntityBinding( SingleEntity.class );
assertTrue( "SingleEntity should be a root entity", noInheritanceEntityBinding.isRoot() );
assertNull( noInheritanceEntityBinding.getSuperEntityBinding() );
assertSame( noInheritanceEntityBinding, getRootEntityBinding( SingleEntity.class ) );
assertFalse( noInheritanceEntityBinding.isPolymorphic() );
assertFalse( noInheritanceEntityBinding.hasSubEntityBindings() );
assertEquals( 0, noInheritanceEntityBinding.getSubEntityBindingClosureSpan() );
assertFalse( noInheritanceEntityBinding.getPostOrderSubEntityBindingClosure().iterator().hasNext() );
assertFalse( noInheritanceEntityBinding.getPreOrderSubEntityBindingClosure().iterator().hasNext() );
Set<AttributeBinding> directAttributeBindings = new HashSet<AttributeBinding>();
for ( AttributeBinding attributeBinding : noInheritanceEntityBinding.attributeBindings() ) {
assertTrue( directAttributeBindings.add( attributeBinding ) );
}
assertEquals( 1, directAttributeBindings.size() );
assertSame(
noInheritanceEntityBinding.getHierarchyDetails().getEntityIdentifier().getValueBinding(),
directAttributeBindings.iterator().next()
);
assertEquals( 1, noInheritanceEntityBinding.getAttributeBindingClosureSpan() );
Iterator<AttributeBinding> iterator = noInheritanceEntityBinding.attributeBindings().iterator();
assertTrue( iterator.hasNext() );
assertSame( noInheritanceEntityBinding.getHierarchyDetails().getEntityIdentifier().getValueBinding(), iterator.next() );
assertFalse( iterator.hasNext() );
iterator = noInheritanceEntityBinding.getAttributeBindingClosure().iterator();
assertTrue( iterator.hasNext() );
assertSame( noInheritanceEntityBinding.getHierarchyDetails().getEntityIdentifier().getValueBinding(), iterator.next() );
assertFalse( iterator.hasNext() );
iterator = noInheritanceEntityBinding.getSubEntityAttributeBindingClosure().iterator();
assertTrue( iterator.hasNext() );
assertSame( noInheritanceEntityBinding.getHierarchyDetails().getEntityIdentifier().getValueBinding(), iterator.next() );
assertFalse( iterator.hasNext() );
}
@Test
@Resources(annotatedClasses = {
SubclassOfSingleTableInheritance.class,
SingleEntity.class,
RootOfSingleTableInheritance.class,
OtherSubclassOfSingleTableInheritance.class,
SubclassOfSubclassOfSingleTableInheritance.class
})
public void testRootPolymporhism() {
EntityBinding rootEntityBinding = getEntityBinding( RootOfSingleTableInheritance.class );
EntityBinding subclassEntityBinding = getEntityBinding( SubclassOfSingleTableInheritance.class );
EntityBinding otherSubclassEntityBinding = getEntityBinding( OtherSubclassOfSingleTableInheritance.class );
EntityBinding subclassOfSubclassEntityBinding = getEntityBinding( SubclassOfSubclassOfSingleTableInheritance.class );
assertTrue( rootEntityBinding.isRoot() );
assertNull( rootEntityBinding.getDiscriminatorMatchValue() );
assertNull( rootEntityBinding.getSuperEntityBinding() );
assertSame( rootEntityBinding, getRootEntityBinding( RootOfSingleTableInheritance.class ) );
assertTrue( rootEntityBinding.isPolymorphic() );
assertTrue( rootEntityBinding.hasSubEntityBindings() );
Iterator<EntityBinding> directEntityBindingIterator = rootEntityBinding.getDirectSubEntityBindings().iterator();
assertTrue( directEntityBindingIterator.hasNext() );
EntityBinding directSubEntityBinding1 = directEntityBindingIterator.next();
assertTrue( directEntityBindingIterator.hasNext() );
EntityBinding directSubEntityBinding2 = directEntityBindingIterator.next();
assertFalse( directEntityBindingIterator.hasNext() );
boolean isSubclassEntityBindingFirst = directSubEntityBinding1 == subclassEntityBinding;
if ( isSubclassEntityBindingFirst ) {
assertSame( otherSubclassEntityBinding, directSubEntityBinding2 );
}
else {
assertSame( otherSubclassEntityBinding, directSubEntityBinding1 );
assertSame( subclassEntityBinding, directSubEntityBinding2 );
}
Set<AttributeBinding> directAttributeBindings = new HashSet<AttributeBinding>();
for ( AttributeBinding attributeBinding : rootEntityBinding.attributeBindings() ) {
assertTrue( directAttributeBindings.add( attributeBinding ) );
}
assertEquals( 1, directAttributeBindings.size() );
assertTrue( directAttributeBindings.contains( rootEntityBinding.locateAttributeBinding( "id" ) ) );
assertEquals( 1, rootEntityBinding.getAttributeBindingClosureSpan() );
Set<AttributeBinding> attributeBindingClosure = new HashSet<AttributeBinding>();
for ( AttributeBinding attributeBinding : rootEntityBinding.getAttributeBindingClosure() ) {
assertTrue( attributeBindingClosure.add( attributeBinding ) );
}
assertEquals( 1, attributeBindingClosure.size() );
assertTrue( attributeBindingClosure.contains( rootEntityBinding.locateAttributeBinding( "id" ) ) );
Set<AttributeBinding> subAttributeBindings = new HashSet<AttributeBinding>();
for ( AttributeBinding subAttributeBinding : rootEntityBinding.getSubEntityAttributeBindingClosure() ) {
assertTrue( subAttributeBindings.add( subAttributeBinding ) );
}
assertEquals( 4, subAttributeBindings.size() );
assertTrue( subAttributeBindings.contains( rootEntityBinding.locateAttributeBinding( "id" ) ) );
assertTrue( subAttributeBindings.contains( subclassEntityBinding.locateAttributeBinding( "name" ) ) );
assertTrue( subAttributeBindings.contains( subclassOfSubclassEntityBinding.locateAttributeBinding( "otherOtherName" ) ) );
assertTrue( subAttributeBindings.contains( otherSubclassEntityBinding.locateAttributeBinding( "otherName" ) ) );
}
@Test
@Resources(annotatedClasses = {
SubclassOfSingleTableInheritance.class,
SingleEntity.class,
RootOfSingleTableInheritance.class,
OtherSubclassOfSingleTableInheritance.class,
SubclassOfSubclassOfSingleTableInheritance.class
})
public void testPreOrderRootSubEntityClosure() {
EntityBinding rootEntityBinding = getEntityBinding( RootOfSingleTableInheritance.class );
EntityBinding subclassEntityBinding = getEntityBinding( SubclassOfSingleTableInheritance.class );
EntityBinding otherSubclassEntityBinding = getEntityBinding( OtherSubclassOfSingleTableInheritance.class );
EntityBinding subclassOfSubclassEntityBinding = getEntityBinding( SubclassOfSubclassOfSingleTableInheritance.class );
// need to figure out the order of direct subclasses, since it's indeterminate
Iterator<EntityBinding> directEntityBindingIterator = rootEntityBinding.getDirectSubEntityBindings().iterator();
boolean isSubclassEntityBindingFirst = subclassEntityBinding == directEntityBindingIterator.next();
assertEquals( 3, rootEntityBinding.getSubEntityBindingClosureSpan() );
Iterator<EntityBinding> subEntityBindingIterator = rootEntityBinding.getPreOrderSubEntityBindingClosure().iterator();
assertTrue( subEntityBindingIterator.hasNext() );
if ( isSubclassEntityBindingFirst ) {
assertSame( subclassEntityBinding, subEntityBindingIterator.next() );
assertTrue( subEntityBindingIterator.hasNext() );
assertSame( subclassOfSubclassEntityBinding, subEntityBindingIterator.next() );
assertTrue( subEntityBindingIterator.hasNext() );
assertSame( otherSubclassEntityBinding, subEntityBindingIterator.next() );
}
else {
assertSame( otherSubclassEntityBinding, subEntityBindingIterator.next() );
assertTrue( subEntityBindingIterator.hasNext() );
assertSame( subclassEntityBinding, subEntityBindingIterator.next() );
assertTrue( subEntityBindingIterator.hasNext() );
assertSame( subclassOfSubclassEntityBinding, subEntityBindingIterator.next() );
}
assertFalse( subEntityBindingIterator.hasNext() );
}
@Test
@Resources(annotatedClasses = {
SubclassOfSingleTableInheritance.class,
SingleEntity.class,
RootOfSingleTableInheritance.class,
OtherSubclassOfSingleTableInheritance.class,
SubclassOfSubclassOfSingleTableInheritance.class
})
public void testPostOrderRootSubEntityClosure() {
EntityBinding rootEntityBinding = getEntityBinding( RootOfSingleTableInheritance.class );
EntityBinding subclassEntityBinding = getEntityBinding( SubclassOfSingleTableInheritance.class );
EntityBinding otherSubclassEntityBinding = getEntityBinding( OtherSubclassOfSingleTableInheritance.class );
EntityBinding subclassOfSubclassEntityBinding = getEntityBinding( SubclassOfSubclassOfSingleTableInheritance.class );
// need to figure out the order of direct subclasses, since it's indeterminate
Iterator<EntityBinding> directEntityBindingIterator = rootEntityBinding.getDirectSubEntityBindings().iterator();
boolean isSubclassEntityBindingFirst = subclassEntityBinding == directEntityBindingIterator.next();
assertEquals( 3, rootEntityBinding.getSubEntityBindingClosureSpan() );
Iterator<EntityBinding> subEntityBindingIterator = rootEntityBinding.getPostOrderSubEntityBindingClosure().iterator();
assertTrue( subEntityBindingIterator.hasNext() );
if ( isSubclassEntityBindingFirst ) {
assertSame( subclassOfSubclassEntityBinding, subEntityBindingIterator.next() );
assertSame( subclassEntityBinding, subEntityBindingIterator.next() );
assertSame( otherSubclassEntityBinding, subEntityBindingIterator.next() );
}
else {
assertSame( subclassOfSubclassEntityBinding, subEntityBindingIterator.next() );
assertSame( otherSubclassEntityBinding, subEntityBindingIterator.next() );
assertSame( subclassEntityBinding, subEntityBindingIterator.next() );
}
assertFalse( subEntityBindingIterator.hasNext() );
}
@Test
@Resources(annotatedClasses = {
SubclassOfSingleTableInheritance.class,
SingleEntity.class,
RootOfSingleTableInheritance.class,
OtherSubclassOfSingleTableInheritance.class,
SubclassOfSubclassOfSingleTableInheritance.class
})
public void testLeafSubclassOfRoot() {
EntityBinding rootEntityBinding = getEntityBinding( RootOfSingleTableInheritance.class );
EntityBinding subclassEntityBinding = getEntityBinding( SubclassOfSingleTableInheritance.class );
EntityBinding otherSubclassEntityBinding = getEntityBinding( OtherSubclassOfSingleTableInheritance.class );
EntityBinding subclassOfSubclassEntityBinding = getEntityBinding( SubclassOfSubclassOfSingleTableInheritance.class );
assertEquals( "Wrong discriminator value", "foo2", otherSubclassEntityBinding.getDiscriminatorMatchValue() );
assertFalse( otherSubclassEntityBinding.isRoot() );
assertSame( rootEntityBinding, otherSubclassEntityBinding.getSuperEntityBinding() );
assertSame( rootEntityBinding, getRootEntityBinding( OtherSubclassOfSingleTableInheritance.class) );
assertTrue( otherSubclassEntityBinding.isPolymorphic() );
assertFalse( otherSubclassEntityBinding.hasSubEntityBindings() );
assertEquals( 0, otherSubclassEntityBinding.getSubEntityBindingClosureSpan() );
assertFalse( otherSubclassEntityBinding.getPostOrderSubEntityBindingClosure().iterator().hasNext() );
assertFalse( otherSubclassEntityBinding.getPreOrderSubEntityBindingClosure().iterator().hasNext() );
Set<AttributeBinding> directAttributeBindings = new HashSet<AttributeBinding>();
for ( AttributeBinding attributeBinding : otherSubclassEntityBinding.attributeBindings() ) {
assertTrue( directAttributeBindings.add( attributeBinding ) );
}
assertEquals( 1, directAttributeBindings.size() );
assertTrue( directAttributeBindings.contains( otherSubclassEntityBinding.locateAttributeBinding( "otherName" ) ) );
assertEquals( 2, otherSubclassEntityBinding.getAttributeBindingClosureSpan() );
Set<AttributeBinding> attributeBindingClosure = new HashSet<AttributeBinding>();
for ( AttributeBinding attributeBinding : otherSubclassEntityBinding.getAttributeBindingClosure() ) {
assertTrue( attributeBindingClosure.add( attributeBinding ) );
}
assertEquals(2, attributeBindingClosure.size() );
assertTrue( attributeBindingClosure.contains( rootEntityBinding.locateAttributeBinding( "id" ) ) );
assertTrue( attributeBindingClosure.contains( otherSubclassEntityBinding.locateAttributeBinding( "otherName" ) ) );
Set<AttributeBinding> subAttributeBindings = new HashSet<AttributeBinding>();
for ( AttributeBinding subAttributeBinding : otherSubclassEntityBinding.getSubEntityAttributeBindingClosure() ) {
assertTrue( subAttributeBindings.add( subAttributeBinding ) );
}
assertEquals( 2, subAttributeBindings.size() );
assertTrue( subAttributeBindings.contains( rootEntityBinding.locateAttributeBinding( "id" ) ) );
assertTrue( subAttributeBindings.contains( otherSubclassEntityBinding.locateAttributeBinding( "otherName" ) ) );
}
@Test
@Resources(annotatedClasses = {
SubclassOfSingleTableInheritance.class,
SingleEntity.class,
RootOfSingleTableInheritance.class,
OtherSubclassOfSingleTableInheritance.class,
SubclassOfSubclassOfSingleTableInheritance.class
})
public void testNonLeafSubclassOfRootPolymporhism() {
EntityBinding rootEntityBinding = getEntityBinding( RootOfSingleTableInheritance.class );
EntityBinding subclassEntityBinding = getEntityBinding( SubclassOfSingleTableInheritance.class );
EntityBinding otherSubclassEntityBinding = getEntityBinding( OtherSubclassOfSingleTableInheritance.class );
EntityBinding subclassOfSubclassEntityBinding = getEntityBinding( SubclassOfSubclassOfSingleTableInheritance.class );
assertEquals( "Wrong discriminator value", "foo1", subclassEntityBinding.getDiscriminatorMatchValue() );
assertFalse( subclassEntityBinding.isRoot() );
assertSame( rootEntityBinding, subclassEntityBinding.getSuperEntityBinding() );
assertSame( rootEntityBinding, getRootEntityBinding( SubclassOfSingleTableInheritance.class ) );
assertTrue( subclassEntityBinding.isPolymorphic() );
assertTrue( subclassEntityBinding.hasSubEntityBindings() );
assertEquals( 1, subclassEntityBinding.getSubEntityBindingClosureSpan() );
Iterator<EntityBinding> itSubEntityBindings = subclassEntityBinding.getPostOrderSubEntityBindingClosure().iterator();
assertTrue( itSubEntityBindings.hasNext() );
assertSame( subclassOfSubclassEntityBinding, itSubEntityBindings.next() );
assertFalse( itSubEntityBindings.hasNext() );
itSubEntityBindings = subclassEntityBinding.getPreOrderSubEntityBindingClosure().iterator();
assertTrue( itSubEntityBindings.hasNext() );
assertSame( subclassOfSubclassEntityBinding, itSubEntityBindings.next() );
assertFalse( itSubEntityBindings.hasNext() );
Set<AttributeBinding> directAttributeBindings = new HashSet<AttributeBinding>();
for ( AttributeBinding attributeBinding : subclassEntityBinding.attributeBindings() ) {
assertTrue( directAttributeBindings.add( attributeBinding ) );
}
assertEquals( 1, directAttributeBindings.size() );
assertTrue( directAttributeBindings.contains( subclassEntityBinding.locateAttributeBinding( "name" ) ) );
assertEquals( 2, subclassEntityBinding.getAttributeBindingClosureSpan() );
Set<AttributeBinding> attributeBindingClosure = new HashSet<AttributeBinding>();
for ( AttributeBinding attributeBinding : subclassEntityBinding.getAttributeBindingClosure() ) {
assertTrue( attributeBindingClosure.add( attributeBinding ) );
}
assertEquals( 2, attributeBindingClosure.size() );
assertTrue( attributeBindingClosure.contains( rootEntityBinding.locateAttributeBinding( "id" ) ) );
assertTrue( attributeBindingClosure.contains( subclassEntityBinding.locateAttributeBinding( "name" ) ) );
Set<AttributeBinding> subAttributeBindings = new HashSet<AttributeBinding>();
for ( AttributeBinding subAttributeBinding : subclassEntityBinding.getSubEntityAttributeBindingClosure() ) {
assertTrue( subAttributeBindings.add( subAttributeBinding ) );
}
assertEquals( 3, subAttributeBindings.size() );
assertTrue( subAttributeBindings.contains( rootEntityBinding.locateAttributeBinding( "id" ) ) );
assertTrue( subAttributeBindings.contains( subclassEntityBinding.locateAttributeBinding( "name" ) ) );
assertTrue( subAttributeBindings.contains( subclassOfSubclassEntityBinding.locateAttributeBinding( "otherOtherName" ) ) );
}
@Test
@Resources(annotatedClasses = {
SubclassOfSingleTableInheritance.class,
SingleEntity.class,
RootOfSingleTableInheritance.class,
OtherSubclassOfSingleTableInheritance.class,
SubclassOfSubclassOfSingleTableInheritance.class
})
public void testLeafSubclassOfSubclassOfRootPolymporhism() {
EntityBinding rootEntityBinding = getEntityBinding( RootOfSingleTableInheritance.class );
EntityBinding subclassEntityBinding = getEntityBinding( SubclassOfSingleTableInheritance.class );
EntityBinding otherSubclassEntityBinding = getEntityBinding( OtherSubclassOfSingleTableInheritance.class );
EntityBinding subclassOfSubclassEntityBinding = getEntityBinding( SubclassOfSubclassOfSingleTableInheritance.class );
assertEquals( "Wrong discriminator value", "foo1_1", subclassOfSubclassEntityBinding.getDiscriminatorMatchValue() );
assertFalse( subclassOfSubclassEntityBinding.isRoot() );
assertSame( subclassEntityBinding, subclassOfSubclassEntityBinding.getSuperEntityBinding() );
assertSame( rootEntityBinding, getRootEntityBinding( SubclassOfSubclassOfSingleTableInheritance.class ) );
assertTrue( subclassOfSubclassEntityBinding.isPolymorphic() );
assertFalse( subclassOfSubclassEntityBinding.hasSubEntityBindings() );
assertEquals( 0, subclassOfSubclassEntityBinding.getSubEntityBindingClosureSpan() );
assertFalse( subclassOfSubclassEntityBinding.getPostOrderSubEntityBindingClosure().iterator().hasNext() );
assertFalse( subclassOfSubclassEntityBinding.getPreOrderSubEntityBindingClosure().iterator().hasNext() );
Set<AttributeBinding> directAttributeBindings = new HashSet<AttributeBinding>();
for ( AttributeBinding attributeBinding : subclassOfSubclassEntityBinding.attributeBindings() ) {
assertTrue( directAttributeBindings.add( attributeBinding ) );
}
assertEquals( 1, directAttributeBindings.size() );
assertTrue( directAttributeBindings.contains( subclassOfSubclassEntityBinding.locateAttributeBinding( "otherOtherName" ) ) );
assertEquals( 3, subclassOfSubclassEntityBinding.getAttributeBindingClosureSpan() );
Set<AttributeBinding> attributeBindingClosure = new HashSet<AttributeBinding>();
for ( AttributeBinding attributeBinding : subclassOfSubclassEntityBinding.getAttributeBindingClosure() ) {
assertTrue( attributeBindingClosure.add( attributeBinding ) );
}
assertEquals( 3, attributeBindingClosure.size() );
assertTrue( attributeBindingClosure.contains( rootEntityBinding.locateAttributeBinding( "id" ) ) );
assertTrue( attributeBindingClosure.contains( subclassEntityBinding.locateAttributeBinding( "name" ) ) );
assertTrue( attributeBindingClosure.contains( subclassOfSubclassEntityBinding.locateAttributeBinding( "otherOtherName" ) ) );
Set<AttributeBinding> subAttributeBindings = new HashSet<AttributeBinding>();
for ( AttributeBinding subAttributeBinding : subclassOfSubclassEntityBinding.getSubEntityAttributeBindingClosure() ) {
assertTrue( subAttributeBindings.add( subAttributeBinding ) );
}
assertEquals( 3, subAttributeBindings.size() );
assertTrue( subAttributeBindings.contains( rootEntityBinding.locateAttributeBinding( "id" ) ) );
assertTrue( subAttributeBindings.contains( subclassEntityBinding.locateAttributeBinding( "name" ) ) );
assertTrue( subAttributeBindings.contains( subclassOfSubclassEntityBinding.locateAttributeBinding( "otherOtherName" ) ) );
}
@Test
@Resources(annotatedClasses = { RootOfSingleTableInheritance.class, SubclassOfSingleTableInheritance.class })
public void testDefaultDiscriminatorOptions() {
EntityBinding rootEntityBinding = getEntityBinding( RootOfSingleTableInheritance.class );
EntityDiscriminator discriminator = rootEntityBinding.getHierarchyDetails().getEntityDiscriminator();
assertFalse( "Wrong default value", discriminator.isForced() );
assertTrue( "Wrong default value", discriminator.isInserted() );
}
@Test
@Resources(annotatedClasses = { Base.class, Jump.class })
public void testExplicitDiscriminatorOptions() {
EntityBinding rootEntityBinding = getEntityBinding( Base.class );
EntityDiscriminator discriminator = rootEntityBinding.getHierarchyDetails().getEntityDiscriminator();
assertTrue( "Wrong default value", discriminator.isForced() );
assertFalse( "Wrong default value", discriminator.isInserted() );
}
@Test
@Resources(annotatedClasses = { Base.class, Jump.class })
public void testRootDiscriminatorMatchValue() {
EntityBinding rootEntityBinding = getEntityBinding( Base.class );
assertEquals( "base", rootEntityBinding.getDiscriminatorMatchValue() );
}
@Test
@Resources(annotatedClasses = { Fruit.class, Apple.class })
public void testDiscriminatorFormula() {
EntityBinding rootEntityBinding = getEntityBinding( Fruit.class );
assertTrue( rootEntityBinding.isRoot() );
EntityBinding entityBinding = getEntityBinding( Apple.class );
assertFalse( entityBinding.isRoot() );
EntityDiscriminator discriminator = rootEntityBinding.getHierarchyDetails().getEntityDiscriminator();
SimpleValue simpleValue = discriminator.getBoundValue();
assertTrue( simpleValue instanceof DerivedValue);
DerivedValue derivedValue = (DerivedValue)simpleValue;
assertEquals( "case when zik_type is null then 0 else zik_type end", derivedValue.getExpression() );
assertTrue( "Wrong default value", discriminator.isForced() );
assertFalse( "Wrong default value", discriminator.isInserted() );
}
@Entity
class SingleEntity {
@Id
@GeneratedValue
private int id;
}
@Entity
class RootOfSingleTableInheritance {
@Id
@GeneratedValue
private int id;
}
@Entity
@DiscriminatorValue("foo1")
public class SubclassOfSingleTableInheritance extends RootOfSingleTableInheritance {
private String name;
}
@Entity
@DiscriminatorValue("foo2")
public class OtherSubclassOfSingleTableInheritance extends RootOfSingleTableInheritance {
private String otherName;
}
@Entity
@DiscriminatorValue("foo1_1")
public class SubclassOfSubclassOfSingleTableInheritance extends SubclassOfSingleTableInheritance {
private String otherOtherName;
}
@Entity
@DiscriminatorValue("base")
@DiscriminatorOptions(force = true, insert = false)
class Base {
@Id
@GeneratedValue
private int id;
}
@Entity
class Jump extends Base {
}
@Entity
@DiscriminatorColumn(discriminatorType = DiscriminatorType.INTEGER)
@DiscriminatorFormula("case when zik_type is null then 0 else zik_type end")
@DiscriminatorOptions(force = true, insert = false)
class Fruit {
@Id
private int id;
}
@Entity
class Apple extends Fruit {
}
}

View File

@ -1,250 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.entity;
import java.io.Serializable;
import java.sql.Blob;
import java.sql.Clob;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;
import org.junit.Test;
import org.hibernate.metamodel.binding.AttributeBinding;
import org.hibernate.metamodel.binding.EntityBinding;
import org.hibernate.metamodel.binding.HibernateTypeDescriptor;
import org.hibernate.type.BlobType;
import org.hibernate.type.CharacterArrayClobType;
import org.hibernate.type.ClobType;
import org.hibernate.type.MaterializedBlobType;
import org.hibernate.type.MaterializedClobType;
import org.hibernate.type.PrimitiveCharacterArrayClobType;
import org.hibernate.type.SerializableToBlobType;
import org.hibernate.type.StandardBasicTypes;
import org.hibernate.type.WrappedMaterializedBlobType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* @author Strong Liu
*/
public class LobBindingTests extends BaseAnnotationBindingTestCase {
@Entity
class Item {
@Id
long id;
@Lob
Clob clob;
@Lob
Blob blob;
@Lob
String str;
@Lob
Character[] characters;
@Lob
char[] chars;
@Lob
Byte[] bytes;
@Lob
byte[] bytes2;
@Lob
Thing serializable;
String noLob;
}
class Thing implements Serializable {
int size;
}
private HibernateTypeDescriptor getTypeDescriptor(String attributeName) {
EntityBinding binding = getEntityBinding( Item.class );
AttributeBinding attributeBinding = binding.locateAttributeBinding( attributeName );
return attributeBinding.getHibernateTypeDescriptor();
}
private class ExpectedValue {
String explicitTypeName;
String javaTypeName;
boolean isResolvedTypeMappingNull;
Class resolvedTypeMappingClass;
boolean isTypeParametersNull;
boolean isTypeParametersEmpty;
private ExpectedValue(String explicitTypeName,
String javaTypeName,
boolean resolvedTypeMappingNull,
Class resolvedTypeMappingClass,
boolean typeParametersNull,
boolean typeParametersEmpty
) {
this.explicitTypeName = explicitTypeName;
this.isResolvedTypeMappingNull = resolvedTypeMappingNull;
this.isTypeParametersEmpty = typeParametersEmpty;
this.isTypeParametersNull = typeParametersNull;
this.javaTypeName = javaTypeName;
this.resolvedTypeMappingClass = resolvedTypeMappingClass;
}
}
private void checkHibernateTypeDescriptor(ExpectedValue expectedValue, String attributeName) {
HibernateTypeDescriptor descriptor = getTypeDescriptor( attributeName );
assertEquals( expectedValue.explicitTypeName, descriptor.getExplicitTypeName() );
assertEquals( expectedValue.javaTypeName, descriptor.getJavaTypeName() );
assertEquals( expectedValue.isResolvedTypeMappingNull, descriptor.getResolvedTypeMapping() == null );
assertEquals( expectedValue.resolvedTypeMappingClass, descriptor.getResolvedTypeMapping().getClass() );
assertEquals( expectedValue.isTypeParametersNull, descriptor.getTypeParameters() == null );
assertEquals( expectedValue.isTypeParametersEmpty, descriptor.getTypeParameters().isEmpty() );
}
@Test
@Resources(annotatedClasses = Item.class)
public void testClobWithLobAnnotation() {
ExpectedValue expectedValue = new ExpectedValue(
"clob",
Clob.class.getName(),
false,
ClobType.class,
false,
true
);
checkHibernateTypeDescriptor( expectedValue, "clob" );
}
@Test
@Resources(annotatedClasses = Item.class)
public void testBlobWithLobAnnotation() {
ExpectedValue expectedValue = new ExpectedValue(
"blob",
Blob.class.getName(),
false,
BlobType.class,
false,
true
);
checkHibernateTypeDescriptor( expectedValue, "blob" );
}
@Test
@Resources(annotatedClasses = Item.class)
public void testStringWithLobAnnotation() {
ExpectedValue expectedValue = new ExpectedValue(
"materialized_clob",
String.class.getName(),
false,
MaterializedClobType.class,
false,
true
);
checkHibernateTypeDescriptor( expectedValue, "str" );
}
@Test
@Resources(annotatedClasses = Item.class)
public void testCharacterArrayWithLobAnnotation() {
ExpectedValue expectedValue = new ExpectedValue(
CharacterArrayClobType.class.getName(),
Character[].class.getName(),
false,
CharacterArrayClobType.class,
false,
true
);
checkHibernateTypeDescriptor( expectedValue, "characters" );
}
@Test
@Resources(annotatedClasses = Item.class)
public void testPrimitiveCharacterArrayWithLobAnnotation() {
ExpectedValue expectedValue = new ExpectedValue(
PrimitiveCharacterArrayClobType.class.getName(),
char[].class.getName(),
false,
PrimitiveCharacterArrayClobType.class,
false,
true
);
checkHibernateTypeDescriptor( expectedValue, "chars" );
}
@Test
@Resources(annotatedClasses = Item.class)
public void testByteArrayWithLobAnnotation() {
ExpectedValue expectedValue = new ExpectedValue(
WrappedMaterializedBlobType.class.getName(),
Byte[].class.getName(),
false,
WrappedMaterializedBlobType.class,
false,
true
);
checkHibernateTypeDescriptor( expectedValue, "bytes" );
}
@Test
@Resources(annotatedClasses = Item.class)
public void testPrimitiveByteArrayWithLobAnnotation() {
ExpectedValue expectedValue = new ExpectedValue(
StandardBasicTypes.MATERIALIZED_BLOB.getName(),
byte[].class.getName(),
false,
MaterializedBlobType.class,
false,
true
);
checkHibernateTypeDescriptor( expectedValue, "bytes2" );
}
@Test
@Resources(annotatedClasses = Item.class)
public void testSerializableWithLobAnnotation() {
ExpectedValue expectedValue = new ExpectedValue(
SerializableToBlobType.class.getName(),
Thing.class.getName(),
false,
SerializableToBlobType.class,
false,
false
);
checkHibernateTypeDescriptor( expectedValue, "serializable" );
assertTrue(
getTypeDescriptor( "serializable" ).getTypeParameters()
.get( SerializableToBlobType.CLASS_NAME )
.equals( Thing.class.getName() )
);
}
@Test
@Resources(annotatedClasses = Item.class)
public void testNoLobAttribute() {
assertNull( getTypeDescriptor( "noLob" ).getExplicitTypeName() );
assertTrue( getTypeDescriptor( "noLob" ).getTypeParameters().isEmpty() );
}
}

View File

@ -1,118 +0,0 @@
/*
* 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.metamodel.source.annotations.entity;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import org.junit.Test;
import org.hibernate.metamodel.binding.EntityBinding;
import org.hibernate.metamodel.binding.SingularAttributeBinding;
import org.hibernate.metamodel.domain.NonEntity;
import org.hibernate.metamodel.relational.Column;
import org.hibernate.testing.FailureExpected;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertTrue;
/**
* Tests for {@link javax.persistence.MappedSuperclass} {@link javax.persistence.AttributeOverrides}
* and {@link javax.persistence.AttributeOverride}.
*
* @author Hardy Ferentschik
*/
@FailureExpected(jiraKey = "HHH-6447", message = "Work in progress")
public class MappedSuperclassTest extends BaseAnnotationBindingTestCase {
@Test
// @Resources(annotatedClasses = { MyMappedSuperClass.class, MyEntity.class, MyMappedSuperClassBase.class })
public void testSimpleAttributeOverrideInMappedSuperclass() {
EntityBinding binding = getEntityBinding( MyEntity.class );
SingularAttributeBinding nameBinding = (SingularAttributeBinding) binding.locateAttributeBinding( "name" );
assertNotNull( "the name attribute should be bound to MyEntity", nameBinding );
Column column = (Column) nameBinding.getValue();
assertEquals( "Wrong column name", "MY_NAME", column.getColumnName().toString() );
}
@Test
// @Resources(annotatedClasses = { MyMappedSuperClass.class, MyEntity.class, MyMappedSuperClassBase.class })
public void testLastAttributeOverrideWins() {
EntityBinding binding = getEntityBinding( MyEntity.class );
SingularAttributeBinding fooBinding = (SingularAttributeBinding) binding.locateAttributeBinding( "foo" );
assertNotNull( "the foo attribute should be bound to MyEntity", fooBinding );
Column column = (Column) fooBinding.getValue();
assertEquals( "Wrong column name", "MY_FOO", column.getColumnName().toString() );
}
@Test
// @Resources(annotatedClasses = { SubclassOfNoEntity.class, NoEntity.class })
public void testNonEntityBaseClass() {
EntityBinding binding = getEntityBinding( SubclassOfNoEntity.class );
assertEquals( "Wrong entity name", SubclassOfNoEntity.class.getName(), binding.getEntity().getName() );
assertEquals( "Wrong entity name", NoEntity.class.getName(), binding.getEntity().getSuperType().getName() );
assertTrue( binding.getEntity().getSuperType() instanceof NonEntity );
}
@MappedSuperclass
class MyMappedSuperClassBase {
@Id
private int id;
String foo;
}
@MappedSuperclass
@AttributeOverride(name = "foo", column = @javax.persistence.Column(name = "SUPER_FOO"))
class MyMappedSuperClass extends MyMappedSuperClassBase {
String name;
}
@Entity
@AttributeOverrides( {
@AttributeOverride(name = "name", column = @javax.persistence.Column(name = "MY_NAME")),
@AttributeOverride(name = "foo", column = @javax.persistence.Column(name = "MY_FOO"))
})
class MyEntity extends MyMappedSuperClass {
private Long count;
}
class NoEntity {
String name;
int age;
}
@Entity
class SubclassOfNoEntity extends NoEntity {
@Id
private int id;
}
}

View File

@ -1,96 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.entity;
import javax.persistence.Embeddable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.MapsId;
import javax.persistence.OneToMany;
import org.junit.Test;
import org.hibernate.metamodel.MetadataSources;
import org.hibernate.metamodel.source.MappingException;
import org.hibernate.service.ServiceRegistryBuilder;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
import static junit.framework.Assert.fail;
/**
* @author Hardy Ferentschik
*/
public class MapsIdTest extends BaseAnnotationBindingTestCase {
@Entity
public class Employee {
@Id
long empId;
String name;
}
@Embeddable
public class DependentId {
String name;
long empid; // corresponds to PK type of Employee
}
@Entity
public class Dependent {
@Id
// should be @EmbeddedId, but embedded id are not working atm
DependentId id;
@MapsId("empid")
@OneToMany
Employee emp; // maps the empid attribute of embedded id @ManyToOne Employee emp;
}
@Test
@Resources(annotatedClasses = DependentId.class)
public void testMapsIsOnOneToManyThrowsException() {
try {
sources = new MetadataSources( new ServiceRegistryBuilder().buildServiceRegistry() );
sources.addAnnotatedClass( DependentId.class );
sources.addAnnotatedClass( Dependent.class );
sources.addAnnotatedClass( Employee.class );
sources.buildMetadata();
fail();
}
catch ( MappingException e ) {
assertTrue(
e.getMessage()
.startsWith( "@MapsId can only be specified on a many-to-one or one-to-one associations" )
);
assertEquals(
"Wrong error origin",
"org.hibernate.metamodel.source.annotations.entity.MapsIdTest$Dependent",
e.getOrigin().getName()
);
}
}
}

View File

@ -1,108 +0,0 @@
/*
* 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.metamodel.source.annotations.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.junit.Test;
import org.hibernate.annotations.Proxy;
import org.hibernate.metamodel.binding.EntityBinding;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
/**
* Tests for {@code o.h.a.Cache}.
*
* @author Hardy Ferentschik
*/
public class ProxyBindingTest extends BaseAnnotationBindingTestCase {
@Test
@Resources(annotatedClasses = ProxiedEntity.class)
public void testProxyNoAttributes() {
EntityBinding binding = getEntityBinding( ProxiedEntity.class );
assertTrue( "Wrong laziness", binding.isLazy() );
assertEquals( "Wrong proxy interface", ProxiedEntity.class, binding.getProxyInterfaceType().getValue() );
}
@Test
@Resources(annotatedClasses = NoProxyEntity.class)
public void testNoProxy() {
EntityBinding binding = getEntityBinding( NoProxyEntity.class );
assertTrue( "Wrong laziness", binding.isLazy() );
assertEquals( "Wrong proxy interface", NoProxyEntity.class, binding.getProxyInterfaceType().getValue() );
}
@Test
@Resources(annotatedClasses = ProxyDisabledEntity.class)
public void testProxyDisabled() {
EntityBinding binding = getEntityBinding( ProxyDisabledEntity.class );
assertFalse( "Wrong laziness", binding.isLazy() );
assertEquals( "Wrong proxy interface", null, binding.getProxyInterfaceType() );
}
@Test
@Resources(annotatedClasses = ProxyInterfaceEntity.class)
public void testProxyInterface() {
EntityBinding binding = getEntityBinding( ProxyInterfaceEntity.class );
assertTrue( "Wrong laziness", binding.isLazy() );
assertEquals(
"Wrong proxy interface",
"org.hibernate.metamodel.source.annotations.entity.ProxyBindingTest$ProxyInterfaceEntity",
binding.getProxyInterfaceType().getValue().getName()
);
}
@Entity
class NoProxyEntity {
@Id
private int id;
}
@Entity
@Proxy
class ProxiedEntity {
@Id
private int id;
}
@Entity
@Proxy(lazy = false)
class ProxyDisabledEntity {
@Id
private int id;
}
@Entity
@Proxy(proxyClass = ProxyInterfaceEntity.class)
class ProxyInterfaceEntity {
@Id
private int id;
}
}

View File

@ -1,94 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.junit.Test;
import org.hibernate.metamodel.binding.EntityBinding;
import org.hibernate.metamodel.relational.Identifier;
import static org.junit.Assert.assertEquals;
/**
* @author Strong Liu
*/
public class QuotedIdentifierTest extends BaseAnnotationBindingTestCase {
private final String ormPath = "org/hibernate/metamodel/source/annotations/xml/orm-quote-identifier.xml";
@Test
@Resources(annotatedClasses = { Item.class, Item2.class, Item3.class, Item4.class }, ormXmlPath = ormPath)
public void testDelimitedIdentifiers() {
EntityBinding item = getEntityBinding( Item.class );
assertIdentifierEquals( "`QuotedIdentifierTest$Item`", item );
item = getEntityBinding( Item2.class );
assertIdentifierEquals( "`TABLE_ITEM2`", item );
item = getEntityBinding( Item3.class );
assertIdentifierEquals( "`TABLE_ITEM3`", item );
// TODO: not sure about this -- revisit after metamodel merge
// item = getEntityBinding( Item4.class );
// assertIdentifierEquals( "`TABLE_ITEM4`", item );
}
//todo check if the column names are quoted
private void assertIdentifierEquals(String expected, EntityBinding realValue) {
org.hibernate.metamodel.relational.Table table = (org.hibernate.metamodel.relational.Table) realValue.getPrimaryTable();
assertEquals( Identifier.toIdentifier( expected ), table.getTableName() );
}
@Entity
private static class Item {
@Id
Long id;
}
@Entity
@Table(name = "TABLE_ITEM2")
private static class Item2 {
@Id
Long id;
}
@Entity
@Table(name = "`TABLE_ITEM3`")
private static class Item3 {
@Id
Long id;
}
@Entity
@Table(name = "\"TABLE_ITEM4\"")
private static class Item4 {
@Id
Long id;
}
}

View File

@ -1,46 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.entity;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.persistence.SharedCacheMode;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Allows to specify the annotated classes and xml configuration files for this test
*
* @author Hardy Ferentschik
*/
@Target(METHOD)
@Retention(RUNTIME)
public @interface Resources {
Class<?>[] annotatedClasses() default { };
String ormXmlPath() default "";
SharedCacheMode cacheMode() default SharedCacheMode.ENABLE_SELECTIVE;
}

View File

@ -1,70 +0,0 @@
/*
* 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.metamodel.source.annotations.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.junit.Test;
import org.hibernate.annotations.RowId;
import org.hibernate.metamodel.binding.EntityBinding;
import static junit.framework.Assert.assertEquals;
/**
* Tests for {@code o.h.a.RowId}.
*
* @author Hardy Ferentschik
*/
public class RowIdBindingTests extends BaseAnnotationBindingTestCase {
@Test
@Resources(annotatedClasses = NoRowIdEntity.class)
public void testNoRowId() {
EntityBinding binding = getEntityBinding( NoRowIdEntity.class );
assertEquals( "Wrong row id", null, binding.getRowId() );
}
@Test
@Resources(annotatedClasses = RowIdEntity.class)
public void testRowId() {
EntityBinding binding = getEntityBinding( RowIdEntity.class );
assertEquals( "Wrong row id", "rowid", binding.getRowId() );
}
@Entity
class NoRowIdEntity {
@Id
private int id;
}
@Entity
@RowId("rowid")
class RowIdEntity {
@Id
private int id;
}
}

View File

@ -1,86 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.entity;
import java.util.Iterator;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.SecondaryTable;
import org.junit.Test;
import org.hibernate.AssertionFailure;
import org.hibernate.metamodel.binding.EntityBinding;
import org.hibernate.metamodel.relational.SimpleValue;
import org.hibernate.metamodel.relational.Table;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
import static junit.framework.Assert.fail;
/**
* @author Hardy Ferentschik
*/
public class SecondaryTableTest extends BaseAnnotationBindingTestCase {
@Entity
@SecondaryTable(name = "SECOND_TABLE")
class EntityWithSecondaryTable {
@Id
private long id;
@Column(table = "SECOND_TABLE")
private String name;
}
@Test
@Resources(annotatedClasses = EntityWithSecondaryTable.class)
public void testSecondaryTableExists() {
EntityBinding binding = getEntityBinding( EntityWithSecondaryTable.class );
Table table = (Table) binding.locateTable( "SECOND_TABLE" );
assertEquals( "The secondary table should exist", "SECOND_TABLE", table.getTableName().getName() );
Iterator<SimpleValue> valueIterator = table.values().iterator();
assertTrue( valueIterator.hasNext() );
org.hibernate.metamodel.relational.Column column = (org.hibernate.metamodel.relational.Column) valueIterator.next();
assertEquals( "Wrong column name", "name", column.getColumnName().getName() );
assertFalse( valueIterator.hasNext() );
}
@Test
@Resources(annotatedClasses = EntityWithSecondaryTable.class)
public void testRetrievingUnknownTable() {
EntityBinding binding = getEntityBinding( EntityWithSecondaryTable.class );
try {
binding.locateTable( "FOO" );
fail();
}
catch ( AssertionFailure e ) {
assertTrue( e.getMessage().startsWith( "Unable to find table" ) );
}
}
}

View File

@ -1,75 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.entity;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.junit.Test;
import org.hibernate.annotations.Synchronize;
import org.hibernate.metamodel.binding.EntityBinding;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
/**
* Tests for {@code o.h.a.Synchronize}.
*
* @author Hardy Ferentschik
*/
public class SynchronizeBindingTest extends BaseAnnotationBindingTestCase {
@Test
@Resources(annotatedClasses = TestEntityWithSynchronizeAnnotation.class)
public void testSynchronizeAnnotation() {
EntityBinding binding = getEntityBinding( TestEntityWithSynchronizeAnnotation.class );
Set<String> synchronizedTableNames = binding.getSynchronizedTableNames();
assertEquals( "Wrong number of synced tables", 2, synchronizedTableNames.size() );
assertTrue( "Table name missing", synchronizedTableNames.contains( "Foo" ) );
assertTrue( "Table name missing", synchronizedTableNames.contains( "Bar" ) );
}
@Test
@Resources(annotatedClasses = TestEntity.class)
public void testNoSynchronizeAnnotation() {
EntityBinding binding = getEntityBinding( TestEntity.class );
assertTrue( "There should be no cache binding", binding.getSynchronizedTableNames().size() == 0 );
}
@Entity
class TestEntity {
@Id
private int id;
}
@Entity
@Synchronize( { "Foo", "Bar" })
class TestEntityWithSynchronizeAnnotation {
@Id
private int id;
}
}

View File

@ -1,141 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.Table;
import org.junit.Test;
import org.hibernate.metamodel.binding.EntityBinding;
import org.hibernate.metamodel.binding.InheritanceType;
import static junit.framework.Assert.assertEquals;
/**
* @author Hardy Ferentschik
*/
public class TableNameTest extends BaseAnnotationBindingTestCase {
@Entity
class A {
@Id
@GeneratedValue
private int id;
}
@Entity
class B extends A {
}
@Test
@Resources(annotatedClasses = { A.class, B.class })
public void testSingleInheritanceDefaultTableName() {
EntityBinding binding = getEntityBinding( A.class );
assertEquals( "wrong inheritance type", InheritanceType.SINGLE_TABLE, binding.getHierarchyDetails().getInheritanceType() );
assertEquals(
"wrong table name",
"TableNameTest$A",
( (org.hibernate.metamodel.relational.Table) binding.getPrimaryTable() ).getTableName().getName()
);
binding = getEntityBinding( B.class );
assertEquals( "wrong inheritance type", InheritanceType.SINGLE_TABLE, binding.getHierarchyDetails().getInheritanceType() );
assertEquals(
"wrong table name",
"TableNameTest$A",
( (org.hibernate.metamodel.relational.Table) binding.getPrimaryTable() ).getTableName().getName()
);
}
@Entity
@Inheritance(strategy = javax.persistence.InheritanceType.JOINED)
@Table(name = "FOO")
class JoinedA {
@Id
@GeneratedValue
private int id;
}
@Entity
class JoinedB extends JoinedA {
}
@Test
@Resources(annotatedClasses = { JoinedA.class, JoinedB.class })
public void testJoinedSubclassDefaultTableName() {
EntityBinding binding = getEntityBinding( JoinedA.class );
assertEquals( "wrong inheritance type", InheritanceType.JOINED, binding.getHierarchyDetails().getInheritanceType() );
assertEquals(
"wrong table name",
"FOO",
( (org.hibernate.metamodel.relational.Table) binding.getPrimaryTable() ).getTableName().getName()
);
binding = getEntityBinding( JoinedB.class );
assertEquals( "wrong inheritance type", InheritanceType.JOINED, binding.getHierarchyDetails().getInheritanceType() );
assertEquals(
"wrong table name",
"TableNameTest$JoinedB",
( (org.hibernate.metamodel.relational.Table) binding.getPrimaryTable() ).getTableName().getName()
);
}
@Entity
@Inheritance(strategy = javax.persistence.InheritanceType.TABLE_PER_CLASS)
class TablePerClassA {
@Id
@GeneratedValue
private int id;
}
@Entity
class TablePerClassB extends TablePerClassA {
}
@Test
@Resources(annotatedClasses = { TablePerClassA.class, TablePerClassB.class })
public void testTablePerClassDefaultTableName() {
EntityBinding binding = getEntityBinding( TablePerClassA.class );
assertEquals( "wrong inheritance type", InheritanceType.TABLE_PER_CLASS, binding.getHierarchyDetails().getInheritanceType() );
assertEquals(
"wrong table name",
"TableNameTest$TablePerClassA",
( (org.hibernate.metamodel.relational.Table) binding.getPrimaryTable() ).getTableName().getName()
);
binding = getEntityBinding( TablePerClassB.class );
assertEquals( "wrong inheritance type", InheritanceType.TABLE_PER_CLASS, binding.getHierarchyDetails().getInheritanceType() );
assertEquals(
"wrong table name",
"TableNameTest$TablePerClassB",
( (org.hibernate.metamodel.relational.Table) binding.getPrimaryTable() ).getTableName().getName()
);
}
}

View File

@ -1,104 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.entity;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.junit.Test;
import org.hibernate.AnnotationException;
import org.hibernate.metamodel.binding.AttributeBinding;
import org.hibernate.metamodel.binding.EntityBinding;
import org.hibernate.metamodel.binding.HibernateTypeDescriptor;
import org.hibernate.type.TimestampType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* @author Strong Liu
*/
public class TemporalBindingTest extends BaseAnnotationBindingTestCase {
@Entity
class Item1 {
@Id
long id;
Date date;
}
@Test(expected = AnnotationException.class)
@Resources(annotatedClasses = TemporalBindingTest.Item1.class)
public void testNoTemporalAnnotationOnTemporalTypeAttribute() {
getEntityBinding( Item1.class );
}
@Entity
class Item2 {
@Id
long id;
@Temporal(TemporalType.TIMESTAMP)
Date date;
}
@Test
@Resources(annotatedClasses = TemporalBindingTest.Item2.class)
public void testTemporalTypeAttribute() {
EntityBinding binding = getEntityBinding( Item2.class );
AttributeBinding attributeBinding = binding.locateAttributeBinding( "date" );
HibernateTypeDescriptor descriptor = attributeBinding.getHibernateTypeDescriptor();
assertEquals( "timestamp", descriptor.getExplicitTypeName() );
assertEquals( Date.class.getName(), descriptor.getJavaTypeName() );
assertNotNull( descriptor.getResolvedTypeMapping() );
assertEquals( TimestampType.class, descriptor.getResolvedTypeMapping().getClass() );
assertNotNull( descriptor.getTypeParameters() );
assertTrue( descriptor.getTypeParameters().isEmpty() );
}
@Entity
class Item3 {
@Id
@Temporal(TemporalType.TIMESTAMP)
Date date;
}
@Test
@Resources(annotatedClasses = TemporalBindingTest.Item3.class)
public void testTemporalTypeAsId() {
EntityBinding binding = getEntityBinding( Item3.class );
AttributeBinding attributeBinding = binding.locateAttributeBinding( "date" );
HibernateTypeDescriptor descriptor = attributeBinding.getHibernateTypeDescriptor();
assertEquals( "timestamp", descriptor.getExplicitTypeName() );
assertEquals( Date.class.getName(), descriptor.getJavaTypeName() );
assertNotNull( descriptor.getResolvedTypeMapping() );
assertEquals( TimestampType.class, descriptor.getResolvedTypeMapping().getClass() );
assertNotNull( descriptor.getTypeParameters() );
assertTrue( descriptor.getTypeParameters().isEmpty() );
}
}

View File

@ -1,79 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import org.junit.Test;
import org.hibernate.metamodel.binding.EntityBinding;
import org.hibernate.metamodel.relational.Column;
import org.hibernate.metamodel.relational.TableSpecification;
import org.hibernate.metamodel.relational.UniqueKey;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertTrue;
/**
* test for {@link javax.persistence.UniqueConstraint}
*
* @author Strong Liu
*/
public class UniqueConstraintBindingTest extends BaseAnnotationBindingTestCase {
@Test
@Resources(annotatedClasses = TableWithUniqueConstraint.class)
public void testTableUniqueConstraints() {
EntityBinding binding = getEntityBinding( TableWithUniqueConstraint.class );
TableSpecification table = binding.getPrimaryTable();
Iterable<UniqueKey> uniqueKeyIterable = table.getUniqueKeys();
assertNotNull( uniqueKeyIterable );
int i = 0;
for ( UniqueKey key : uniqueKeyIterable ) {
i++;
assertEquals( "u1", key.getName() );
assertTrue( table == key.getTable() );
assertNotNull( key.getColumns() );
int j = 0;
for ( Column column : key.getColumns() ) {
j++;
}
assertEquals( "There should be two columns in the unique constraint", 2, j );
}
assertEquals( "There should only be one unique constraint", 1, i );
}
@Entity
@Table(uniqueConstraints = { @UniqueConstraint(name = "u1", columnNames = { "name", "age" }) })
class TableWithUniqueConstraint {
@Id
int id;
String name;
int age;
}
}

View File

@ -1,32 +0,0 @@
package org.hibernate.metamodel.source.annotations.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.junit.Test;
import org.hibernate.annotations.Where;
import org.hibernate.metamodel.binding.EntityBinding;
import static junit.framework.Assert.assertEquals;
/**
* @author Hardy Ferentschik
*/
public class WhereClauseTest extends BaseAnnotationBindingTestCase {
@Test
@Resources(annotatedClasses = Foo.class)
public void testWhereFilter() {
EntityBinding binding = getEntityBinding( Foo.class );
assertEquals( "Wrong where filter", "1=1", binding.getWhereFilter() );
}
@Entity
@Where(clause = "1=1")
class Foo {
@Id
private long id;
}
}

View File

@ -1,146 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.global;
import java.util.Iterator;
import org.jboss.jandex.Index;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.hibernate.MappingException;
import org.hibernate.annotations.FetchMode;
import org.hibernate.annotations.FetchProfile;
import org.hibernate.annotations.FetchProfiles;
import org.hibernate.metamodel.MetadataSources;
import org.hibernate.metamodel.source.annotations.AnnotationBindingContextImpl;
import org.hibernate.metamodel.source.annotations.JandexHelper;
import org.hibernate.metamodel.source.internal.MetadataImpl;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.service.classloading.spi.ClassLoaderService;
import org.hibernate.service.internal.StandardServiceRegistryImpl;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import static junit.framework.Assert.fail;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @author Hardy Ferentschik
*/
public class FetchProfileBinderTest extends BaseUnitTestCase {
private StandardServiceRegistryImpl serviceRegistry;
private ClassLoaderService service;
private MetadataImpl meta;
@Before
public void setUp() {
serviceRegistry = (StandardServiceRegistryImpl) new ServiceRegistryBuilder().buildServiceRegistry();
service = serviceRegistry.getService( ClassLoaderService.class );
meta = (MetadataImpl) new MetadataSources( serviceRegistry ).buildMetadata();
}
@After
public void tearDown() {
serviceRegistry.destroy();
}
@Test
public void testSingleFetchProfile() {
@FetchProfile(name = "foo", fetchOverrides = {
@FetchProfile.FetchOverride(entity = Foo.class, association = "bar", mode = FetchMode.JOIN)
})
class Foo {
}
Index index = JandexHelper.indexForClass( service, Foo.class );
FetchProfileBinder.bind( new AnnotationBindingContextImpl( meta, index ) );
Iterator<org.hibernate.metamodel.binding.FetchProfile> mappedFetchProfiles = meta.getFetchProfiles().iterator();
assertTrue( mappedFetchProfiles.hasNext() );
org.hibernate.metamodel.binding.FetchProfile profile = mappedFetchProfiles.next();
assertEquals( "Wrong fetch profile name", "foo", profile.getName() );
org.hibernate.metamodel.binding.FetchProfile.Fetch fetch = profile.getFetches().iterator().next();
assertEquals( "Wrong association name", "bar", fetch.getAssociation() );
assertEquals( "Wrong association type", Foo.class.getName(), fetch.getEntity() );
}
@Test
public void testFetchProfiles() {
Index index = JandexHelper.indexForClass( service, FooBar.class );
FetchProfileBinder.bind( new AnnotationBindingContextImpl( meta, index ) );
Iterator<org.hibernate.metamodel.binding.FetchProfile> mappedFetchProfiles = meta.getFetchProfiles().iterator();
assertTrue( mappedFetchProfiles.hasNext() );
org.hibernate.metamodel.binding.FetchProfile profile = mappedFetchProfiles.next();
assertProfiles( profile );
assertTrue( mappedFetchProfiles.hasNext() );
profile = mappedFetchProfiles.next();
assertProfiles( profile );
}
private void assertProfiles(org.hibernate.metamodel.binding.FetchProfile profile) {
if ( profile.getName().equals( "foobar" ) ) {
org.hibernate.metamodel.binding.FetchProfile.Fetch fetch = profile.getFetches().iterator().next();
assertEquals( "Wrong association name", "foobar", fetch.getAssociation() );
assertEquals( "Wrong association type", FooBar.class.getName(), fetch.getEntity() );
}
else if ( profile.getName().equals( "fubar" ) ) {
org.hibernate.metamodel.binding.FetchProfile.Fetch fetch = profile.getFetches().iterator().next();
assertEquals( "Wrong association name", "fubar", fetch.getAssociation() );
assertEquals( "Wrong association type", FooBar.class.getName(), fetch.getEntity() );
}
else {
fail( "Wrong fetch name:" + profile.getName() );
}
}
@Test(expected = MappingException.class)
public void testNonJoinFetchThrowsException() {
@FetchProfile(name = "foo", fetchOverrides = {
@FetchProfile.FetchOverride(entity = Foo.class, association = "bar", mode = FetchMode.SELECT)
})
class Foo {
}
Index index = JandexHelper.indexForClass( service, Foo.class );
FetchProfileBinder.bind( new AnnotationBindingContextImpl( meta, index ) );
}
@FetchProfiles( {
@FetchProfile(name = "foobar", fetchOverrides = {
@FetchProfile.FetchOverride(entity = FooBar.class, association = "foobar", mode = FetchMode.JOIN)
}),
@FetchProfile(name = "fubar", fetchOverrides = {
@FetchProfile.FetchOverride(entity = FooBar.class, association = "fubar", mode = FetchMode.JOIN)
})
})
class FooBar {
}
}

View File

@ -1,98 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.global;
import javax.persistence.NamedNativeQuery;
import org.jboss.jandex.Index;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.hibernate.cfg.NotYetImplementedException;
import org.hibernate.engine.query.spi.sql.NativeSQLQueryReturn;
import org.hibernate.engine.query.spi.sql.NativeSQLQueryRootReturn;
import org.hibernate.engine.spi.NamedSQLQueryDefinition;
import org.hibernate.metamodel.MetadataSources;
import org.hibernate.metamodel.source.annotations.AnnotationBindingContextImpl;
import org.hibernate.metamodel.source.annotations.JandexHelper;
import org.hibernate.metamodel.source.internal.MetadataImpl;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.service.classloading.spi.ClassLoaderService;
import org.hibernate.service.internal.StandardServiceRegistryImpl;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertTrue;
/**
* @author Hardy Ferentschik
*/
public class QueryBinderTest extends BaseUnitTestCase {
private StandardServiceRegistryImpl serviceRegistry;
private ClassLoaderService service;
private MetadataImpl meta;
@Before
public void setUp() {
serviceRegistry = (StandardServiceRegistryImpl) new ServiceRegistryBuilder().buildServiceRegistry();
service = serviceRegistry.getService( ClassLoaderService.class );
meta = (MetadataImpl) new MetadataSources( serviceRegistry ).buildMetadata();
}
@After
public void tearDown() {
serviceRegistry.destroy();
}
@Test(expected = NotYetImplementedException.class)
public void testNoResultClass() {
@NamedNativeQuery(name = "fubar", query = "SELECT * FROM FOO")
class Foo {
}
Index index = JandexHelper.indexForClass( service, Foo.class );
QueryBinder.bind( new AnnotationBindingContextImpl( meta, index ) );
}
@Test
public void testResultClass() {
@NamedNativeQuery(name = "fubar", query = "SELECT * FROM FOO", resultClass = Foo.class)
class Foo {
}
Index index = JandexHelper.indexForClass( service, Foo.class );
QueryBinder.bind( new AnnotationBindingContextImpl( meta, index ) );
NamedSQLQueryDefinition namedQuery = meta.getNamedNativeQuery( "fubar" );
assertNotNull( namedQuery );
NativeSQLQueryReturn queryReturns[] = namedQuery.getQueryReturns();
assertTrue( "Wrong number of returns", queryReturns.length == 1 );
assertTrue( "Wrong query return type", queryReturns[0] instanceof NativeSQLQueryRootReturn );
NativeSQLQueryRootReturn rootReturn = (NativeSQLQueryRootReturn) queryReturns[0];
assertEquals( "Wrong result class", Foo.class.getName(), rootReturn.getReturnEntityName() );
}
}

View File

@ -1,80 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.util;
import java.util.Set;
import javax.persistence.AccessType;
import org.jboss.jandex.Index;
import org.junit.After;
import org.junit.Before;
import org.hibernate.metamodel.MetadataSources;
import org.hibernate.metamodel.source.annotations.AnnotationBindingContext;
import org.hibernate.metamodel.source.annotations.AnnotationBindingContextImpl;
import org.hibernate.metamodel.source.annotations.EntityHierarchyBuilder;
import org.hibernate.metamodel.source.annotations.JandexHelper;
import org.hibernate.metamodel.source.annotations.entity.EmbeddableHierarchy;
import org.hibernate.metamodel.source.binder.EntityHierarchy;
import org.hibernate.metamodel.source.internal.MetadataImpl;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.service.classloading.spi.ClassLoaderService;
import org.hibernate.testing.junit4.BaseUnitTestCase;
/**
* @author Hardy Ferentschik
*/
public abstract class BaseAnnotationIndexTestCase extends BaseUnitTestCase {
private MetadataImpl meta;
@Before
public void setUp() {
MetadataSources sources = new MetadataSources( new ServiceRegistryBuilder().buildServiceRegistry() );
meta = (MetadataImpl) sources.buildMetadata();
}
@After
public void tearDown() {
}
public Set<EntityHierarchy> createEntityHierarchies(Class<?>... clazz) {
Index index = JandexHelper.indexForClass(
meta.getServiceRegistry().getService( ClassLoaderService.class ),
clazz
);
AnnotationBindingContext context = new AnnotationBindingContextImpl( meta, index );
return EntityHierarchyBuilder.createEntityHierarchies( context );
}
public EmbeddableHierarchy createEmbeddableHierarchy(AccessType accessType, Class<?>... configuredClasses) {
Index index = JandexHelper.indexForClass(
meta.getServiceRegistry().getService( ClassLoaderService.class ),
configuredClasses
);
AnnotationBindingContext context = new AnnotationBindingContextImpl( meta, index );
return EmbeddableHierarchy.createEmbeddableHierarchy( configuredClasses[0], "", accessType, context );
}
}

View File

@ -1,112 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.util;
import java.util.Iterator;
import javax.persistence.AccessType;
import javax.persistence.Embeddable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.junit.Ignore;
import org.junit.Test;
import org.hibernate.AssertionFailure;
import org.hibernate.metamodel.source.annotations.entity.EmbeddableClass;
import org.hibernate.metamodel.source.annotations.entity.EmbeddableHierarchy;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import static org.junit.Assert.assertFalse;
/**
* @author Hardy Ferentschik
*/
@Ignore("fails on openjdk")
public class EmbeddableHierarchyTest extends BaseAnnotationIndexTestCase {
@Test
@Ignore("HHH-6606 ignore for now")
public void testEmbeddableHierarchy() {
@Embeddable
class A {
String foo;
}
class B extends A {
}
@Embeddable
class C extends B {
String bar;
}
EmbeddableHierarchy hierarchy = createEmbeddableHierarchy(
AccessType.FIELD,
C.class,
A.class,
B.class
);
Iterator<EmbeddableClass> iter = hierarchy.iterator();
ClassInfo info = iter.next().getClassInfo();
assertEquals( "wrong class", DotName.createSimple( A.class.getName() ), info.name() );
info = iter.next().getClassInfo();
assertEquals( "wrong class", DotName.createSimple( B.class.getName() ), info.name() );
info = iter.next().getClassInfo();
assertEquals( "wrong class", DotName.createSimple( C.class.getName() ), info.name() );
assertFalse( iter.hasNext() );
assertNotNull( hierarchy );
}
@Test(expected = AssertionFailure.class)
public void testEmbeddableHierarchyWithNotAnnotatedEntity() {
class NonAnnotatedEmbeddable {
}
createEmbeddableHierarchy( AccessType.FIELD, NonAnnotatedEmbeddable.class );
}
@Entity
public class Foo {
@Id
@GeneratedValue
private int id;
}
@Entity
public class A {
@Id
@GeneratedValue
private int id;
}
@Entity
public class B extends A {
private String name;
}
}

View File

@ -1,268 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.util;
import java.util.Iterator;
import java.util.Set;
import javax.persistence.Embeddable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.MappedSuperclass;
import org.junit.Test;
import org.hibernate.AnnotationException;
import org.hibernate.metamodel.binding.InheritanceType;
import org.hibernate.metamodel.source.binder.EntityHierarchy;
import org.hibernate.metamodel.source.binder.RootEntitySource;
import org.hibernate.metamodel.source.binder.SubclassEntitySource;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
/**
* @author Hardy Ferentschik
*/
public class EntityHierarchyTest extends BaseAnnotationIndexTestCase {
@Test
public void testSingleEntity() {
@Entity
class Foo {
@Id
@GeneratedValue
private int id;
}
Set<EntityHierarchy> hierarchies = createEntityHierarchies( Foo.class );
assertEquals( "There should be only one hierarchy", 1, hierarchies.size() );
EntityHierarchy hierarchy = hierarchies.iterator().next();
assertEquals(
"wrong entity name",
Foo.class.getName(),
hierarchy.getRootEntitySource().getEntityName()
);
}
@Test
public void testSimpleInheritance() {
@Entity
class A {
@Id
@GeneratedValue
private int id;
}
@Entity
class B extends A {
private String name;
}
Set<EntityHierarchy> hierarchies = createEntityHierarchies( B.class, A.class );
assertEquals( "There should be only one hierarchy", 1, hierarchies.size() );
EntityHierarchy hierarchy = hierarchies.iterator().next();
RootEntitySource rootSource = hierarchy.getRootEntitySource();
assertEquals(
"wrong entity name",
A.class.getName(),
rootSource.getEntityName()
);
Iterator<SubclassEntitySource> iter = rootSource.subclassEntitySources().iterator();
assertTrue( "There should be a subclass entity source", iter.hasNext() );
assertEquals( "wrong class", B.class.getName(), iter.next().getEntityName() );
assertFalse( "There should be no more subclass entity sources", iter.hasNext() );
}
@Test
public void testMultipleHierarchies() {
@Entity
class Foo {
@Id
@GeneratedValue
private int id;
}
@Entity
class A {
@Id
@GeneratedValue
private int id;
}
@Entity
class B extends A {
private String name;
}
Set<EntityHierarchy> hierarchies = createEntityHierarchies( B.class, Foo.class, A.class );
assertEquals( "There should be only one hierarchy", 2, hierarchies.size() );
}
@Test
public void testMappedSuperClass() {
@MappedSuperclass
class MappedSuperClass {
@Id
@GeneratedValue
private int id;
}
class UnmappedSubClass extends MappedSuperClass {
private String unmappedProperty;
}
@Entity
class MappedSubClass extends UnmappedSubClass {
private String mappedProperty;
}
Set<EntityHierarchy> hierarchies = createEntityHierarchies(
MappedSubClass.class,
MappedSuperClass.class,
UnmappedSubClass.class
);
assertEquals( "There should be only one hierarchy", 1, hierarchies.size() );
EntityHierarchy hierarchy = hierarchies.iterator().next();
assertEquals(
"wrong entity name",
MappedSubClass.class.getName(),
hierarchy.getRootEntitySource().getEntityName()
);
}
@Test(expected = AnnotationException.class)
public void testEntityAndMappedSuperClassAnnotations() {
@Entity
@MappedSuperclass
class EntityAndMappedSuperClass {
}
createEntityHierarchies( EntityAndMappedSuperClass.class );
}
@Test(expected = AnnotationException.class)
public void testEntityAndEmbeddableAnnotations() {
@Entity
@Embeddable
class EntityAndEmbeddable {
}
createEntityHierarchies( EntityAndEmbeddable.class );
}
@Test(expected = AnnotationException.class)
public void testNoIdAnnotation() {
@Entity
class A {
String id;
}
@Entity
class B extends A {
}
createEntityHierarchies( B.class, A.class );
}
@Test
public void testDefaultInheritanceStrategy() {
@Entity
class A {
@Id
String id;
}
@Entity
class B extends A {
}
Set<EntityHierarchy> hierarchies = createEntityHierarchies( B.class, A.class );
assertEquals( "There should be only one hierarchy", 1, hierarchies.size() );
EntityHierarchy hierarchy = hierarchies.iterator().next();
assertEquals(
"wrong entity name",
A.class.getName(),
hierarchy.getRootEntitySource().getEntityName()
);
assertEquals( "Wrong inheritance type", InheritanceType.SINGLE_TABLE, hierarchy.getHierarchyInheritanceType() );
}
@Test
public void testExplicitInheritanceStrategy() {
@MappedSuperclass
class MappedSuperClass {
}
@Entity
@Inheritance(strategy = javax.persistence.InheritanceType.JOINED)
class A extends MappedSuperClass {
@Id
String id;
}
@Entity
class B extends A {
}
Set<EntityHierarchy> hierarchies = createEntityHierarchies(
B.class,
MappedSuperClass.class,
A.class
);
EntityHierarchy hierarchy = hierarchies.iterator().next();
assertEquals(
"wrong entity name",
A.class.getName(),
hierarchy.getRootEntitySource().getEntityName()
);
assertEquals( "Wrong inheritance type", InheritanceType.JOINED, hierarchy.getHierarchyInheritanceType() );
}
@Test(expected = AnnotationException.class)
public void testMultipleConflictingInheritanceDefinitions() {
@Entity
@Inheritance(strategy = javax.persistence.InheritanceType.JOINED)
class A {
String id;
}
@Entity
@Inheritance(strategy = javax.persistence.InheritanceType.TABLE_PER_CLASS)
class B extends A {
}
createEntityHierarchies( B.class, A.class );
}
}

View File

@ -1,253 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.util;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.MappedSuperclass;
import org.junit.Test;
/**
* @author Hardy Ferentschik
*/
public class GenericTypeDiscoveryTest extends BaseAnnotationIndexTestCase {
@Test
public void testGenericClassHierarchy() {
// Set<ConfiguredClassHierarchy<EntityClass>> hierarchies = createEntityHierarchies(
// Paper.class,
// Stuff.class,
// Item.class,
// PricedStuff.class
// );
// assertEquals( "There should be only one hierarchy", 1, hierarchies.size() );
//
// Iterator<EntityClass> iter = hierarchies.iterator().next().iterator();
// ConfiguredClass configuredClass = iter.next();
// ClassInfo info = configuredClass.getClassInfo();
// assertEquals( "wrong class", DotName.createSimple( Stuff.class.getName() ), info.name() );
// MappedAttribute property = configuredClass.getMappedAttribute( "value" );
// assertEquals( Price.class, property.getJavaType() );
//
// assertTrue( iter.hasNext() );
// configuredClass = iter.next();
// info = configuredClass.getClassInfo();
// assertEquals( "wrong class", DotName.createSimple( PricedStuff.class.getName() ), info.name() );
// assertFalse(
// "PricedStuff should not mapped properties", configuredClass.getSimpleAttributes().iterator().hasNext()
// );
//
// assertTrue( iter.hasNext() );
// configuredClass = iter.next();
// info = configuredClass.getClassInfo();
// assertEquals( "wrong class", DotName.createSimple( Item.class.getName() ), info.name() );
// // properties are alphabetically ordered!
// property = configuredClass.getMappedAttribute( "owner" );
// assertEquals( SomeGuy.class, property.getJavaType() );
// property = configuredClass.getMappedAttribute( "type" );
// assertEquals( PaperType.class, property.getJavaType() );
//
// assertTrue( iter.hasNext() );
// configuredClass = iter.next();
// info = configuredClass.getClassInfo();
// assertEquals( "wrong class", DotName.createSimple( Paper.class.getName() ), info.name() );
// assertFalse( "Paper should not mapped properties", configuredClass.getSimpleAttributes().iterator().hasNext() );
//
// assertFalse( iter.hasNext() );
}
@Test
public void testUnresolvedType() {
// Set<ConfiguredClassHierarchy<EntityClass>> hierarchies = createEntityHierarchies( UnresolvedType.class );
// assertEquals( "There should be only one hierarchy", 1, hierarchies.size() );
}
@MappedSuperclass
public class Stuff<Value> {
private Value value;
@ManyToOne
public Value getValue() {
return value;
}
public void setValue(Value value) {
this.value = value;
}
}
@MappedSuperclass
public class PricedStuff extends Stuff<Price> {
}
@MappedSuperclass
public class Item<Type, Owner> extends PricedStuff {
private Integer id;
private String name;
private Type type;
private Owner owner;
@Id
@GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ManyToOne
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
@ManyToOne
public Owner getOwner() {
return owner;
}
public void setOwner(Owner owner) {
this.owner = owner;
}
}
@Entity
public class Paper extends Item<PaperType, SomeGuy> {
}
@Entity
public class PaperType {
private Integer id;
private String name;
@Id
@GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Entity
public class Price {
private Integer id;
private Double amount;
private String currency;
@Id
@GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Double getAmount() {
return amount;
}
public void setAmount(Double amount) {
this.amount = amount;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
}
@Entity
public class SomeGuy {
private Integer id;
@Id
@GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
@Entity
public class UnresolvedType<T> {
private Integer id;
private T state;
@Id
@GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
//@Type(type = "org.hibernate.test.annotations.generics.StateType")
public T getState() {
return state;
}
public void setState(T state) {
this.state = state;
}
}
}

View File

@ -1,249 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.util;
import java.util.List;
import java.util.Map;
import javax.persistence.AttributeOverride;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.LockModeType;
import javax.persistence.NamedQuery;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.Index;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.hibernate.AssertionFailure;
import org.hibernate.annotations.NamedNativeQuery;
import org.hibernate.metamodel.source.annotations.HibernateDotNames;
import org.hibernate.metamodel.source.annotations.JPADotNames;
import org.hibernate.metamodel.source.annotations.JandexHelper;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.service.classloading.spi.ClassLoaderService;
import org.hibernate.service.internal.StandardServiceRegistryImpl;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import static junit.framework.Assert.assertTrue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
/**
* Tests for the helper class {@link JandexHelper}.
*
* @author Hardy Ferentschik
*/
public class JandexHelperTest extends BaseUnitTestCase {
private StandardServiceRegistryImpl serviceRegistry;
private ClassLoaderService classLoaderService;
@Before
public void setUp() {
serviceRegistry = (StandardServiceRegistryImpl) new ServiceRegistryBuilder().buildServiceRegistry();
classLoaderService = serviceRegistry.getService( ClassLoaderService.class );
}
@After
public void tearDown() {
serviceRegistry.destroy();
}
@Test
public void testGetMemberAnnotations() {
class Foo {
@Column
@Basic
private String bar;
private String fubar;
}
Index index = JandexHelper.indexForClass( classLoaderService, Foo.class );
ClassInfo classInfo = index.getClassByName( DotName.createSimple( Foo.class.getName() ) );
Map<DotName, List<AnnotationInstance>> memberAnnotations = JandexHelper.getMemberAnnotations(
classInfo, "bar"
);
assertTrue(
"property bar should defines @Column annotation",
memberAnnotations.containsKey( DotName.createSimple( Column.class.getName() ) )
);
assertTrue(
"property bar should defines @Basic annotation",
memberAnnotations.containsKey( DotName.createSimple( Basic.class.getName() ) )
);
memberAnnotations = JandexHelper.getMemberAnnotations( classInfo, "fubar" );
assertTrue( "there should be no annotations in fubar", memberAnnotations.isEmpty() );
}
@Test
public void testGettingNestedAnnotation() {
@AttributeOverride(name = "foo", column = @Column(name = "FOO"))
class Foo {
}
Index index = JandexHelper.indexForClass( classLoaderService, Foo.class );
List<AnnotationInstance> annotationInstances = index.getAnnotations( JPADotNames.ATTRIBUTE_OVERRIDE );
assertTrue( annotationInstances.size() == 1 );
AnnotationInstance annotationInstance = annotationInstances.get( 0 );
// try to retrieve the name
String name = JandexHelper.getValue( annotationInstance, "name", String.class );
assertEquals( "Wrong nested annotation", "foo", name );
// try to retrieve the nested column annotation instance
AnnotationInstance columnAnnotationInstance = JandexHelper.getValue(
annotationInstance,
"column",
AnnotationInstance.class
);
assertNotNull( columnAnnotationInstance );
assertEquals(
"Wrong nested annotation",
"javax.persistence.Column",
columnAnnotationInstance.name().toString()
);
}
@Test(expected = AssertionFailure.class)
public void testTryingToRetrieveWrongType() {
@AttributeOverride(name = "foo", column = @Column(name = "FOO"))
class Foo {
}
Index index = JandexHelper.indexForClass( classLoaderService, Foo.class );
List<AnnotationInstance> annotationInstances = index.getAnnotations( JPADotNames.ATTRIBUTE_OVERRIDE );
assertTrue( annotationInstances.size() == 1 );
AnnotationInstance annotationInstance = annotationInstances.get( 0 );
JandexHelper.getValue( annotationInstance, "name", Float.class );
}
@Test
public void testRetrieveDefaultEnumElement() {
@NamedQuery(name = "foo", query = "fubar")
class Foo {
}
Index index = JandexHelper.indexForClass( classLoaderService, Foo.class );
List<AnnotationInstance> annotationInstances = index.getAnnotations( JPADotNames.NAMED_QUERY );
assertTrue( annotationInstances.size() == 1 );
AnnotationInstance annotationInstance = annotationInstances.get( 0 );
LockModeType lockMode = JandexHelper.getEnumValue( annotationInstance, "lockMode", LockModeType.class );
assertEquals( "Wrong lock mode", LockModeType.NONE, lockMode );
}
@Test
public void testRetrieveExplicitEnumElement() {
@NamedQuery(name = "foo", query = "bar", lockMode = LockModeType.OPTIMISTIC)
class Foo {
}
Index index = JandexHelper.indexForClass( classLoaderService, Foo.class );
List<AnnotationInstance> annotationInstances = index.getAnnotations( JPADotNames.NAMED_QUERY );
assertTrue( annotationInstances.size() == 1 );
AnnotationInstance annotationInstance = annotationInstances.get( 0 );
LockModeType lockMode = JandexHelper.getEnumValue( annotationInstance, "lockMode", LockModeType.class );
assertEquals( "Wrong lock mode", LockModeType.OPTIMISTIC, lockMode );
}
@Test
public void testRetrieveStringArray() {
class Foo {
@org.hibernate.annotations.Index(name = "index", columnNames = { "a", "b", "c" })
private String foo;
}
Index index = JandexHelper.indexForClass( classLoaderService, Foo.class );
List<AnnotationInstance> annotationInstances = index.getAnnotations( HibernateDotNames.INDEX );
assertTrue( annotationInstances.size() == 1 );
AnnotationInstance annotationInstance = annotationInstances.get( 0 );
String[] columnNames = JandexHelper.getValue( annotationInstance, "columnNames", String[].class );
Assert.assertTrue( columnNames.length == 3 );
}
@Test(expected = AssertionFailure.class)
public void testRetrieveClassParameterAsClass() {
@NamedNativeQuery(name = "foo", query = "bar", resultClass = Foo.class)
class Foo {
}
Index index = JandexHelper.indexForClass( classLoaderService, Foo.class );
List<AnnotationInstance> annotationInstances = index.getAnnotations( HibernateDotNames.NAMED_NATIVE_QUERY );
assertTrue( annotationInstances.size() == 1 );
AnnotationInstance annotationInstance = annotationInstances.get( 0 );
JandexHelper.getValue( annotationInstance, "resultClass", Class.class );
}
@Test
public void testRetrieveClassParameterAsString() {
@NamedNativeQuery(name = "foo", query = "bar", resultClass = Foo.class)
class Foo {
}
Index index = JandexHelper.indexForClass( classLoaderService, Foo.class );
List<AnnotationInstance> annotationInstances = index.getAnnotations( HibernateDotNames.NAMED_NATIVE_QUERY );
assertTrue( annotationInstances.size() == 1 );
AnnotationInstance annotationInstance = annotationInstances.get( 0 );
String fqcn = JandexHelper.getValue( annotationInstance, "resultClass", String.class );
assertEquals( "Wrong class names", Foo.class.getName(), fqcn );
}
@Test
public void testRetrieveUnknownParameter() {
@Entity
class Foo {
}
Index index = JandexHelper.indexForClass( classLoaderService, Foo.class );
List<AnnotationInstance> annotationInstances = index.getAnnotations( JPADotNames.ENTITY );
assertTrue( annotationInstances.size() == 1 );
AnnotationInstance annotationInstance = annotationInstances.get( 0 );
try {
JandexHelper.getValue( annotationInstance, "foo", String.class );
fail();
}
catch ( AssertionFailure e ) {
assertTrue(
e.getMessage()
.startsWith( "The annotation javax.persistence.Entity does not define a parameter 'foo'" )
);
}
}
}

View File

@ -1,67 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.util;
import javax.persistence.Id;
import org.junit.Test;
import org.hibernate.annotations.Parameter;
import org.hibernate.annotations.Type;
/**
* @author Hardy Ferentschik
*/
public class TypeDiscoveryTest extends BaseAnnotationIndexTestCase {
@Test
public void testImplicitAndExplicitType() {
// Set<ConfiguredClassHierarchy<EntityClass>> hierarchies = createEntityHierarchies( Entity.class );
// assertEquals( "There should be only one hierarchy", 1, hierarchies.size() );
//
// Iterator<EntityClass> iter = hierarchies.iterator().next().iterator();
// ConfiguredClass configuredClass = iter.next();
//
// MappedAttribute property = configuredClass.getMappedAttribute( "id" );
// assertEquals( "Unexpected property type", int.class, property.getJavaType() );
//
// property = configuredClass.getMappedAttribute( "string" );
// assertEquals( "Unexpected property type", String.class, property.getJavaType() );
//
// property = configuredClass.getMappedAttribute( "customString" );
// assertEquals( "Unexpected property type", "my.custom.Type", property.getExplicitHibernateTypeName() );
//
// Map<String, String> typeParameters = property.getExplicitHibernateTypeParameters();
// assertEquals( "There should be a type parameter", "bar", typeParameters.get( "foo" ) );
}
@javax.persistence.Entity
class Entity {
@Id
private int id;
private String string;
@Type(type = "my.custom.Type", parameters = { @Parameter(name = "foo", value = "bar") })
private String customString;
}
}

View File

@ -1,51 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.xml;
/**
* @author Hardy Ferentschik
*/
public class Father {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -1,69 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.xml;
import org.junit.Test;
import org.hibernate.metamodel.MetadataSources;
import org.hibernate.metamodel.binding.EntityBinding;
import org.hibernate.metamodel.source.MappingException;
import org.hibernate.metamodel.source.internal.MetadataImpl;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import static junit.framework.Assert.assertNotNull;
/**
* @author Hardy Ferentschik
*/
public class OrmXmlParserTests extends BaseUnitTestCase {
@Test
public void testSimpleOrmVersion2() {
MetadataSources sources = new MetadataSources( new ServiceRegistryBuilder().buildServiceRegistry() );
sources.addResource( "org/hibernate/metamodel/source/annotations/xml/orm-father.xml" );
MetadataImpl metadata = (MetadataImpl) sources.buildMetadata();
EntityBinding binding = metadata.getEntityBinding( Father.class.getName() );
assertNotNull( binding );
}
@Test
public void testSimpleOrmVersion1() {
MetadataSources sources = new MetadataSources( new ServiceRegistryBuilder().buildServiceRegistry() );
sources.addResource( "org/hibernate/metamodel/source/annotations/xml/orm-star.xml" );
MetadataImpl metadata = (MetadataImpl) sources.buildMetadata();
EntityBinding binding = metadata.getEntityBinding( Star.class.getName() );
assertNotNull( binding );
}
@Test(expected = MappingException.class)
public void testInvalidOrmXmlThrowsException() {
MetadataSources sources = new MetadataSources( new ServiceRegistryBuilder().buildServiceRegistry() );
sources.addResource( "org/hibernate/metamodel/source/annotations/xml/orm-invalid.xml" );
sources.buildMetadata();
}
}

View File

@ -1,36 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.xml;
import javax.persistence.Entity;
/**
* @author Hardy Ferentschik
*/
@Entity
public class Star {
private int id;
}

View File

@ -1,206 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.xml.mocker;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBException;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationValue;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.Index;
import org.jboss.jandex.Indexer;
import org.hibernate.AnnotationException;
import org.hibernate.HibernateException;
import org.hibernate.internal.jaxb.mapping.orm.JaxbEntityMappings;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.classloading.spi.ClassLoaderService;
import org.hibernate.testing.ServiceRegistryBuilder;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
/**
* @author Strong Liu
*/
public abstract class AbstractMockerTest {
private static final String ORM1_MAPPING_XSD = "org/hibernate/ejb/orm_1_0.xsd";
private static final String ORM2_MAPPING_XSD = "org/hibernate/ejb/orm_2_0.xsd";
private IndexBuilder indexBuilder;
private Index index;
private ServiceRegistry serviceRegistry;
protected String packagePrefix = getClass().getPackage().getName().replace( '.', '/' ) + '/';
protected IndexBuilder getIndexBuilder() {
if ( indexBuilder == null ) {
indexBuilder = new IndexBuilder( getIndex(), getServiceRegistry() );
}
return indexBuilder;
}
protected EntityMappingsMocker getEntityMappingsMocker(String... mappingFiles) {
ClassLoaderService classLoaderService = getServiceRegistry().getService( ClassLoaderService.class );
List<JaxbEntityMappings> xmlEntityMappingsList = new ArrayList<JaxbEntityMappings>();
for ( String fileName : mappingFiles ) {
JaxbEntityMappings entityMappings;
try {
entityMappings = XmlHelper.unmarshallXml(
packagePrefix + fileName, ORM2_MAPPING_XSD, JaxbEntityMappings.class, classLoaderService
).getRoot();
}
catch ( JAXBException orm2Exception ) {
// if we cannot parse against orm_2_0.xsd we try orm_1_0.xsd for backwards compatibility
try {
entityMappings = XmlHelper.unmarshallXml(
packagePrefix + fileName, ORM1_MAPPING_XSD, JaxbEntityMappings.class, classLoaderService
).getRoot();
}
catch ( JAXBException orm1Exception ) {
throw new AnnotationException( "Unable to parse xml configuration.", orm1Exception );
}
}
xmlEntityMappingsList.add( entityMappings );
}
return new EntityMappingsMocker( xmlEntityMappingsList, getIndex(), getServiceRegistry() );
}
protected Index getIndex() {
if ( index == null ) {
Indexer indexer = new Indexer();
for ( Class<?> clazz : getAnnotatedClasses() ) {
indexClass( indexer, clazz.getName().replace( '.', '/' ) + ".class" );
}
// add package-info from the configured packages
for ( String packageName : getAnnotatedPackages() ) {
indexClass( indexer, packageName.replace( '.', '/' ) + "/package-info.class" );
}
index = indexer.complete();
}
return index;
}
protected Index getMockedIndex(String ormFileName) {
EntityMappingsMocker mocker = getEntityMappingsMocker( ormFileName );
return mocker.mockNewIndex();
}
private void indexClass(Indexer indexer, String className) {
ClassLoaderService classLoaderService = getServiceRegistry().getService( ClassLoaderService.class );
InputStream stream = classLoaderService.locateResourceStream( className );
try {
indexer.index( stream );
}
catch ( IOException e ) {
throw new HibernateException( "Unable to open input stream for class " + className, e );
}
}
protected Class[] getAnnotatedClasses() {
return new Class[0];
}
protected String[] getAnnotatedPackages() {
return new String[0];
}
protected ServiceRegistry getServiceRegistry() {
if ( serviceRegistry == null ) {
serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry();
}
return serviceRegistry;
}
protected void assertHasNoAnnotation(Index index, DotName className, DotName annName) {
List<AnnotationInstance> annotationInstanceList = getAnnotationInstances( index, className, annName );
if ( annotationInstanceList != null ) {
if ( !annotationInstanceList.isEmpty() ) {
fail( className + " has Annotation " + annName );
}
}
}
protected void assertHasAnnotation(Index index, DotName annName) {
assertHasAnnotation( index, null, annName, 1 );
}
protected void assertHasAnnotation(Index index, DotName className, DotName annName) {
assertHasAnnotation( index, className, annName, 1 );
}
protected void assertHasAnnotation(Index index, DotName className, DotName annName, int size) {
List<AnnotationInstance> annotationInstanceList = getAnnotationInstances( index, className, annName );
if ( annotationInstanceList == null || annotationInstanceList.isEmpty() ) {
fail( "Expected annotation " + annName + " size is " + size + ", but no one can be found in Index" );
}
assertEquals(
"Expected annotation " + annName + " size is " + size + ", but it actually is " + annotationInstanceList
.size(), size, annotationInstanceList.size()
);
}
protected void assertStringAnnotationValue(String expected, AnnotationValue annotationValue) {
if ( annotationValue == null ) {
fail( "Annotation Value is null." );
}
assertEquals( expected, annotationValue.asString() );
}
protected void assertAnnotationValue(Index index, DotName className, DotName annName, AnnotationValueChecker checker) {
assertAnnotationValue( index, className, annName, 1, checker );
}
protected void assertAnnotationValue(Index index, DotName className, DotName annName, int size, AnnotationValueChecker checker) {
assertHasAnnotation( index, className, annName, size );
List<AnnotationInstance> annotationInstanceList = getAnnotationInstances( index,className,annName );
for ( AnnotationInstance annotationInstance : annotationInstanceList ) {
checker.check( annotationInstance );
}
}
private List<AnnotationInstance> getAnnotationInstances(Index index, DotName className, DotName annName) {
if ( className != null ) {
ClassInfo classInfo = index.getClassByName( className );
if ( classInfo == null ) {
fail( "Can't find " + className + " from Index" );
}
if ( classInfo.annotations() == null ) {
fail( classInfo + " doesn't have any annotations defined" );
}
return classInfo.annotations().get( annName );
}
else {
return index.getAnnotations( annName );
}
}
static interface AnnotationValueChecker {
void check(AnnotationInstance annotationInstance);
}
}

View File

@ -1,73 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.xml.mocker;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
/**
* @author Strong Liu
*/
@Entity
public class Author {
private Long id;
private String name;
private List<Book> books = new ArrayList<Book>();
@Id
@GeneratedValue(generator = "SEQ_GEN")
@SequenceGenerator(name = "SEQ_GEN", initialValue = 123)
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;
}
@OneToMany(mappedBy = "author",cascade = CascadeType.MERGE)
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
}

View File

@ -1,108 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.xml.mocker;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationValue;
import org.jboss.jandex.DotName;
import org.jboss.jandex.Index;
import org.junit.Test;
import org.hibernate.internal.jaxb.mapping.orm.JaxbAttributes;
import org.hibernate.internal.jaxb.mapping.orm.JaxbEntity;
import org.hibernate.internal.jaxb.mapping.orm.JaxbGeneratedValue;
import org.hibernate.internal.jaxb.mapping.orm.JaxbId;
import org.hibernate.metamodel.source.annotations.JPADotNames;
import static org.junit.Assert.assertEquals;
/**
* @author Strong Liu
*/
public class BasicMockerTest extends AbstractMockerTest {
@Test
public void testEntity() {
JaxbEntity entity = createEntity();
IndexBuilder indexBuilder = getIndexBuilder();
EntityMocker entityMocker = new EntityMocker( indexBuilder, entity, new EntityMappingsMocker.Default() );
entityMocker.preProcess();
entityMocker.process();
Index index = indexBuilder.build( new EntityMappingsMocker.Default() );
assertEquals( 1, index.getKnownClasses().size() );
DotName itemName = DotName.createSimple( Item.class.getName() );
assertHasAnnotation( index, itemName, JPADotNames.ENTITY );
assertHasAnnotation( index, itemName, JPADotNames.ID );
assertHasAnnotation( index, itemName, JPADotNames.GENERATED_VALUE );
}
@Test
public void testEntityWithEntityMappingsConfiguration() {
JaxbEntity entity = new JaxbEntity();
entity.setName( "Item" );
entity.setClazz( "Item" );
IndexBuilder indexBuilder = getIndexBuilder();
EntityMappingsMocker.Default defaults = new EntityMappingsMocker.Default();
defaults.setPackageName( getClass().getPackage().getName() );
defaults.setSchema( "HIBERNATE_SCHEMA" );
defaults.setCatalog( "HIBERNATE_CATALOG" );
EntityMocker entityMocker = new EntityMocker( indexBuilder, entity, defaults );
entityMocker.preProcess();
entityMocker.process();
Index index = indexBuilder.build( new EntityMappingsMocker.Default() );
assertEquals( 1, index.getKnownClasses().size() );
DotName itemName = DotName.createSimple( Item.class.getName() );
assertHasAnnotation( index, itemName, JPADotNames.ENTITY );
assertHasAnnotation( index, itemName, JPADotNames.TABLE );
assertAnnotationValue(
index, itemName, JPADotNames.TABLE, new AnnotationValueChecker() {
@Override
public void check(AnnotationInstance annotationInstance) {
AnnotationValue schemaValue = annotationInstance.value( "schema" );
AnnotationValue catalogValue = annotationInstance.value( "catalog" );
assertStringAnnotationValue( "HIBERNATE_SCHEMA", schemaValue );
assertStringAnnotationValue( "HIBERNATE_CATALOG", catalogValue );
}
}
);
}
private JaxbEntity createEntity() {
JaxbEntity entity = new JaxbEntity();
entity.setName( "Item" );
entity.setClazz( Item.class.getName() );
JaxbAttributes attributes = new JaxbAttributes();
JaxbId id = new JaxbId();
id.setName( "id" );
id.setGeneratedValue( new JaxbGeneratedValue() );
attributes.getId().add( id );
entity.setAttributes( attributes );
return entity;
}
}

View File

@ -1,101 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.xml.mocker;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.AttributeOverride;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.TableGenerator;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Version;
/**
* @author Strong Liu
*/
@Entity
@TableGenerator(name = "TABLE_GEN", catalog = "ANNOTATION_CATALOG", schema = "ANNOTATION_SCHEMA")
public class Book {
@Id
@GeneratedValue(generator = "TABLE_GEN")
private Long id;
@Temporal(TemporalType.TIMESTAMP)
private Date publishDate;
@ManyToOne(cascade = CascadeType.DETACH)
private Author author;
@ElementCollection
@AttributeOverride(name = "title", column = @Column(name = "TOC_TITLE"))
private List<Topic> topics = new ArrayList<Topic>();
public List<Topic> getTopics() {
return topics;
}
public void setTopics(List<Topic> topics) {
this.topics = topics;
}
@Version
private Long version;
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getPublishDate() {
return publishDate;
}
public void setPublishDate(Date publishDate) {
this.publishDate = publishDate;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
}

View File

@ -1,200 +0,0 @@
package org.hibernate.metamodel.source.annotations.xml.mocker;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.SecondaryTable;
import javax.persistence.SecondaryTables;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.DotName;
import org.jboss.jandex.Index;
import org.junit.Test;
import org.hibernate.internal.jaxb.mapping.orm.JaxbEntity;
import org.hibernate.metamodel.source.annotations.JPADotNames;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* @author Strong Liu
*/
public class DefaultConfigurationHelperTest extends AbstractMockerTest {
@Test
public void applyNullDefaultToEntity() {
JaxbEntity entity = new JaxbEntity();
entity.setClazz( "Entity" );
DefaultConfigurationHelper.INSTANCE.applyDefaults( entity, null );
assertNull( entity.getTable() );
assertEquals( "Entity", entity.getClazz() );
}
@Test
public void applyDefaultToEntity() {
EntityMappingsMocker.Default defaults = new EntityMappingsMocker.Default();
defaults.setPackageName( "org.test" );
defaults.setSchema( "schema" );
defaults.setMetadataComplete( true );
JaxbEntity entity = new JaxbEntity();
entity.setClazz( "Entity" );
DefaultConfigurationHelper.INSTANCE.applyDefaults( entity, defaults );
assertNotNull( entity.getTable() );
assertNull( entity.getTable().getSchema() );
assertNull( entity.getTable().getCatalog() );
assertTrue( entity.isMetadataComplete() );
assertEquals( "org.test.Entity", entity.getClazz() );
DefaultConfigurationHelper.INSTANCE
.applyDefaults( new SchemaAware.TableSchemaAware( entity.getTable() ), defaults );
assertEquals( "schema", entity.getTable().getSchema() );
assertNull( entity.getTable().getCatalog() );
}
@Test
public void testDefaultCascadePersist() {
EntityMappingsMocker.Default defaults = new EntityMappingsMocker.Default();
defaults.setCascadePersist( true );
Index index = getIndex();
Map<DotName, List<AnnotationInstance>> annotations = new HashMap<DotName, List<AnnotationInstance>>();
annotations.putAll( index.getClassByName( DotName.createSimple( Parent.class.getName() ) ).annotations() );
assertEquals( 4, annotations.size() );
assertEquals( 1, annotations.get( JPADotNames.ENTITY ).size() );
assertEquals( 1, annotations.get( JPADotNames.ID ).size() );
assertEquals( 1, annotations.get( JPADotNames.ONE_TO_MANY ).size() );
assertEquals( 1, annotations.get( JPADotNames.MANY_TO_ONE ).size() );
DefaultConfigurationHelper.INSTANCE.applyDefaults( annotations, defaults );
assertEquals( 4, annotations.size() );
assertEquals( 1, annotations.get( JPADotNames.ENTITY ).size() );
assertEquals( 1, annotations.get( JPADotNames.ID ).size() );
assertEquals( 1, annotations.get( JPADotNames.ONE_TO_MANY ).size() );
assertEquals( 1, annotations.get( JPADotNames.MANY_TO_ONE ).size() );
AnnotationInstance oneToMany = annotations.get( JPADotNames.ONE_TO_MANY ).get( 0 );
String[] cascadeTypes = oneToMany.value( "cascade" ).asEnumArray();
assertArrayEquals( new String[] { "ALL", "DETACH", "PERSIST" }, cascadeTypes );
AnnotationInstance manyToOne = annotations.get( JPADotNames.MANY_TO_ONE ).get( 0 );
cascadeTypes = manyToOne.value( "cascade" ).asEnumArray();
assertArrayEquals( new String[] { "PERSIST" }, cascadeTypes );
annotations.clear();
annotations.putAll( index.getClassByName( DotName.createSimple( Child.class.getName() ) ).annotations() );
assertEquals( 3, annotations.size() );
assertEquals( 1, annotations.get( JPADotNames.ENTITY ).size() );
assertEquals( 1, annotations.get( JPADotNames.ID ).size() );
assertEquals( 1, annotations.get( JPADotNames.MANY_TO_ONE ).size() );
DefaultConfigurationHelper.INSTANCE.applyDefaults( annotations, defaults );
assertEquals( 3, annotations.size() );
assertEquals( 1, annotations.get( JPADotNames.ENTITY ).size() );
assertEquals( 1, annotations.get( JPADotNames.ID ).size() );
assertEquals( 1, annotations.get( JPADotNames.MANY_TO_ONE ).size() );
manyToOne = annotations.get( JPADotNames.MANY_TO_ONE ).get( 0 );
cascadeTypes = manyToOne.value( "cascade" ).asEnumArray();
assertArrayEquals( new String[] { "PERSIST", "ALL", "DETACH" }, cascadeTypes );
}
@Test
public void testDefaultSchemaToAnnotationInstance() {
EntityMappingsMocker.Default defaults = new EntityMappingsMocker.Default();
defaults.setSchema( "hib_schema" );
defaults.setCatalog( "hib_catalog" );
Index index = getIndex();
Map<DotName, List<AnnotationInstance>> annotations = new HashMap<DotName, List<AnnotationInstance>>();
annotations.putAll( index.getClassByName( DotName.createSimple( Parent.class.getName() ) ).annotations() );
assertEquals( 4, annotations.size() );
assertEquals( 1, annotations.get( JPADotNames.ENTITY ).size() );
assertEquals( 1, annotations.get( JPADotNames.ID ).size() );
assertEquals( 1, annotations.get( JPADotNames.ONE_TO_MANY ).size() );
assertEquals( 1, annotations.get( JPADotNames.MANY_TO_ONE ).size() );
DefaultConfigurationHelper.INSTANCE.applyDefaults( annotations, defaults );
assertEquals( 5, annotations.size() );
assertEquals( 1, annotations.get( JPADotNames.ENTITY ).size() );
assertEquals( 1, annotations.get( JPADotNames.ID ).size() );
assertEquals( 1, annotations.get( JPADotNames.ONE_TO_MANY ).size() );
assertEquals( 1, annotations.get( JPADotNames.MANY_TO_ONE ).size() );
assertEquals( 1, annotations.get( JPADotNames.TABLE ).size() );
AnnotationInstance table = annotations.get( JPADotNames.TABLE ).get( 0 );
assertEquals( "hib_schema", table.value( "schema" ).asString() );
assertEquals( "hib_catalog", table.value( "catalog" ).asString() );
annotations.clear();
annotations.putAll( index.getClassByName( DotName.createSimple( Name.class.getName() ) ).annotations() );
DefaultConfigurationHelper.INSTANCE.applyDefaults( annotations, defaults );
assertEquals( 1, annotations.size() );
assertEquals( 1, annotations.get( JPADotNames.SECONDARY_TABLES ).size() );
AnnotationInstance[] secondaryTables = annotations.get( JPADotNames.SECONDARY_TABLES )
.get( 0 )
.value()
.asNestedArray();
assertEquals( 2, secondaryTables.length );
AnnotationInstance secondaryTable = secondaryTables[0];
String name = secondaryTable.value( "name" ).asString();
if ( name.equals( "sec1" ) ) {
assertSt1( secondaryTable );
assertSt2( secondaryTables[1] );
}
else {
assertSt1( secondaryTables[1] );
assertSt2( secondaryTable );
}
}
private void assertSt1(AnnotationInstance secondaryTable) {
assertEquals( "hib_schema", secondaryTable.value( "schema" ).asString() );
assertEquals( "sec1_catalog", secondaryTable.value( "catalog" ).asString() );
}
private void assertSt2(AnnotationInstance secondaryTable) {
assertEquals( "sec2_schema", secondaryTable.value( "schema" ).asString() );
assertEquals( "hib_catalog", secondaryTable.value( "catalog" ).asString() );
}
@Override
protected Class[] getAnnotatedClasses() {
return new Class[] { Parent.class, Child.class, Name.class };
}
@SecondaryTables( {
@SecondaryTable(name = "sec1", catalog = "sec1_catalog"),
@SecondaryTable(name = "sec2", schema = "sec2_schema")
})
class Name {
}
@Entity
class Parent {
@Id
long id;
@OneToMany(cascade = { CascadeType.ALL, CascadeType.DETACH, CascadeType.PERSIST })
Set<Child> children = new HashSet<Child>();
@ManyToOne
Parent parent;
}
@Entity
class Child {
@Id
long id;
@ManyToOne(cascade = { CascadeType.ALL, CascadeType.DETACH })
Parent parent;
}
}

View File

@ -1,62 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.xml.mocker;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.Index;
import org.junit.Test;
import org.hibernate.metamodel.source.annotations.JPADotNames;
import org.hibernate.metamodel.source.annotations.xml.PseudoJpaDotNames;
import static org.junit.Assert.assertEquals;
/**
* @author Strong Liu
*/
public class EntityListenerTest extends AbstractMockerTest {
@Test
public void basicEntityListenerMockTest() {
Index index = getMockedIndex( "listener.xml" );
DotName itemName = DotName.createSimple( Item.class.getName() );
DotName itemListenerName = DotName.createSimple( ItemListener.class.getName() );
ClassInfo itemClassInfo = index.getClassByName( itemName );
assertEquals( 2, itemClassInfo.annotations().size() );
//entity
assertHasAnnotation( index, itemName, JPADotNames.ENTITY );
assertHasAnnotation( index, itemName, JPADotNames.ENTITY_LISTENERS );
//listener
assertHasAnnotation( index, itemListenerName, JPADotNames.PRE_PERSIST );
assertHasAnnotation( index, itemListenerName, JPADotNames.POST_PERSIST );
//assert global configurations
assertHasAnnotation( index, PseudoJpaDotNames.DEFAULT_DELIMITED_IDENTIFIERS );
assertHasAnnotation( index, PseudoJpaDotNames.DEFAULT_ACCESS );
assertHasAnnotation( index, PseudoJpaDotNames.DEFAULT_ENTITY_LISTENERS );
assertHasAnnotation( index, PseudoJpaDotNames.DEFAULT_PRE_PERSIST );
assertHasAnnotation( index, PseudoJpaDotNames.DEFAULT_POST_PERSIST );
}
}

View File

@ -1,13 +0,0 @@
package org.hibernate.metamodel.source.annotations.xml.mocker;
import org.junit.Test;
/**
* @author Strong Liu
*/
public class IndexBuilderTest extends AbstractMockerTest {
@Test
public void test() {
IndexBuilder builder = getIndexBuilder();
}
}

View File

@ -1,39 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.xml.mocker;
/**
* @author Strong Liu
*/
public class Item {
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}

View File

@ -1,32 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.xml.mocker;
/**
* @author Strong Liu
*/
public class ItemListener {
public void prePersist(){}
public void postPersist(){}
}

View File

@ -1,252 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.xml.mocker;
import java.util.List;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationValue;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.Index;
import org.junit.Test;
import org.hibernate.internal.jaxb.mapping.orm.JaxbEntity;
import org.hibernate.metamodel.source.annotations.JPADotNames;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
/**
* @author Strong Liu
*/
public class OverrideTest extends AbstractMockerTest {
@Override
protected Class[] getAnnotatedClasses() {
return new Class[] {
Author.class,
Book.class,
Topic.class
};
}
@Test
public void testPersistenceUnitMetadataMetadataComplete() {
JaxbEntity author = new JaxbEntity();
author.setClazz( Author.class.getName() );
IndexBuilder indexBuilder = getIndexBuilder();
EntityMappingsMocker.Default defaults = new EntityMappingsMocker.Default();
defaults.setMetadataComplete( true );
EntityMocker entityMocker = new EntityMocker( indexBuilder, author, defaults );
entityMocker.preProcess();
entityMocker.process();
Index index = indexBuilder.build( new EntityMappingsMocker.Default() );
DotName className = DotName.createSimple( Author.class.getName() );
ClassInfo classInfo = index.getClassByName( className );
assertEquals( 1, classInfo.annotations().size() );
assertHasAnnotation( index, className, JPADotNames.ENTITY );
}
@Test
public void testEntityMetadataComplete() {
Index index = getMockedIndex( "entity-metadata-complete.xml" );
DotName authorName = DotName.createSimple( Author.class.getName() );
ClassInfo authorClassInfo = index.getClassByName( authorName );
assertHasAnnotation( index, authorName, JPADotNames.ENTITY );
assertHasAnnotation( index, authorName, JPADotNames.ID_CLASS );
assertEquals( 2, authorClassInfo.annotations().size() );
DotName bookName = DotName.createSimple( Book.class.getName() );
assertHasAnnotation( index, bookName, JPADotNames.ENTITY );
}
@Test
public void testOverrideToMappedSuperClass() {
Index index = getMockedIndex( "override-to-mappedsuperclass.xml" );
index.printAnnotations();
DotName authorName = DotName.createSimple( Author.class.getName() );
assertHasAnnotation( index, authorName, JPADotNames.ENTITY );
assertHasNoAnnotation( index, authorName, JPADotNames.TABLE );
DotName bookName = DotName.createSimple( Book.class.getName() );
assertHasAnnotation( index, bookName, JPADotNames.MAPPED_SUPERCLASS );
assertHasNoAnnotation( index, bookName, JPADotNames.TABLE );
}
@Test
public void testPersistenceUnitDefaultsCascadePersistInAnnotation() {
JaxbEntity author = new JaxbEntity();
author.setClazz( Author.class.getName() );
IndexBuilder indexBuilder = getIndexBuilder();
EntityMappingsMocker.Default defaults = new EntityMappingsMocker.Default();
defaults.setCascadePersist( true );
EntityMocker entityMocker = new EntityMocker( indexBuilder, author, defaults );
entityMocker.preProcess();
entityMocker.process();
Index index = indexBuilder.build( new EntityMappingsMocker.Default() );
DotName className = DotName.createSimple( Author.class.getName() );
assertAnnotationValue(
index, className, JPADotNames.ONE_TO_MANY, new CascadeAnnotationValueChecker( "PERSIST", "MERGE" )
);
}
@Test
public void testPersistenceUnitDefaultsCascadePersistInXML() {
Index index = getMockedIndex( "AttributeOverride.xml" );
DotName className = DotName.createSimple( Author.class.getName() );
assertAnnotationValue(
index,
className,
JPADotNames.ONE_TO_MANY,
new CascadeAnnotationValueChecker( new String[] { "PERSIST", "ALL" } )
);
}
protected class CascadeAnnotationValueChecker implements AnnotationValueChecker {
private String[] expected = new String[0];
public CascadeAnnotationValueChecker(String... expected) {
this.expected = expected;
}
@Override
public void check(AnnotationInstance annotationInstance) {
AnnotationValue cascadeValue = annotationInstance.value( "cascade" );
assertNotNull(
"Cascade is null in @OneToMany, but should be added a Cascade persist", cascadeValue
);
String[] enumArray = cascadeValue.asEnumArray();
assertEquals( expected.length, enumArray.length );
assertArrayEquals( expected, enumArray );
}
}
/**
* Entity has a @AttributeOverride on property topic
* and this property also has a <attribute-override> in orm.xml but with different name
* by jpa override rules, this two attribute-override should be merged into one @AttributeOverrides
*/
@Test
public void testAttributeOverride() {
Index index = getMockedIndex( "AttributeOverride.xml" );
DotName className = DotName.createSimple( Book.class.getName() );
index.printAnnotations();
assertHasNoAnnotation(
index,
className,
JPADotNames.ATTRIBUTE_OVERRIDE
);
assertAnnotationValue(
index,
className,
JPADotNames.ATTRIBUTE_OVERRIDES, new AnnotationValueChecker() {
@Override
public void check(AnnotationInstance annotationInstance) {
AnnotationValue value = annotationInstance.value();
assertNotNull( value );
AnnotationInstance[] annotationInstances = value.asNestedArray();
assertEquals( 2, annotationInstances.length );
AnnotationInstance ai = annotationInstances[0];
String name = ai.value( "name" ).asString();
AnnotationValue columnValue = ai.value( "column" ).asNested().value( "name" );
if ( name.equals( "title" ) ) {
assertEquals( "TOC_TITLE", columnValue.asString() );
}
else if ( name.equals( "summary" ) ) {
assertEquals( "TOPIC_SUMMARY", columnValue.asString() );
}
else {
fail( "AttributeOverride's name is " + name + ", should be either 'title' or 'summary'" );
}
}
}
);
}
@Test
public void testSchemaInPersistenceMetadata() {
Index index = getMockedIndex( "default-schema.xml" );
index.printAnnotations();
//Global Configuration should be accessed like this, not from ClassInfo
List<AnnotationInstance> annotationInstanceList = index.getAnnotations( JPADotNames.TABLE_GENERATOR );
assertNotNull( annotationInstanceList );
assertEquals( 1, annotationInstanceList.size() );
AnnotationInstance generator = annotationInstanceList.get( 0 );
assertEquals( "TABLE_GEN", generator.value( "name" ).asString() );
assertEquals( "ANNOTATION_CATALOG", generator.value( "catalog" ).asString() );
assertEquals( "ANNOTATION_SCHEMA", generator.value( "schema" ).asString() );
annotationInstanceList = index.getAnnotations( JPADotNames.SEQUENCE_GENERATOR );
assertNotNull( annotationInstanceList );
assertEquals( 1, annotationInstanceList.size() );
generator = annotationInstanceList.get( 0 );
assertEquals( "SEQ_GEN", generator.value( "name" ).asString() );
assertEquals( "XML_CATALOG", generator.value( "catalog" ).asString() );
assertEquals( "XML_SCHEMA", generator.value( "schema" ).asString() );
assertEquals( 123, generator.value( "initialValue" ).asInt() );
//Book and Author and Topic are all not defined @Table
//but orm xml defines default schema and catalog in persistence-unit-metadata
//so, we have to mock @Table for entities, Book and Author but not Topic which is a Embeddable
annotationInstanceList = index.getAnnotations( JPADotNames.TABLE );
assertNotNull( annotationInstanceList );
assertEquals( 2, annotationInstanceList.size() );
for ( AnnotationInstance table : annotationInstanceList ) {
assertEquals( "XML_CATALOG", table.value( "catalog" ).asString() );
assertEquals( "XML_SCHEMA", table.value( "schema" ).asString() );
}
}
@Test
public void testSchemaInEntityMapping() {
Index index = getMockedIndex( "default-schema2.xml" );
index.printAnnotations();
//Global Configuration should be accessed like this, not from ClassInfo
List<AnnotationInstance> annotationInstanceList = index.getAnnotations( JPADotNames.TABLE_GENERATOR );
assertNotNull( annotationInstanceList );
assertEquals( 1, annotationInstanceList.size() );
AnnotationInstance generator = annotationInstanceList.get( 0 );
assertEquals( "TABLE_GEN", generator.value( "name" ).asString() );
assertEquals( "ANNOTATION_CATALOG", generator.value( "catalog" ).asString() );
assertEquals( "ANNOTATION_SCHEMA", generator.value( "schema" ).asString() );
annotationInstanceList = index.getAnnotations( JPADotNames.SEQUENCE_GENERATOR );
assertNotNull( annotationInstanceList );
assertEquals( 1, annotationInstanceList.size() );
generator = annotationInstanceList.get( 0 );
assertEquals( "SEQ_GEN", generator.value( "name" ).asString() );
assertNull( generator.value( "catalog" ) );
assertNull( generator.value( "schema" ) );
assertEquals( 123, generator.value( "initialValue" ).asInt() );
annotationInstanceList = index.getAnnotations( JPADotNames.TABLE );
assertNotNull( annotationInstanceList );
assertEquals( 0, annotationInstanceList.size() );
}
}

View File

@ -1,51 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.xml.mocker;
import javax.persistence.AccessType;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.Index;
import org.junit.Test;
import org.hibernate.metamodel.source.annotations.xml.PseudoJpaDotNames;
import static org.junit.Assert.assertEquals;
/**
* @author Strong Liu
*/
public class PersistenceMetadataMockerTest extends AbstractMockerTest {
@Test
public void testPersistenceMetadata() {
Index index = getMockedIndex( "persistence-metadata.xml" );
assertHasAnnotation( index, null, PseudoJpaDotNames.DEFAULT_ACCESS, 1 );
assertAnnotationValue(index,null, PseudoJpaDotNames.DEFAULT_ACCESS,new AnnotationValueChecker(){
@Override
public void check(AnnotationInstance annotationInstance) {
assertEquals( AccessType.FIELD.toString(), annotationInstance.value().asEnum());
}
});
}
}

View File

@ -1,60 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.xml.mocker;
import javax.persistence.Embeddable;
/**
* @author Strong Liu
*/
@Embeddable
public class Topic {
private String title;
private String summary;
private int position;
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}

View File

@ -1,79 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.annotations.xml.mocker;
import java.io.InputStream;
import java.net.URL;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.jboss.logging.Logger;
import org.xml.sax.SAXException;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.jaxb.JaxbRoot;
import org.hibernate.internal.jaxb.Origin;
import org.hibernate.service.classloading.spi.ClassLoaderService;
/**
* @author Hardy Ferentschik
*/
public class XmlHelper {
private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, XmlHelper.class.getName() );
private XmlHelper() {
}
public static <T> JaxbRoot<T> unmarshallXml(String fileName, String schemaName, Class<T> clazz, ClassLoaderService classLoaderService)
throws JAXBException {
Schema schema = getMappingSchema( schemaName, classLoaderService );
InputStream in = classLoaderService.locateResourceStream( fileName );
JAXBContext jc = JAXBContext.newInstance( clazz );
Unmarshaller unmarshaller = jc.createUnmarshaller();
unmarshaller.setSchema( schema );
StreamSource stream = new StreamSource( in );
JAXBElement<T> elem = unmarshaller.unmarshal( stream, clazz );
Origin origin = new Origin( null, fileName );
return new JaxbRoot<T>( elem.getValue(), origin );
}
private static Schema getMappingSchema(String schemaVersion, ClassLoaderService classLoaderService) {
URL schemaUrl = classLoaderService.locateResource( schemaVersion );
SchemaFactory sf = SchemaFactory.newInstance( javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI );
Schema schema = null;
try {
schema = sf.newSchema( schemaUrl );
}
catch ( SAXException e ) {
LOG.debugf( "Unable to create schema for %s: %s", schemaVersion, e.getMessage() );
}
return schema;
}
}

View File

@ -1,32 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.internal;
/**
* @author Hardy Ferentschik
*/
public class Foo {
}

View File

@ -1,110 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.internal;
import java.util.Iterator;
import org.junit.Test;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.metamodel.Metadata;
import org.hibernate.metamodel.MetadataSources;
import org.hibernate.metamodel.SessionFactoryBuilder;
import org.hibernate.metamodel.binding.FetchProfile;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertTrue;
/**
* @author Hardy Ferentschik
*/
public class MetadataImplTest extends BaseUnitTestCase {
@Test(expected = IllegalArgumentException.class)
public void testAddingNullClass() {
MetadataSources sources = new MetadataSources( new ServiceRegistryBuilder().buildServiceRegistry() );
sources.addClass( null );
sources.buildMetadata();
}
@Test(expected = IllegalArgumentException.class)
public void testAddingNullPackageName() {
MetadataSources sources = new MetadataSources( new ServiceRegistryBuilder().buildServiceRegistry() );
sources.addPackage( null );
sources.buildMetadata();
}
@Test(expected = HibernateException.class)
public void testAddingNonExistingPackageName() {
MetadataSources sources = new MetadataSources( new ServiceRegistryBuilder().buildServiceRegistry() );
sources.addPackage( "not.a.package" );
sources.buildMetadata();
}
@Test
public void testAddingPackageName() {
MetadataSources sources = new MetadataSources( new ServiceRegistryBuilder().buildServiceRegistry() );
sources.addPackage( "org.hibernate.metamodel.source.internal" );
MetadataImpl metadata = (MetadataImpl) sources.buildMetadata();
assertFetchProfile( metadata );
}
@Test
public void testAddingPackageNameWithTrailingDot() {
MetadataSources sources = new MetadataSources( new ServiceRegistryBuilder().buildServiceRegistry() );
sources.addPackage( "org.hibernate.metamodel.source.internal." );
MetadataImpl metadata = (MetadataImpl) sources.buildMetadata();
assertFetchProfile( metadata );
}
@Test
public void testGettingSessionFactoryBuilder() {
MetadataSources sources = new MetadataSources( new ServiceRegistryBuilder().buildServiceRegistry() );
Metadata metadata = sources.buildMetadata();
SessionFactoryBuilder sessionFactoryBuilder = metadata.getSessionFactoryBuilder();
assertNotNull( sessionFactoryBuilder );
assertTrue( SessionFactoryBuilderImpl.class.isInstance( sessionFactoryBuilder ) );
SessionFactory sessionFactory = metadata.buildSessionFactory();
assertNotNull( sessionFactory );
}
private void assertFetchProfile(MetadataImpl metadata) {
Iterator<FetchProfile> profiles = metadata.getFetchProfiles().iterator();
assertTrue( profiles.hasNext() );
FetchProfile profile = profiles.next();
assertEquals( "wrong profile name", "package-configured-profile", profile.getName() );
assertFalse( profiles.hasNext() );
}
}

View File

@ -1,197 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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.metamodel.source.internal;
import java.io.Serializable;
import java.util.Iterator;
import org.junit.Test;
import org.hibernate.CallbackException;
import org.hibernate.EmptyInterceptor;
import org.hibernate.EntityMode;
import org.hibernate.Interceptor;
import org.hibernate.ObjectNotFoundException;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.metamodel.MetadataSources;
import org.hibernate.metamodel.SessionFactoryBuilder;
import org.hibernate.proxy.EntityNotFoundDelegate;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.type.Type;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertSame;
import static junit.framework.Assert.assertTrue;
/**
* @author Gail Badner
*/
public class SessionFactoryBuilderImplTest extends BaseUnitTestCase {
@Test
public void testGettingSessionFactoryBuilder() {
SessionFactoryBuilder sessionFactoryBuilder = getSessionFactoryBuilder();
assertNotNull( sessionFactoryBuilder );
assertTrue( SessionFactoryBuilderImpl.class.isInstance( sessionFactoryBuilder ) );
}
@Test
public void testBuildSessionFactoryWithDefaultOptions() {
SessionFactoryBuilder sessionFactoryBuilder = getSessionFactoryBuilder();
SessionFactory sessionFactory = sessionFactoryBuilder.buildSessionFactory();
assertSame( EmptyInterceptor.INSTANCE, sessionFactory.getSessionFactoryOptions().getInterceptor() );
assertTrue( EntityNotFoundDelegate.class.isInstance(
sessionFactory.getSessionFactoryOptions().getEntityNotFoundDelegate()
) );
sessionFactory.close();
}
@Test
public void testBuildSessionFactoryWithUpdatedOptions() {
SessionFactoryBuilder sessionFactoryBuilder = getSessionFactoryBuilder();
Interceptor interceptor = new AnInterceptor();
EntityNotFoundDelegate entityNotFoundDelegate = new EntityNotFoundDelegate() {
@Override
public void handleEntityNotFound(String entityName, Serializable id) {
throw new ObjectNotFoundException( id, entityName );
}
};
sessionFactoryBuilder.with( interceptor );
sessionFactoryBuilder.with( entityNotFoundDelegate );
SessionFactory sessionFactory = sessionFactoryBuilder.buildSessionFactory();
assertSame( interceptor, sessionFactory.getSessionFactoryOptions().getInterceptor() );
assertSame( entityNotFoundDelegate, sessionFactory.getSessionFactoryOptions().getEntityNotFoundDelegate() );
sessionFactory.close();
}
private SessionFactoryBuilder getSessionFactoryBuilder() {
MetadataSources sources = new MetadataSources( new ServiceRegistryBuilder().buildServiceRegistry() );
sources.addAnnotatedClass( SimpleEntity.class );
MetadataImpl metadata = (MetadataImpl) sources.buildMetadata();
return metadata.getSessionFactoryBuilder();
}
private static class AnInterceptor implements Interceptor {
private static final Interceptor INSTANCE = EmptyInterceptor.INSTANCE;
@Override
public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
throws CallbackException {
return INSTANCE.onLoad( entity, id, state, propertyNames, types );
}
@Override
public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types)
throws CallbackException {
return INSTANCE.onFlushDirty( entity, id, currentState, previousState, propertyNames, types );
}
@Override
public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
throws CallbackException {
return INSTANCE.onSave( entity, id, state, propertyNames, types );
}
@Override
public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
throws CallbackException {
INSTANCE.onDelete( entity, id, state, propertyNames, types );
}
@Override
public void onCollectionRecreate(Object collection, Serializable key) throws CallbackException {
INSTANCE.onCollectionRecreate( collection, key );
}
@Override
public void onCollectionRemove(Object collection, Serializable key) throws CallbackException {
INSTANCE.onCollectionRemove( collection, key );
}
@Override
public void onCollectionUpdate(Object collection, Serializable key) throws CallbackException {
INSTANCE.onCollectionUpdate( collection, key );
}
@Override
public void preFlush(Iterator entities) throws CallbackException {
INSTANCE.preFlush( entities );
}
@Override
public void postFlush(Iterator entities) throws CallbackException {
INSTANCE.postFlush( entities );
}
@Override
public Boolean isTransient(Object entity) {
return INSTANCE.isTransient( entity );
}
@Override
public int[] findDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
return INSTANCE.findDirty( entity, id, currentState, previousState, propertyNames, types );
}
@Override
public Object instantiate(String entityName, EntityMode entityMode, Serializable id)
throws CallbackException {
return INSTANCE.instantiate( entityName, entityMode, id );
}
@Override
public String getEntityName(Object object) throws CallbackException {
return INSTANCE.getEntityName( object );
}
@Override
public Object getEntity(String entityName, Serializable id) throws CallbackException {
return INSTANCE.getEntity( entityName, id );
}
@Override
public void afterTransactionBegin(Transaction tx) {
INSTANCE.afterTransactionBegin( tx );
}
@Override
public void beforeTransactionCompletion(Transaction tx) {
INSTANCE.beforeTransactionCompletion( tx );
}
@Override
public void afterTransactionCompletion(Transaction tx) {
INSTANCE.afterTransactionCompletion( tx );
}
@Override
public String onPrepareStatement(String sql) {
return INSTANCE.onPrepareStatement( sql );
}
}
}

View File

@ -1,60 +0,0 @@
/*
* 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.metamodel.source.internal;
import javax.persistence.Entity;
import javax.persistence.Id;
/**
* @author Steve Ebersole
*/
@Entity
public class SimpleEntity {
@Id
private Long id;
private String name;
public SimpleEntity() {
}
public SimpleEntity(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -1,31 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, 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
*/
@FetchProfile(name = "package-configured-profile", fetchOverrides = {
@FetchProfile.FetchOverride(entity = Foo.class, association = "bar", mode = FetchMode.JOIN)
})
package org.hibernate.metamodel.source.internal;
import org.hibernate.annotations.FetchMode;
import org.hibernate.annotations.FetchProfile;