HHH-7780 - Proper enumeration named/ordinal discovery

This commit is contained in:
Lukasz Antoniak 2012-11-14 16:15:43 +01:00
parent 65093aabf0
commit 5b004e4cbd
7 changed files with 486 additions and 49 deletions

View File

@ -32,78 +32,110 @@ import org.hibernate.envers.entities.mapper.SimpleMapperBuilder;
import org.hibernate.mapping.SimpleValue;
import org.hibernate.mapping.Value;
import org.hibernate.type.BasicType;
import org.hibernate.type.CustomType;
import org.hibernate.type.EnumType;
import org.hibernate.type.SerializableToBlobType;
import org.hibernate.type.Type;
import org.hibernate.usertype.DynamicParameterizedType;
/**
* Generates metadata for basic properties: immutable types (including enums).
* @author Adam Warski (adam at warski dot org)
*/
public final class BasicMetadataGenerator {
@SuppressWarnings({"unchecked"})
@SuppressWarnings({ "unchecked" })
boolean addBasic(Element parent, PropertyAuditingData propertyAuditingData,
Value value, SimpleMapperBuilder mapper, boolean insertable, boolean key) {
Type type = value.getType();
if (type instanceof BasicType || type instanceof SerializableToBlobType ||
"org.hibernate.type.PrimitiveByteArrayBlobType".equals(type.getClass().getName())) {
if (parent != null) {
boolean addNestedType = (value instanceof SimpleValue) && ((SimpleValue) value).getTypeParameters() != null;
if ( type instanceof BasicType || type instanceof SerializableToBlobType ||
"org.hibernate.type.PrimitiveByteArrayBlobType".equals( type.getClass().getName() ) ) {
if ( parent != null ) {
boolean addNestedType = ( value instanceof SimpleValue ) && ( (SimpleValue) value ).getTypeParameters() != null;
String typeName = type.getName();
if (typeName == null) {
typeName = type.getClass().getName();
}
String typeName = type.getName();
if ( typeName == null ) {
typeName = type.getClass().getName();
}
Element prop_mapping = MetadataTools.addProperty(parent, propertyAuditingData.getName(),
addNestedType ? null : typeName, propertyAuditingData.isForceInsertable() || insertable, key);
MetadataTools.addColumns(prop_mapping, value.getColumnIterator());
Element prop_mapping = MetadataTools.addProperty(
parent, propertyAuditingData.getName(),
addNestedType ? null : typeName, propertyAuditingData.isForceInsertable() || insertable, key
);
MetadataTools.addColumns( prop_mapping, value.getColumnIterator() );
if (addNestedType) {
Properties typeParameters = ((SimpleValue) value).getTypeParameters();
Element type_mapping = prop_mapping.addElement("type");
type_mapping.addAttribute("name", typeName);
if ( addNestedType ) {
Properties typeParameters = ( (SimpleValue) value ).getTypeParameters();
Element type_mapping = prop_mapping.addElement( "type" );
type_mapping.addAttribute( "name", typeName );
if ( "org.hibernate.type.EnumType".equals( typeName ) ) {
// Proper handling of enumeration type
mapEnumerationType( type_mapping, type, typeParameters );
}
else {
// By default copying all Hibernate properties
for ( Object object : typeParameters.keySet() ) {
String keyType = (String) object;
String property = typeParameters.getProperty( keyType );
for (Object object : typeParameters.keySet()) {
String keyType = (String) object;
String property = typeParameters.getProperty(keyType);
if ( property != null ) {
type_mapping.addElement( "param" ).addAttribute( "name", keyType ).setText( property );
}
}
}
}
}
if (property != null) {
Element type_param = type_mapping.addElement("param");
type_param.addAttribute("name", keyType);
type_param.setText(property);
}
}
}
}
// A null mapper means that we only want to add xml mappings
if (mapper != null) {
mapper.add(propertyAuditingData.getPropertyData());
}
} else {
// A null mapper means that we only want to add xml mappings
if ( mapper != null ) {
mapper.add( propertyAuditingData.getPropertyData() );
}
}
else {
return false;
}
return true;
}
@SuppressWarnings({"unchecked"})
boolean addManyToOne(Element parent, PropertyAuditingData propertyAuditingData, Value value,
SimpleMapperBuilder mapper) {
Type type = value.getType();
private void mapEnumerationType(Element parent, Type type, Properties parameters) {
if ( parameters.getProperty( EnumType.ENUM ) != null ) {
parent.addElement( "param" ).addAttribute( "name", EnumType.ENUM ).setText( parameters.getProperty( EnumType.ENUM ) );
}
else {
parent.addElement( "param" ).addAttribute( "name", EnumType.ENUM ).setText( type.getReturnedClass().getName() );
}
if ( parameters.getProperty( EnumType.NAMED ) != null ) {
parent.addElement( "param" ).addAttribute( "name", EnumType.NAMED ).setText( parameters.getProperty( EnumType.NAMED ) );
}
else if ( parameters.get( DynamicParameterizedType.XPROPERTY ) != null ) {
// Case of annotations.
parent.addElement( "param" ).addAttribute( "name", EnumType.NAMED )
.setText( "" + !( (EnumType) ( (CustomType) type ).getUserType() ).isOrdinal() );
}
else {
// Otherwise we assume that the choice between ordinal and named representation has been omitted.
// Call to EnumType#isOrdinal() would always return the default Types.INTEGER. We let Hibernate
// to choose the proper strategy during runtime.
}
}
// A null mapper occurs when adding to composite-id element
Element manyToOneElement = parent.addElement(mapper != null ? "many-to-one" : "key-many-to-one");
manyToOneElement.addAttribute("name", propertyAuditingData.getName());
manyToOneElement.addAttribute("class", type.getName());
MetadataTools.addColumns(manyToOneElement, value.getColumnIterator());
@SuppressWarnings({ "unchecked" })
boolean addManyToOne(Element parent, PropertyAuditingData propertyAuditingData, Value value, SimpleMapperBuilder mapper) {
Type type = value.getType();
// A null mapper means that we only want to add xml mappings
if (mapper != null) {
mapper.add(propertyAuditingData.getPropertyData());
}
return true;
}
// A null mapper occurs when adding to composite-id element
Element manyToOneElement = parent.addElement( mapper != null ? "many-to-one" : "key-many-to-one" );
manyToOneElement.addAttribute( "name", propertyAuditingData.getName() );
manyToOneElement.addAttribute( "class", type.getName() );
MetadataTools.addColumns( manyToOneElement, value.getColumnIterator() );
// A null mapper means that we only want to add xml mappings
if ( mapper != null ) {
mapper.add( propertyAuditingData.getPropertyData() );
}
return true;
}
}

View File

@ -0,0 +1,94 @@
package org.hibernate.envers.test.entities.customtype;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.hibernate.envers.Audited;
/**
* @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com)
*/
@Entity
@Audited
public class EnumTypeEntity {
public static enum E1 { X, Y }
public static enum E2 { A, B }
@Id
@GeneratedValue
private Long id;
@Enumerated(EnumType.STRING)
private E1 enum1;
@Enumerated(EnumType.ORDINAL)
private E2 enum2;
public EnumTypeEntity() {
}
public EnumTypeEntity(E1 enum1, E2 enum2) {
this.enum1 = enum1;
this.enum2 = enum2;
}
public EnumTypeEntity(E1 enum1, E2 enum2, Long id) {
this.enum1 = enum1;
this.enum2 = enum2;
this.id = id;
}
@Override
public boolean equals(Object o) {
if ( this == o ) return true;
if ( ! ( o instanceof EnumTypeEntity ) ) return false;
EnumTypeEntity that = (EnumTypeEntity) o;
if ( enum1 != that.enum1 ) return false;
if ( enum2 != that.enum2 ) return false;
if ( id != null ? !id.equals( that.id ) : that.id != null ) return false;
return true;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + ( enum1 != null ? enum1.hashCode() : 0 );
result = 31 * result + ( enum2 != null ? enum2.hashCode() : 0 );
return result;
}
@Override
public String toString() {
return "EnumTypeEntity(id = " + id + ", enum1 = " + enum1 + ", enum2 = " + enum2 + ")";
}
public E1 getEnum1() {
return enum1;
}
public void setEnum1(E1 enum1) {
this.enum1 = enum1;
}
public E2 getEnum2() {
return enum2;
}
public void setEnum2(E2 enum2) {
this.enum2 = enum2;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}

View File

@ -0,0 +1,85 @@
package org.hibernate.envers.test.entities.customtype;
import java.io.Serializable;
import org.hibernate.envers.Audited;
/**
* @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com)
*/
@Audited
public class UnspecifiedEnumTypeEntity implements Serializable {
public static enum E1 { X, Y }
public static enum E2 { A, B }
private Long id;
private E1 enum1;
private E2 enum2;
public UnspecifiedEnumTypeEntity() {
}
public UnspecifiedEnumTypeEntity(E1 enum1, E2 enum2) {
this.enum1 = enum1;
this.enum2 = enum2;
}
public UnspecifiedEnumTypeEntity(E1 enum1, E2 enum2, Long id) {
this.enum1 = enum1;
this.enum2 = enum2;
this.id = id;
}
@Override
public boolean equals(Object o) {
if ( this == o ) return true;
if ( ! ( o instanceof UnspecifiedEnumTypeEntity ) ) return false;
UnspecifiedEnumTypeEntity that = (UnspecifiedEnumTypeEntity) o;
if ( enum1 != that.enum1 ) return false;
if ( enum2 != that.enum2 ) return false;
if ( id != null ? !id.equals( that.id ) : that.id != null ) return false;
return true;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + ( enum1 != null ? enum1.hashCode() : 0 );
result = 31 * result + ( enum2 != null ? enum2.hashCode() : 0 );
return result;
}
@Override
public String toString() {
return "UnspecifiedEnumTypeEntity(id = " + id + ", enum1 = " + enum1 + ", enum2 = " + enum2 + ")";
}
public E1 getEnum1() {
return enum1;
}
public void setEnum1(E1 enum1) {
this.enum1 = enum1;
}
public E2 getEnum2() {
return enum2;
}
public void setEnum2(E2 enum2) {
this.enum2 = enum2;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}

View File

@ -24,8 +24,10 @@
package org.hibernate.envers.test.integration.collection;
import java.util.Arrays;
import java.util.List;
import javax.persistence.EntityManager;
import org.junit.Assert;
import org.junit.Test;
import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase ;
@ -34,6 +36,7 @@ import org.hibernate.envers.test.entities.collection.EnumSetEntity;
import org.hibernate.envers.test.entities.collection.EnumSetEntity.E1;
import org.hibernate.envers.test.entities.collection.EnumSetEntity.E2;
import org.hibernate.envers.test.tools.TestTools;
import org.hibernate.testing.TestForIssue;
/**
* @author Adam Warski (adam at warski dot org)
@ -107,4 +110,16 @@ public class EnumSet extends BaseEnversJPAFunctionalTestCase {
assert rev2.getEnums2().equals(TestTools.makeSet(E2.A));
assert rev3.getEnums2().equals(TestTools.makeSet(E2.A));
}
@Test
@TestForIssue( jiraKey = "HHH-7780" )
public void testEnumRepresentation() {
EntityManager entityManager = getEntityManager();
List<Object[]> enums1 = entityManager.createNativeQuery( "SELECT enums1 FROM EnumSetEntity_enums1_AUD ORDER BY rev ASC" ).getResultList();
List<Object[]> enums2 = entityManager.createNativeQuery( "SELECT enums2 FROM EnumSetEntity_enums2_AUD ORDER BY rev ASC" ).getResultList();
entityManager.close();
Assert.assertEquals( Arrays.asList( "X", "Y", "X" ), enums1 );
Assert.assertEquals( Arrays.asList( 0 ), enums2 );
}
}

View File

@ -0,0 +1,47 @@
package org.hibernate.envers.test.integration.customtype;
import java.util.List;
import javax.persistence.EntityManager;
import org.junit.Assert;
import org.junit.Test;
import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase;
import org.hibernate.envers.test.Priority;
import org.hibernate.envers.test.entities.customtype.EnumTypeEntity;
import org.hibernate.testing.TestForIssue;
/**
* @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com)
*/
@TestForIssue( jiraKey = "HHH-7780" )
public class EnumTypeTest extends BaseEnversJPAFunctionalTestCase {
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class<?>[] { EnumTypeEntity.class };
}
@Test
@Priority(10)
public void initData() {
EntityManager em = getEntityManager();
em.getTransaction().begin();
EnumTypeEntity entity = new EnumTypeEntity( EnumTypeEntity.E1.X, EnumTypeEntity.E2.A );
em.persist( entity );
em.getTransaction().commit();
em.close();
}
@Test
public void testEnumRepresentation() {
EntityManager entityManager = getEntityManager();
List<Object[]> values = entityManager.createNativeQuery( "SELECT enum1, enum2 FROM EnumTypeEntity_AUD ORDER BY rev ASC" ).getResultList();
entityManager.close();
Assert.assertNotNull( values );
Assert.assertEquals( 1, values.size() );
Assert.assertArrayEquals( new Object[] { "X", 0 }, values.get( 0 ) );
}
}

View File

@ -0,0 +1,141 @@
package org.hibernate.envers.test.integration.customtype;
import java.util.Arrays;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.envers.test.BaseEnversFunctionalTestCase;
import org.hibernate.envers.test.Priority;
import org.hibernate.envers.test.entities.customtype.UnspecifiedEnumTypeEntity;
import org.hibernate.testing.RequiresDialect;
import org.hibernate.testing.TestForIssue;
/**
* @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com)
*/
@TestForIssue( jiraKey = "HHH-7780" )
@RequiresDialect( value = H2Dialect.class )
public class UnspecifiedEnumTypeTest extends BaseEnversFunctionalTestCase {
private Long id = null;
@Override
protected String[] getMappings() {
return new String[] { "mappings/customType/mappings.hbm.xml" };
}
@Override
protected void configure(Configuration configuration) {
super.configure( configuration );
configuration.setProperty( Environment.HBM2DDL_AUTO, "" );
}
@Test
@Priority(10)
public void prepareSchema() {
Session session = openSession();
dropSchema( session );
createSchema( session );
session.close();
}
@Test
@Priority(1)
public void dropSchema() {
dropSchema( session );
}
public void dropSchema(Session session) {
executeUpdateSafety( session, "alter table ENUM_ENTITY_AUD drop constraint FK_AUD_REV" );
executeUpdateSafety( session, "drop table ENUM_ENTITY if exists" );
executeUpdateSafety( session, "drop table ENUM_ENTITY_AUD if exists" );
executeUpdateSafety( session, "drop table REVINFO if exists" );
executeUpdateSafety( session, "drop sequence REVISION_GENERATOR" );
}
private void createSchema(Session session) {
executeUpdateSafety(
session,
"create table ENUM_ENTITY (ID bigint not null, enum1 varchar(255), enum2 integer, primary key (ID))"
);
executeUpdateSafety(
session,
"create table ENUM_ENTITY_AUD (ID bigint not null, REV integer not null, REVTYPE tinyint, enum1 varchar(255), enum2 integer, primary key (ID, REV))"
);
executeUpdateSafety(
session,
"create table REVINFO (REV integer not null, REVTSTMP bigint, primary key (REV))"
);
executeUpdateSafety(
session,
"alter table ENUM_ENTITY_AUD add constraint FK_AUD_REV foreign key (REV) references REVINFO"
);
executeUpdateSafety( session, "create sequence REVISION_GENERATOR start with 1 increment by 1" );
}
private void executeUpdateSafety(Session session, String query) {
try {
session.createSQLQuery( query ).executeUpdate();
}
catch ( Exception e ) {
}
}
@Test
@Priority(9)
public void initData() {
Session session = getSession();
// Revision 1
session.getTransaction().begin();
UnspecifiedEnumTypeEntity entity = new UnspecifiedEnumTypeEntity( UnspecifiedEnumTypeEntity.E1.X, UnspecifiedEnumTypeEntity.E2.A );
session.persist( entity );
session.getTransaction().commit();
id = entity.getId();
// Revision 2
session.getTransaction().begin();
entity = (UnspecifiedEnumTypeEntity) session.get( UnspecifiedEnumTypeEntity.class, entity.getId() );
entity.setEnum1( UnspecifiedEnumTypeEntity.E1.Y );
entity.setEnum2( UnspecifiedEnumTypeEntity.E2.B );
session.update( entity );
session.getTransaction().commit();
session.close();
}
@Test
@Priority(8)
public void testRevisionCount() {
Assert.assertEquals( Arrays.asList( 1, 2 ), getAuditReader().getRevisions( UnspecifiedEnumTypeEntity.class, id ) );
}
@Test
@Priority(7)
public void testHistoryOfEnums() {
UnspecifiedEnumTypeEntity ver1 = new UnspecifiedEnumTypeEntity( UnspecifiedEnumTypeEntity.E1.X, UnspecifiedEnumTypeEntity.E2.A, id );
UnspecifiedEnumTypeEntity ver2 = new UnspecifiedEnumTypeEntity( UnspecifiedEnumTypeEntity.E1.Y, UnspecifiedEnumTypeEntity.E2.B, id );
Assert.assertEquals( ver1, getAuditReader().find(UnspecifiedEnumTypeEntity.class, id, 1) );
Assert.assertEquals( ver2, getAuditReader().find(UnspecifiedEnumTypeEntity.class, id, 2) );
}
@Test
@Priority(6)
public void testEnumRepresentation() {
Session session = getSession();
List<Object[]> values = session.createSQLQuery( "SELECT enum1, enum2 FROM enum_entity_aud ORDER BY rev ASC" ).list();
session.close();
Assert.assertNotNull( values );
Assert.assertEquals( 2, values.size() );
Assert.assertArrayEquals( new Object[] { "X", 0 }, values.get( 0 ) );
Assert.assertArrayEquals( new Object[] { "Y", 1 }, values.get( 1 ) );
}
}

View File

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="WINDOWS-1251"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="org.hibernate.envers.test.entities.customtype.UnspecifiedEnumTypeEntity" table="ENUM_ENTITY">
<id name="id" column="ID" type="long">
<generator class="increment" />
</id>
<property name="enum1">
<type name="org.hibernate.type.EnumType">
<!-- We omit choice between named and ordinal. -->
<!--<param name="useNamed">true</param>-->
<param name="enumClass">org.hibernate.envers.test.entities.customtype.UnspecifiedEnumTypeEntity$E1</param>
</type>
</property>
<property name="enum2">
<type name="org.hibernate.type.EnumType">
<!-- We omit choice between named and ordinal. -->
<!--<param name="useNamed">false</param>-->
<param name="enumClass">org.hibernate.envers.test.entities.customtype.UnspecifiedEnumTypeEntity$E2</param>
</type>
</property>
</class>
</hibernate-mapping>