More property DAO changes

git-svn-id: https://svn.alfresco.com/repos/alfresco-enterprise/alfresco/HEAD/root@15652 c4b6b30b-aa2e-2d43-bbcb-ca4b014f7261
This commit is contained in:
Derek Hulley
2009-08-10 09:33:20 +00:00
parent 1a04cecec8
commit 2401bfc93e
9 changed files with 465 additions and 300 deletions

View File

@@ -44,12 +44,13 @@ CREATE TABLE alf_prop_serializable_value
CREATE TABLE alf_prop_value CREATE TABLE alf_prop_value
( (
id BIGINT NOT NULL AUTO_INCREMENT, id BIGINT NOT NULL AUTO_INCREMENT,
actual_type_id BIGINT NOT NULL,
persisted_type TINYINT NOT NULL, persisted_type TINYINT NOT NULL,
long_value BIGINT NOT NULL, long_value BIGINT NOT NULL,
INDEX idx_alf_prop_val (persisted_type, long_value), INDEX idx_alf_prop_per (persisted_type, long_value),
INDEX idx_alf_prop_act (actual_type_id, long_value),
PRIMARY KEY (id) PRIMARY KEY (id)
) ENGINE=InnoDB; ) ENGINE=InnoDB;
-- --
-- Record script finish -- Record script finish
-- --

View File

@@ -35,7 +35,12 @@
</resultMap> </resultMap>
<resultMap id="result.PropertyValue" class="PropertyValue"> <resultMap id="result.PropertyValue" class="PropertyValue">
<result property="id" column="id" jdbcType="BIGINT" javaType="java.lang.Long"/> <result property="id" column="id" jdbcType="BIGINT" javaType="java.lang.Long"/>
<result property="actualTypeId" column="actual_type_id" jdbcType="BIGINT" javaType="java.lang.Long"/>
<result property="persistedType" column="persisted_type" jdbcType="TINYINT" javaType="java.lang.Short"/>
<result property="longValue" column="long_value" jdbcType="BIGINT" javaType="java.lang.Long"/> <result property="longValue" column="long_value" jdbcType="BIGINT" javaType="java.lang.Long"/>
<result property="doubleValue" column="double_value" jdbcType="DOUBLE" javaType="java.lang.Double"/>
<result property="stringValue" column="string_value" jdbcType="VARCHAR" javaType="java.lang.String"/>
<result property="serializableValue" column="serializable_value" jdbcType="BLOB" javaType="java.lang.Object"/>
</resultMap> </resultMap>
<!-- --> <!-- -->
@@ -72,8 +77,8 @@
</sql> </sql>
<sql id="insert.PropertyValue.AutoIncrement"> <sql id="insert.PropertyValue.AutoIncrement">
insert into alf_prop_value (persisted_type, long_value) insert into alf_prop_value (actual_type_id, persisted_type, long_value)
values (#persistedType#, #longValue#) values (#actualTypeId#, #persistedType#, #longValue#)
</sql> </sql>
<!-- --> <!-- -->
@@ -111,8 +116,8 @@
id = #id# id = #id#
</select> </select>
<!-- Get the property string value by string --> <!-- Get the property string value by value -->
<select id="select.PropertyStringValueByString" parameterClass="PropertyStringValue" resultMap="result.PropertyStringValue"> <select id="select.PropertyStringValueByValue" parameterClass="PropertyStringValue" resultMap="result.PropertyStringValue">
select select
* *
from from
@@ -121,7 +126,7 @@
string_value = #stringValue# string_value = #stringValue#
</select> </select>
<!-- Get a property simple value by ID --> <!-- Get a property double value by ID -->
<select id="select.PropertyDoubleValueByID" parameterClass="PropertyDoubleValue" resultMap="result.PropertyDoubleValue"> <select id="select.PropertyDoubleValueByID" parameterClass="PropertyDoubleValue" resultMap="result.PropertyDoubleValue">
select select
* *
@@ -131,7 +136,7 @@
id = #id# id = #id#
</select> </select>
<!-- Get the property string value by string --> <!-- Get the property double value by value -->
<select id="select.PropertyDoubleValueByValue" parameterClass="PropertyDoubleValue" resultMap="result.PropertyDoubleValue"> <select id="select.PropertyDoubleValueByValue" parameterClass="PropertyDoubleValue" resultMap="result.PropertyDoubleValue">
select select
* *
@@ -141,4 +146,76 @@
double_value = #doubleValue# double_value = #doubleValue#
</select> </select>
<!-- Get the property value by value in alf_prop_value -->
<select id="select.PropertyValueByLocalValue" parameterClass="PropertyValue" resultMap="result.PropertyValue">
select
pv.id as id,
pv.actual_type_id as actual_type_id,
pv.persisted_type as persisted_type,
pv.long_value as long_value,
null as double_value,
null as string_value,
null as serializable_value
from
alf_prop_value pv
where
pv.actual_type_id = #actualTypeId# and
pv.long_value = #longValue#
</select>
<!-- Get the property value by value in alf_prop_double_value -->
<select id="select.PropertyValueByDoubleValue" parameterClass="PropertyValue" resultMap="result.PropertyValue">
select
pv.id as id,
pv.actual_type_id as actual_type_id,
pv.persisted_type as persisted_type,
pv.long_value as long_value,
dv.double_value as double_value,
null as string_value,
null as serializable_value
from
alf_prop_value pv
join alf_prop_double_value dv on (dv.id = pv.long_value and pv.persisted_type = #persistedType#)
where
pv.actual_type_id = #actualTypeId# and
dv.double_value = #doubleValue#
</select>
<!-- Get the property value by value in alf_prop_string_value -->
<select id="select.PropertyValueByStringValue" parameterClass="PropertyValue" resultMap="result.PropertyValue">
select
pv.id as id,
pv.actual_type_id as actual_type_id,
pv.persisted_type as persisted_type,
pv.long_value as long_value,
null as double_value,
sv.string_value as string_value,
null as serializable_value
from
alf_prop_value pv
join alf_prop_string_value sv on (sv.id = pv.long_value and pv.persisted_type = #persistedType#)
where
pv.actual_type_id = #actualTypeId# and
sv.string_value = #stringValue#
</select>
<!-- Get the property value by ID -->
<select id="select.PropertyValueById" parameterClass="PropertyValue" resultMap="result.PropertyValue">
select
pv.id as id,
pv.actual_type_id as actual_type_id,
pv.persisted_type as persisted_type,
pv.long_value as long_value,
dv.double_value as double_value,
sv.string_value as string_value,
serv.serializable_value as serializable_value
from
alf_prop_value pv
left join alf_prop_double_value dv on (dv.id = pv.long_value and pv.persisted_type = 2)
left join alf_prop_string_value sv on (sv.id = pv.long_value and pv.persisted_type = 3)
left join alf_prop_serializable_value serv on (serv.id = pv.long_value and pv.persisted_type = 4)
where
pv.id = #id#
</select>
</sqlMap> </sqlMap>

View File

@@ -60,7 +60,6 @@ public abstract class AbstractContentDataDAOImpl implements ContentDataDAO
* Content URL IDs to delete before final commit. * Content URL IDs to delete before final commit.
*/ */
private static final String KEY_PRE_COMMIT_CONTENT_URL_DELETIONS = "AbstractContentDataDAOImpl.PreCommitContentUrlDeletions"; private static final String KEY_PRE_COMMIT_CONTENT_URL_DELETIONS = "AbstractContentDataDAOImpl.PreCommitContentUrlDeletions";
private static final Long CACHE_NULL_LONG = Long.MIN_VALUE;
private static Log logger = LogFactory.getLog(AbstractContentDataDAOImpl.class); private static Log logger = LogFactory.getLog(AbstractContentDataDAOImpl.class);

View File

@@ -29,7 +29,7 @@ import java.io.Serializable;
import org.alfresco.error.AlfrescoRuntimeException; import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.repo.cache.SimpleCache; import org.alfresco.repo.cache.SimpleCache;
import org.alfresco.repo.cache.lookup.EntityLookupCache; import org.alfresco.repo.cache.lookup.EntityLookupCache;
import org.alfresco.repo.cache.lookup.EntityLookupCache.EntityLookupCallbackDAO; import org.alfresco.repo.cache.lookup.EntityLookupCache.EntityLookupCallbackDAOAdaptor;
import org.alfresco.repo.domain.CrcHelper; import org.alfresco.repo.domain.CrcHelper;
import org.alfresco.repo.domain.propval.PropertyValueEntity.PersistedType; import org.alfresco.repo.domain.propval.PropertyValueEntity.PersistedType;
import org.alfresco.util.Pair; import org.alfresco.util.Pair;
@@ -205,7 +205,7 @@ public abstract class AbstractPropertyValueDAOImpl implements PropertyValueDAO
/** /**
* Callback for <b>alf_prop_class</b> DAO. * Callback for <b>alf_prop_class</b> DAO.
*/ */
private class PropertyClassCallbackDAO implements EntityLookupCallbackDAO<Long, Class<?>, String> private class PropertyClassCallbackDAO extends EntityLookupCallbackDAOAdaptor<Long, Class<?>, String>
{ {
private final Pair<Long, Class<?>> convertEntityToPair(PropertyClassEntity entity) private final Pair<Long, Class<?>> convertEntityToPair(PropertyClassEntity entity)
{ {
@@ -288,7 +288,7 @@ public abstract class AbstractPropertyValueDAOImpl implements PropertyValueDAO
/** /**
* Callback for <b>alf_prop_string_value</b> DAO. * Callback for <b>alf_prop_string_value</b> DAO.
*/ */
private class PropertyStringValueCallbackDAO implements EntityLookupCallbackDAO<Long, String, Pair<String, Long>> private class PropertyStringValueCallbackDAO extends EntityLookupCallbackDAOAdaptor<Long, String, Pair<String, Long>>
{ {
private final Pair<Long, String> convertEntityToPair(PropertyStringValueEntity entity) private final Pair<Long, String> convertEntityToPair(PropertyStringValueEntity entity)
{ {
@@ -371,7 +371,7 @@ public abstract class AbstractPropertyValueDAOImpl implements PropertyValueDAO
/** /**
* Callback for <b>alf_prop_double_value</b> DAO. * Callback for <b>alf_prop_double_value</b> DAO.
*/ */
private class PropertyDoubleValueCallbackDAO implements EntityLookupCallbackDAO<Long, Double, Double> private class PropertyDoubleValueCallbackDAO extends EntityLookupCallbackDAOAdaptor<Long, Double, Double>
{ {
private final Pair<Long, Double> convertEntityToPair(PropertyDoubleValueEntity entity) private final Pair<Long, Double> convertEntityToPair(PropertyDoubleValueEntity entity)
{ {
@@ -446,7 +446,7 @@ public abstract class AbstractPropertyValueDAOImpl implements PropertyValueDAO
/** /**
* Callback for <b>alf_prop_value</b> DAO. * Callback for <b>alf_prop_value</b> DAO.
*/ */
private class PropertyValueCallbackDAO implements EntityLookupCallbackDAO<Long, Serializable, Serializable> private class PropertyValueCallbackDAO extends EntityLookupCallbackDAOAdaptor<Long, Serializable, Serializable>
{ {
private final Pair<Long, Serializable> convertEntityToPair(PropertyValueEntity entity) private final Pair<Long, Serializable> convertEntityToPair(PropertyValueEntity entity)
{ {
@@ -454,18 +454,23 @@ public abstract class AbstractPropertyValueDAOImpl implements PropertyValueDAO
{ {
return null; return null;
} }
else Long entityId = entity.getId();
{ Serializable entityValue = entity.getPersistedValue();
return entity.getEntityPair();
} // Dig out the class to convert the value to i.e. the actual type of the value
Long actualTypeId = entity.getActualTypeId();
Class<?> actualType = getPropertyClassById(actualTypeId).getSecond();
// Convert it
Serializable actualValue = (Serializable) converter.convert(actualType, entityValue);
// Done
return new Pair<Long, Serializable>(entityId, actualValue);
} }
public Serializable getValueKey(Serializable value) public Serializable getValueKey(Serializable value)
{ {
// Find out how it would be persisted PersistedType persistedType = PropertyValueEntity.getPersistedTypeEnum(value);
Pair<Short, Serializable> persistedValuePair = converter.convertToPersistedType(value);
// We don't return keys for pure Serializable instances // We don't return keys for pure Serializable instances
if (persistedValuePair.getFirst().equals(PersistedType.SERIALIZABLE.getOrdinalNumber())) if (persistedType == PersistedType.SERIALIZABLE)
{ {
// It will be Serialized, so no key // It will be Serialized, so no key
return null; return null;
@@ -477,7 +482,7 @@ public abstract class AbstractPropertyValueDAOImpl implements PropertyValueDAO
else else
{ {
// We've dodged Serializable and String; everything else is OK as a key. // We've dodged Serializable and String; everything else is OK as a key.
return persistedValuePair; return value;
} }
} }
@@ -495,14 +500,6 @@ public abstract class AbstractPropertyValueDAOImpl implements PropertyValueDAO
public Pair<Long, Serializable> findByValue(Serializable value) public Pair<Long, Serializable> findByValue(Serializable value)
{ {
// // Find out how it would be persisted
// Pair<Short, Serializable> persistedValuePair = converter.convertToPersistedType(value);
// // We don't do lookups for serializable values
// if (persistedValuePair.getFirst().equals(PersistedType.SERIALIZABLE.getOrdinalNumber()))
// {
// // It will be Serialized, so no we don't look it up
// return null;
// }
PropertyValueEntity entity = findPropertyValueByValue(value); PropertyValueEntity entity = findPropertyValueByValue(value);
return convertEntityToPair(entity); return convertEntityToPair(entity);
} }

View File

@@ -24,30 +24,19 @@
*/ */
package org.alfresco.repo.domain.propval; package org.alfresco.repo.domain.propval;
import java.io.Serializable;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.repo.domain.propval.PropertyValueEntity.PersistedType;
import org.alfresco.service.cmr.repository.datatype.DefaultTypeConverter; import org.alfresco.service.cmr.repository.datatype.DefaultTypeConverter;
import org.alfresco.service.cmr.repository.datatype.TypeConversionException;
import org.alfresco.util.Pair;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/** /**
* Default converter for handling data going to and from the persistence layer. * Default converter for handling data going to and from the persistence layer.
* <p> * <p/>
* This implementation uses an explicit mapping for each Java class supported. If * Apart from converting between <code>Boolean</code> and <code>Long</code> values,
* an unsupported class is found, then the value is just serialized. Conversions * the {@link DefaultTypeConverter} is used.
* are done using the {@link DefaultTypeConverter}.
* *
* @author Derek Hulley * @author Derek Hulley
* @since 3.3 * @since 3.3
*/ */
public class DefaultPropertyTypeConverter implements PropertyTypeConverter public class DefaultPropertyTypeConverter implements PropertyTypeConverter
{ {
private static final Log logger = LogFactory.getLog(DefaultPropertyTypeConverter.class);
/** /**
* Default constructor * Default constructor
*/ */
@@ -55,84 +44,8 @@ public class DefaultPropertyTypeConverter implements PropertyTypeConverter
{ {
} }
/** public <T> T convert(Class<T> targetClass, Object value)
* {@inheritDoc}
* <p/>
* This converter looks up a {@link PersistedType} using the <code>class</code> of the
* given value. <tt>null</tt> values are handled specially. If there is no match, then
* the {@link PersistedType#SERIALIZABLE} type is used.
*/
public Pair<Short, Serializable> convertToPersistedType(Serializable value)
{ {
if (value == null) return DefaultTypeConverter.INSTANCE.convert(targetClass, value);
{
return PropertyValueEntity.PERSISTED_TYPE_NULL;
}
// Look up the type in the class map
Class<?> clazz = value.getClass();
PersistedType type = PropertyValueEntity.persistedTypesByClass.get(clazz);
if (type == null)
{
return new Pair<Short, Serializable>(PersistedType.SERIALIZABLE.getOrdinalNumber(), value);
}
else
{
// Convert the value
Class<?> toClazz = type.getAssociatedClass();
try
{
Serializable converted = (Serializable) DefaultTypeConverter.INSTANCE.convert(toClazz, value);
return new Pair<Short, Serializable>(type.getOrdinalNumber(), converted);
}
catch (TypeConversionException e)
{
throw new AlfrescoRuntimeException(
"Failed to convert to persistable value: \n" +
" Value: " + value.getClass() + "\n" +
" Target type: " + type + "\n" +
" Target class: " + toClazz,
e);
}
}
}
/**
* {@inheritDoc}
* <p/>
* Looks up the {@link #persistedTypesByOrdinal persisted type} and uses the {@link DefaultTypeConverter} to
* convert back to an external value.
*/
public Serializable convertFromPersistedType(Short persistedType, Class<?> actualType, Serializable persistedValue)
{
if (persistedValue == null)
{
throw new IllegalArgumentException("A persisted value can never be null");
}
PersistedType type = PropertyValueEntity.persistedTypesByOrdinal.get(persistedType);
if (type == null)
{
// Not recognised! This is probably a data issue
logger.warn("Persisted type of '" + persistedType + "' not recognised.");
return persistedValue;
}
else if (type == PersistedType.SERIALIZABLE)
{
// No conversion necessary
return persistedValue;
}
// Convert the value
try
{
return (Serializable) DefaultTypeConverter.INSTANCE.convert(actualType, persistedValue);
}
catch (TypeConversionException e)
{
throw new AlfrescoRuntimeException(
"Failed to convert from persisted value: \n" +
" Value: " + persistedValue.getClass() + "\n" +
" Source type: " + type + "\n" +
" Target class: " + actualType,
e);
}
} }
} }

View File

@@ -24,12 +24,11 @@
*/ */
package org.alfresco.repo.domain.propval; package org.alfresco.repo.domain.propval;
import java.io.Serializable;
import org.alfresco.util.Pair;
/** /**
* Interface for converters that * Interface for converters that to translate between persisted values and external values.
* <p/>
* Implementations must be able to convert between values being stored and Long, Double, String -
* and back again.
* *
* @author Derek Hulley * @author Derek Hulley
* @since 3.3 * @since 3.3
@@ -37,19 +36,10 @@ import org.alfresco.util.Pair;
public interface PropertyTypeConverter public interface PropertyTypeConverter
{ {
/** /**
* Convert an external value into a persisted type and persistable value. * Convert a value to a given type.
* *
* @param value the value to convert * @param value the value to convert
* @return Returns the persisted type and value to persist * @return Returns the persisted type and value to persist
*/ */
Pair<Short, Serializable> convertToPersistedType(Serializable value); <T> T convert(Class<T> targetClass, Object value);
/**
* Convert a persisted type-value pair into an external value
*
* @param persistedType the type that the value was persisted as
* @param actualType the original Java type to convert to
* @param persistedValue the persisted value, which must be one of the {@link PersistedType} values
*/
Serializable convertFromPersistedType(Short persistedType, Class<?> actualType, Serializable persistedValue);
} }

View File

@@ -24,6 +24,8 @@
*/ */
package org.alfresco.repo.domain.propval; package org.alfresco.repo.domain.propval;
import java.io.Serializable;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.alfresco.repo.transaction.RetryingTransactionHelper; import org.alfresco.repo.transaction.RetryingTransactionHelper;
@@ -169,33 +171,6 @@ public class PropertyValueDAOTest extends TestCase
assertNotSame("String IDs were not different", stringEntityPair.getFirst(), stringUpperEntityPair.getFirst()); assertNotSame("String IDs were not different", stringEntityPair.getFirst(), stringUpperEntityPair.getFirst());
} }
// public void testPropertyNumericValue_Boolean() throws Exception
// {
// RetryingTransactionCallback<Pair<Long, Boolean>> createValueCallback = new RetryingTransactionCallback<Pair<Long, Boolean>>()
// {
// public Pair<Long, Boolean> execute() throws Throwable
// {
// // Get the classes
// return propertyValueDAO.getOrCreatePropertyNumericValue(Boolean.TRUE);
// }
// };
// final Pair<Long, Boolean> entityPair = txnHelper.doInTransaction(createValueCallback, false);
// assertNotNull(entityPair);
// assertEquals(Boolean.TRUE, entityPair.getSecond());
//
// RetryingTransactionCallback<Pair<Long, Boolean>> getValueCallback = new RetryingTransactionCallback<Pair<Long, Boolean>>()
// {
// public Pair<Long, Boolean> execute() throws Throwable
// {
// // Get the classes
// return propertyValueDAO.getPropertyDoubleValue(Boolean.TRUE);
// }
// };
// final Pair<Long, Boolean> entityPairCheck = txnHelper.doInTransaction(getValueCallback, false);
// assertNotNull(entityPairCheck);
// assertEquals(entityPair, entityPairCheck);
// }
//
// public void testPropertyNumericValue_Long() throws Exception // public void testPropertyNumericValue_Long() throws Exception
// { // {
// final Long longValue = Long.valueOf(Long.MAX_VALUE); // final Long longValue = Long.valueOf(Long.MAX_VALUE);
@@ -251,4 +226,108 @@ public class PropertyValueDAOTest extends TestCase
assertNotNull(entityPairCheck); assertNotNull(entityPairCheck);
assertEquals(entityPair, entityPairCheck); assertEquals(entityPair, entityPairCheck);
} }
/**
* Tests that the given value can be persisted and retrieved with the same resulting ID
*/
private void runPropertyValueTest(final Serializable value) throws Exception
{
// Create it (if it doesn't exist)
RetryingTransactionCallback<Pair<Long, Serializable>> createValueCallback = new RetryingTransactionCallback<Pair<Long, Serializable>>()
{
public Pair<Long, Serializable> execute() throws Throwable
{
// Get the classes
return propertyValueDAO.getOrCreatePropertyValue(value);
}
};
final Pair<Long, Serializable> entityPair = txnHelper.doInTransaction(createValueCallback, false);
assertNotNull(entityPair);
assertEquals(value, entityPair.getSecond());
// Retrieve it by value
RetryingTransactionCallback<Pair<Long, Serializable>> getValueCallback = new RetryingTransactionCallback<Pair<Long, Serializable>>()
{
public Pair<Long, Serializable> execute() throws Throwable
{
// Get the classes
return propertyValueDAO.getPropertyValue(value);
}
};
final Pair<Long, Serializable> entityPairCheck = txnHelper.doInTransaction(getValueCallback, false);
assertNotNull(entityPairCheck);
assertEquals(entityPair, entityPairCheck);
// Retrieve it by ID
RetryingTransactionCallback<Pair<Long, Serializable>> getByIdCallback = new RetryingTransactionCallback<Pair<Long, Serializable>>()
{
public Pair<Long, Serializable> execute() throws Throwable
{
// Get the classes
return propertyValueDAO.getPropertyValueById(entityPair.getFirst());
}
};
final Pair<Long, Serializable> entityPairCheck2 = txnHelper.doInTransaction(getByIdCallback, false);
assertNotNull(entityPairCheck2);
assertEquals(entityPair, entityPairCheck2);
}
public void testPropertyValue_Null() throws Exception
{
runPropertyValueTest(null);
}
public void testPropertyValue_Boolean() throws Exception
{
runPropertyValueTest(Boolean.TRUE);
runPropertyValueTest(Boolean.FALSE);
}
public void testPropertyValue_Short() throws Exception
{
for (short i = 0; i < 1000; i++)
{
runPropertyValueTest(new Short(i));
}
}
public void testPropertyValue_Integer() throws Exception
{
for (int i = 0; i < 1000; i++)
{
runPropertyValueTest(new Integer(i));
}
}
public void testPropertyValue_Long() throws Exception
{
for (long i = 0; i < 1000; i++)
{
runPropertyValueTest(new Long(i));
}
}
public void testPropertyValue_Float() throws Exception
{
for (long i = 0; i < 1000; i++)
{
runPropertyValueTest(new Float((float)i + 0.01F));
}
}
public void testPropertyValue_Double() throws Exception
{
for (long i = 0; i < 1000; i++)
{
runPropertyValueTest(new Double((double)i + 0.01D));
}
}
public void testPropertyValue_String() throws Exception
{
for (long i = 0; i < 1000; i++)
{
runPropertyValueTest(new String("Value-" + i + ".xyz"));
}
}
} }

View File

@@ -50,12 +50,11 @@ public class PropertyValueEntity
public static final Long LONG_ZERO = new Long(0L); public static final Long LONG_ZERO = new Long(0L);
public static final Long LONG_ONE = new Long(1L); public static final Long LONG_ONE = new Long(1L);
public static final Short ORDINAL_NULL = new Short((short)0); public static final Short ORDINAL_NULL = 0;
public static final Short ORDINAL_BOOLEAN = new Short((short)1); public static final Short ORDINAL_LONG = 1;
public static final Short ORDINAL_LONG = new Short((short)2); public static final Short ORDINAL_DOUBLE = 2;
public static final Short ORDINAL_DOUBLE = new Short((short)3); public static final Short ORDINAL_STRING = 3;
public static final Short ORDINAL_STRING = new Short((short)4); public static final Short ORDINAL_SERIALIZABLE = 4;
public static final Short ORDINAL_SERIALIZABLE = new Short((short)5);
/** /**
* Enumeration of persisted types for <b>alf_prop_value.persisted_type</b>. * Enumeration of persisted types for <b>alf_prop_value.persisted_type</b>.
@@ -81,19 +80,6 @@ public class PropertyValueEntity
throw new UnsupportedOperationException("NULL is a special case and has no associated class."); throw new UnsupportedOperationException("NULL is a special case and has no associated class.");
} }
}, },
BOOLEAN
{
@Override
public Short getOrdinalNumber()
{
return ORDINAL_BOOLEAN;
}
@Override
public Class<?> getAssociatedClass()
{
return Boolean.class;
}
},
LONG LONG
{ {
@Override @Override
@@ -188,7 +174,7 @@ public class PropertyValueEntity
persistedTypesByOrdinal = Collections.unmodifiableMap(mapOrdinal); persistedTypesByOrdinal = Collections.unmodifiableMap(mapOrdinal);
// Create the map of class-type // Create the map of class-type
Map<Class<?>, PersistedType> mapClass = new HashMap<Class<?>, PersistedType>(29); Map<Class<?>, PersistedType> mapClass = new HashMap<Class<?>, PersistedType>(29);
mapClass.put(Boolean.class, PersistedType.BOOLEAN); mapClass.put(Boolean.class, PersistedType.LONG);
mapClass.put(Short.class, PersistedType.LONG); mapClass.put(Short.class, PersistedType.LONG);
mapClass.put(Integer.class, PersistedType.LONG); mapClass.put(Integer.class, PersistedType.LONG);
mapClass.put(Long.class, PersistedType.LONG); mapClass.put(Long.class, PersistedType.LONG);
@@ -202,7 +188,9 @@ public class PropertyValueEntity
private static final Log logger = LogFactory.getLog(PropertyValueEntity.class); private static final Log logger = LogFactory.getLog(PropertyValueEntity.class);
private Long id; private Long id;
private Long actualTypeId;
private Short persistedType; private Short persistedType;
private PersistedType persistedTypeEnum; // Derived
private Long longValue; private Long longValue;
private String stringValue; private String stringValue;
private Double doubleValue; private Double doubleValue;
@@ -217,7 +205,7 @@ public class PropertyValueEntity
@Override @Override
public int hashCode() public int hashCode()
{ {
return (persistedType == null ? 0 : persistedType.intValue()) + (longValue == null ? 0 : longValue.intValue()); return (actualTypeId == null ? 0 : actualTypeId.intValue()) + (longValue == null ? 0 : longValue.intValue());
} }
@Override @Override
@@ -230,7 +218,7 @@ public class PropertyValueEntity
else if (obj != null && obj instanceof PropertyValueEntity) else if (obj != null && obj instanceof PropertyValueEntity)
{ {
PropertyValueEntity that = (PropertyValueEntity) obj; PropertyValueEntity that = (PropertyValueEntity) obj;
return EqualsHelper.nullSafeEquals(this.persistedType, that.persistedType) && return EqualsHelper.nullSafeEquals(this.actualTypeId, that.actualTypeId) &&
EqualsHelper.nullSafeEquals(this.longValue, that.longValue); EqualsHelper.nullSafeEquals(this.longValue, that.longValue);
} }
else else
@@ -245,76 +233,115 @@ public class PropertyValueEntity
StringBuilder sb = new StringBuilder(512); StringBuilder sb = new StringBuilder(512);
sb.append("PropertyValueEntity") sb.append("PropertyValueEntity")
.append("[ ID=").append(id) .append("[ ID=").append(id)
.append(", type=").append(persistedType) .append(", actualTypeId=").append(actualTypeId)
.append(", persistedType=").append(persistedType)
.append(", value=").append(longValue) .append(", value=").append(longValue)
.append("]"); .append("]");
return sb.toString(); return sb.toString();
} }
/**
* @return Returns the ID-value pair
*/
public Pair<Long, Serializable> getEntityPair()
{
Serializable value = getValue();
return new Pair<Long, Serializable>(id, value);
}
/** /**
* Gets the value based on the persisted type. * Gets the value based on the persisted type.
* Note that this is the value <b>as persisted</b> and not the original, client-required * Note that this is the value <b>as persisted</b> and not the original, client-required
* value. * value.
* @return Returns the persisted value * @return Returns the persisted value
*/ */
public Serializable getValue() public Serializable getPersistedValue()
{ {
if (persistedType.equals(PersistedType.NULL.getOrdinalNumber())) switch (persistedTypeEnum)
{ {
return null; case NULL:
return null;
case LONG:
return longValue;
case DOUBLE:
return doubleValue;
case STRING:
return stringValue;
case SERIALIZABLE:
return serializableValue;
default:
throw new IllegalStateException("Should not be able to get through switch");
} }
else if (persistedType.equals(PersistedType.BOOLEAN.getOrdinalNumber())) }
{
return (longValue.longValue() > 0 ? Boolean.TRUE : Boolean.FALSE); /**
} * Shortcut method to set the value. It will be converted as required and the necessary fields
else if (persistedType.equals(PersistedType.LONG.getOrdinalNumber())) * will be populated.
*
* @param value the value to persist (may be <tt>null</tt>)
* @param converter the converter that will perform and type conversion
* @return Returns the persisted type value
*/
public Serializable setValue(Serializable value, PropertyTypeConverter converter)
{
if (value == null)
{ {
this.persistedType = ORDINAL_NULL;
this.persistedTypeEnum = PersistedType.NULL;
this.longValue = LONG_ZERO;
return longValue; return longValue;
} }
else if (persistedType.equals(PersistedType.DOUBLE.getOrdinalNumber()))
{
return doubleValue;
}
else if (persistedType.equals(PersistedType.STRING.getOrdinalNumber()))
{
return stringValue;
}
else if (persistedType.equals(PersistedType.SERIALIZABLE.getOrdinalNumber()))
{
return serializableValue;
}
else else
{ {
logger.warn("Persisted type code not recognised: " + this.persistedType); Class<?> valueClazz = value.getClass();
// Return any non-null value and hope it works persistedTypeEnum = persistedTypesByClass.get(valueClazz);
if (serializableValue != null) if (persistedTypeEnum == null)
{ {
return serializableValue; persistedTypeEnum = PersistedType.SERIALIZABLE;
} }
else if (doubleValue != null) persistedType = persistedTypeEnum.getOrdinalNumber();
// Get the class to persist as
switch (persistedTypeEnum)
{ {
return doubleValue; case LONG:
} longValue = converter.convert(Long.class, value);
else if (stringValue != null) return longValue;
{ case DOUBLE:
return stringValue; doubleValue = converter.convert(Double.class, value);
} return doubleValue;
else case STRING:
{ stringValue = converter.convert(String.class, value);
return longValue; return stringValue;
case SERIALIZABLE:
serializableValue = value;
return serializableValue;
default:
throw new IllegalStateException("Should not be able to get through switch");
} }
} }
} }
/**
* Helper method to determine how the given value will be stored.
*
* @param value the value to check
* @return Returns the persisted type
*/
public static PersistedType getPersistedTypeEnum(Serializable value)
{
PersistedType persistedTypeEnum;
if (value == null)
{
persistedTypeEnum = PersistedType.NULL;
}
else
{
Class<?> valueClazz = value.getClass();
persistedTypeEnum = persistedTypesByClass.get(valueClazz);
if (persistedTypeEnum == null)
{
persistedTypeEnum = PersistedType.SERIALIZABLE;
}
}
return persistedTypeEnum;
}
public PersistedType getPersistedTypeEnum()
{
return persistedTypeEnum;
}
public Long getId() public Long getId()
{ {
return id; return id;
@@ -325,6 +352,16 @@ public class PropertyValueEntity
this.id = id; this.id = id;
} }
public Long getActualTypeId()
{
return actualTypeId;
}
public void setActualTypeId(Long actualTypeId)
{
this.actualTypeId = actualTypeId;
}
public Short getPersistedType() public Short getPersistedType()
{ {
return persistedType; return persistedType;
@@ -333,6 +370,12 @@ public class PropertyValueEntity
public void setPersistedType(Short persistedType) public void setPersistedType(Short persistedType)
{ {
this.persistedType = persistedType; this.persistedType = persistedType;
this.persistedTypeEnum = persistedTypesByOrdinal.get(persistedType);
if (persistedTypeEnum == null)
{
logger.error("Persisted type '" + persistedType + "' is not recognised.");
this.persistedTypeEnum = PersistedType.LONG;
}
} }
public Long getLongValue() public Long getLongValue()

View File

@@ -47,12 +47,19 @@ public class PropertyValueDAOImpl extends AbstractPropertyValueDAOImpl
private static final String SELECT_PROPERTY_CLASS_BY_ID = "select.PropertyClassByID"; private static final String SELECT_PROPERTY_CLASS_BY_ID = "select.PropertyClassByID";
private static final String SELECT_PROPERTY_CLASS_BY_NAME = "select.PropertyClassByName"; private static final String SELECT_PROPERTY_CLASS_BY_NAME = "select.PropertyClassByName";
private static final String INSERT_PROPERTY_CLASS = "insert.PropertyClass"; private static final String INSERT_PROPERTY_CLASS = "insert.PropertyClass";
private static final String SELECT_PROPERTY_STRING_VALUE_BY_ID = "select.PropertyStringValueByID"; private static final String SELECT_PROPERTY_STRING_VALUE_BY_ID = "select.PropertyStringValueByID";
private static final String SELECT_PROPERTY_STRING_VALUE_BY_STRING = "select.PropertyStringValueByString"; private static final String SELECT_PROPERTY_STRING_VALUE_BY_VALUE = "select.PropertyStringValueByValue";
private static final String INSERT_PROPERTY_STRING_VALUE = "insert.PropertyStringValue"; private static final String INSERT_PROPERTY_STRING_VALUE = "insert.PropertyStringValue";
private static final String SELECT_PROPERTY_DOUBLE_VALUE_BY_ID = "select.PropertyDoubleValueByID"; private static final String SELECT_PROPERTY_DOUBLE_VALUE_BY_ID = "select.PropertyDoubleValueByID";
private static final String SELECT_PROPERTY_DOUBLE_VALUE_BY_VALUE = "select.PropertyDoubleValueByValue"; private static final String SELECT_PROPERTY_DOUBLE_VALUE_BY_VALUE = "select.PropertyDoubleValueByValue";
private static final String INSERT_PROPERTY_DOUBLE_VALUE = "insert.PropertyDoubleValue"; private static final String INSERT_PROPERTY_DOUBLE_VALUE = "insert.PropertyDoubleValue";
private static final String SELECT_PROPERTY_VALUE_BY_ID = "select.PropertyValueById";
private static final String SELECT_PROPERTY_VALUE_BY_LOCAL_VALUE = "select.PropertyValueByLocalValue";
private static final String SELECT_PROPERTY_VALUE_BY_DOUBLE_VALUE = "select.PropertyValueByDoubleValue";
private static final String SELECT_PROPERTY_VALUE_BY_STRING_VALUE = "select.PropertyValueByStringValue";
private static final String INSERT_PROPERTY_VALUE = "insert.PropertyValue"; private static final String INSERT_PROPERTY_VALUE = "insert.PropertyValue";
private SqlMapClientTemplate template; private SqlMapClientTemplate template;
@@ -124,9 +131,10 @@ public class PropertyValueDAOImpl extends AbstractPropertyValueDAOImpl
PropertyStringValueEntity entity = new PropertyStringValueEntity(); PropertyStringValueEntity entity = new PropertyStringValueEntity();
entity.setStringValue(value); entity.setStringValue(value);
List<PropertyStringValueEntity> results = (List<PropertyStringValueEntity>) template.queryForList( List<PropertyStringValueEntity> results = (List<PropertyStringValueEntity>) template.queryForList(
SELECT_PROPERTY_STRING_VALUE_BY_STRING, SELECT_PROPERTY_STRING_VALUE_BY_VALUE,
entity); entity);
// There double be several matches, so find the first one that matches exactly // There double be several matches (if the database is case-insensitive), so find the first
// value that matches exactly.
for (PropertyStringValueEntity resultEntity : results) for (PropertyStringValueEntity resultEntity : results)
{ {
if (value.equals(resultEntity.getStringValue())) if (value.equals(resultEntity.getStringValue()))
@@ -175,17 +183,16 @@ public class PropertyValueDAOImpl extends AbstractPropertyValueDAOImpl
List<PropertyDoubleValueEntity> results = (List<PropertyDoubleValueEntity>) template.queryForList( List<PropertyDoubleValueEntity> results = (List<PropertyDoubleValueEntity>) template.queryForList(
SELECT_PROPERTY_DOUBLE_VALUE_BY_VALUE, SELECT_PROPERTY_DOUBLE_VALUE_BY_VALUE,
entity); entity);
// There coult be several matches, so find the first one that matches exactly // There coult be several matches, so take the first one
for (PropertyDoubleValueEntity resultEntity : results) if (results.size() > 0)
{ {
if (value.equals(resultEntity.getDoubleValue())) return results.get(0);
{ }
// Found a match else
return resultEntity; {
} // No match
return null;
} }
// No real match
return null;
} }
@Override @Override
@@ -206,77 +213,136 @@ public class PropertyValueDAOImpl extends AbstractPropertyValueDAOImpl
@Override @Override
protected PropertyValueEntity findPropertyValueById(Long id) protected PropertyValueEntity findPropertyValueById(Long id)
{ {
// TODO: Full query pulling back all related values PropertyValueEntity entity = new PropertyValueEntity();
return null; entity.setId(id);
entity = (PropertyValueEntity) template.queryForObject(
SELECT_PROPERTY_VALUE_BY_ID,
entity);
// Done
return entity;
} }
@SuppressWarnings("unchecked")
@Override @Override
protected PropertyValueEntity findPropertyValueByValue(Serializable value) protected PropertyValueEntity findPropertyValueByValue(Serializable value)
{ {
// TODO: Find out persisted type and perform relevant query // Get the actual type ID
return null; Class<?> clazz = (value == null ? Object.class : value.getClass());
Pair<Long, Class<?>> clazzPair = getPropertyClass(clazz);
if (clazzPair == null)
{
// Shortcut: There are no properties of this type
return null;
}
Long actualTypeId = clazzPair.getFirst();
// Construct the search parameters
PropertyValueEntity queryEntity = new PropertyValueEntity();
queryEntity.setValue(value, converter);
queryEntity.setActualTypeId(actualTypeId);
// How would it be persisted?
PersistedType persistedType = queryEntity.getPersistedTypeEnum();
// Query based on the the persistable value type
String query = null;
boolean singleResult = true; // false if multiple query results are possible
// Handle each persisted type individually
switch (persistedType)
{
case NULL:
case LONG:
query = SELECT_PROPERTY_VALUE_BY_LOCAL_VALUE;
break;
case DOUBLE:
query = SELECT_PROPERTY_VALUE_BY_DOUBLE_VALUE;
break;
case STRING:
query = SELECT_PROPERTY_VALUE_BY_STRING_VALUE;
singleResult = false;
break;
case SERIALIZABLE:
// No query
break;
default:
throw new IllegalStateException("Unhandled PersistedType value: " + persistedType);
}
// Now query
PropertyValueEntity result = null;
if (query != null)
{
if (singleResult)
{
result = (PropertyValueEntity) template.queryForObject(query, queryEntity);
}
else
{
Serializable queryValue = queryEntity.getPersistedValue();
List<PropertyValueEntity> results = (List<PropertyValueEntity>) template.queryForList(
query,
queryEntity);
for (PropertyValueEntity row : results)
{
if (queryValue.equals(row.getPersistedValue()))
{
// We have a match
result = row;
break;
}
}
}
}
// Done
return result;
} }
@Override @Override
protected PropertyValueEntity createPropertyValue(Serializable value) protected PropertyValueEntity createPropertyValue(Serializable value)
{ {
// Find out how it would be persisted // Get the actual type ID
Pair<Short, Serializable> persistedValuePair = converter.convertToPersistedType(value); Class<?> clazz = (value == null ? Object.class : value.getClass());
Serializable persistedValue = persistedValuePair.getSecond(); Pair<Long, Class<?>> clazzPair = getOrCreatePropertyClass(clazz);
Long actualTypeId = clazzPair.getFirst();
PropertyValueEntity entity = new PropertyValueEntity();
// Construct the insert entity
PersistedType persistedType = PropertyValueEntity.persistedTypesByOrdinal.get(persistedValuePair.getFirst()); PropertyValueEntity insertEntity = new PropertyValueEntity();
entity.setPersistedType(persistedType.getOrdinalNumber()); insertEntity.setValue(value, converter);
// Handle each persisted type individually insertEntity.setActualTypeId(actualTypeId);
if (persistedType.equals(PersistedType.NULL.getOrdinalNumber()))
// Persist the persisted value
switch (insertEntity.getPersistedTypeEnum())
{ {
entity.setLongValue(PropertyValueEntity.LONG_ZERO); case DOUBLE:
} Double doubleValue = insertEntity.getDoubleValue();
else if (persistedType.equals(PersistedType.BOOLEAN.getOrdinalNumber())) Pair<Long, Double> insertDoublePair = getOrCreatePropertyDoubleValue(doubleValue);
{ insertEntity.setLongValue(insertDoublePair.getFirst());
Boolean booleanValue = (Boolean) persistedValue; break;
entity.setLongValue( case STRING:
booleanValue.booleanValue() ? PropertyValueEntity.LONG_ONE : PropertyValueEntity.LONG_ZERO); String stringValue = insertEntity.getStringValue();
} Pair<Long, String> insertStringPair = getOrCreatePropertyStringValue(stringValue);
else if (persistedType.equals(PersistedType.LONG.getOrdinalNumber())) insertEntity.setLongValue(insertStringPair.getFirst());
{ break;
Long longValue = (Long) persistedValue; case SERIALIZABLE:
entity.setLongValue(longValue); throw new UnsupportedOperationException("Serializable not supported, yet.");
} // Pair<Long, Serializable> insertSerializablePair = getOrCreatePropertySerializableValue(value);
else if (persistedType.equals(PersistedType.DOUBLE.getOrdinalNumber())) // insertEntity.setLongValue(insertSerializablePair.getFirst());
{ // break;
Double doubleValue = (Double) persistedValue; case NULL:
// Look it up case LONG:
Pair<Long, Double> entityPair = getOrCreatePropertyDoubleValue(doubleValue); // Do nothing for these
entity.setLongValue(entityPair.getFirst()); break;
entity.setDoubleValue(doubleValue); default:
} throw new IllegalStateException("Unknown PersistedType enum: " + insertEntity.getPersistedTypeEnum());
else if (persistedType.equals(PersistedType.STRING.getOrdinalNumber()))
{
String stringValue = (String) persistedValue;
// Look it up
Pair<Long, String> entityPair = getOrCreatePropertyStringValue(stringValue);
entity.setLongValue(entityPair.getFirst());
entity.setStringValue(stringValue);
}
else if (persistedType.equals(PersistedType.SERIALIZABLE.getOrdinalNumber()))
{
throw new UnsupportedOperationException("Serializable not done, yet.");
}
else
{
throw new IllegalStateException(
"The persisted property is not valid: \n" +
" Raw Value: " + value + "\n" +
" Persisted Value: " + persistedValuePair + "\n" +
" Converter:" + converter.getClass());
} }
// Persist the entity // Persist the entity
Long id = (Long) template.insert(INSERT_PROPERTY_VALUE, entity); Long id = (Long) template.insert(INSERT_PROPERTY_VALUE, insertEntity);
entity.setId(id); insertEntity.setId(id);
// Done // Done
return entity; return insertEntity;
} }
} }