kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | 42b5c0e4eb367e47f64562ca0967987b122015b05a0ecd74c781be903d940014 |
|---|---|
| Author | Alexandre Dutra <alexandre.dutra@datastax.com> · 2016-05-30 18:44 +02:00 |
| Committer | olim7t <omichallat+github@gmail.com> · 2016-07-22 09:45 -07:00 |
| Parents | 845bfcad3488 |
32 files changed
modified changelog/README.md +1 −0
| @@ -11,6 +11,7 @@ | ||
| 11 | 11 | - [improvement] JAVA-1212: Don't retry non-idempotent statements by default. |
| 12 | 12 | - [improvement] JAVA-1192: Make EventDebouncer settings updatable at runtime. |
| 13 | 13 | - [new feature] JAVA-541: Add polymorphism support to object mapper. |
| 14 | +- [new feature] JAVA-636: Allow @Column annotations on getters/setters as well as fields. | |
| 14 | 15 | |
| 15 | 16 | Merged from 3.0.x branch: |
| 16 | 17 |
modified clirr-ignores.xml +7 −0
| @@ -13,6 +13,13 @@ | ||
| 13 | 13 | --> |
| 14 | 14 | <differences> |
| 15 | 15 | |
| 16 | + <difference> | |
| 17 | + <differenceType>8001</differenceType> <!-- class removed --> | |
| 18 | + <className>com/datastax/driver/mapping/ColumnMapper$Kind</className> | |
| 19 | + <justification>False positive, the enclosing class is package-private so this was never exposed</justification> | |
| 20 | + </difference> | |
| 21 | + | |
| 22 | + | |
| 16 | 23 | <difference> |
| 17 | 24 | <differenceType>1001</differenceType> <!-- decreased visibility --> |
| 18 | 25 | <className>com/datastax/driver/mapping/ColumnMapper$Kind</className> |
modified driver-core/src/main/java/com/datastax/driver/core/ClusteringOrder.java +1 −1
| @@ -25,4 +25,4 @@ | ||
| 25 | 25 | |
| 26 | 26 | ASC, DESC; |
| 27 | 27 | |
| 28 | -} | |
| 28 | +} | |
| No newline at the end of the file |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/AccessorMapper.java +19 −9
| @@ -19,22 +19,35 @@ | ||
| 19 | 19 | import com.google.common.util.concurrent.Futures; |
| 20 | 20 | import com.google.common.util.concurrent.ListenableFuture; |
| 21 | 21 | |
| 22 | +import java.lang.reflect.Proxy; | |
| 22 | 23 | import java.util.ArrayList; |
| 23 | 24 | import java.util.List; |
| 24 | 25 | |
| 25 | -abstract class AccessorMapper<T> { | |
| 26 | +class AccessorMapper<T> { | |
| 26 | 27 | |
| 27 | - public final Class<T> daoClass; | |
| 28 | - protected final List<MethodMapper> methods; | |
| 28 | + final Class<T> daoClass; | |
| 29 | + final List<MethodMapper> methods; | |
| 30 | + private final Class<T>[] proxyClasses; | |
| 31 | + private final AccessorInvocationHandler<T> handler; | |
| 29 | 32 | |
| 30 | - protected AccessorMapper(Class<T> daoClass, List<MethodMapper> methods) { | |
| 33 | + @SuppressWarnings({"unchecked", "rawtypes"}) | |
| 34 | + AccessorMapper(Class<T> daoClass, List<MethodMapper> methods) { | |
| 31 | 35 | this.daoClass = daoClass; |
| 32 | 36 | this.methods = methods; |
| 37 | + this.proxyClasses = (Class<T>[]) new Class[]{daoClass}; | |
| 38 | + this.handler = new AccessorInvocationHandler<T>(this); | |
| 33 | 39 | } |
| 34 | 40 | |
| 35 | - abstract T createProxy(); | |
| 41 | + @SuppressWarnings("unchecked") | |
| 42 | + T createProxy() { | |
| 43 | + try { | |
| 44 | + return (T) Proxy.newProxyInstance(daoClass.getClassLoader(), proxyClasses, handler); | |
| 45 | + } catch (Exception e) { | |
| 46 | + throw new RuntimeException("Cannot create instance for Accessor interface " + daoClass.getName()); | |
| 47 | + } | |
| 48 | + } | |
| 36 | 49 | |
| 37 | - public void prepare(MappingManager manager) { | |
| 50 | + void prepare(MappingManager manager) { | |
| 38 | 51 | List<ListenableFuture<PreparedStatement>> statements = new ArrayList<ListenableFuture<PreparedStatement>>(methods.size()); |
| 39 | 52 | |
| 40 | 53 | for (MethodMapper method : methods) |
| @@ -49,7 +62,4 @@ | ||
| 49 | 62 | } |
| 50 | 63 | } |
| 51 | 64 | |
| 52 | - interface Factory { | |
| 53 | - public <T> AccessorMapper<T> create(Class<T> daoClass, List<MethodMapper> methods); | |
| 54 | - } | |
| 55 | 65 | } |
deleted driver-mapping/src/main/java/com/datastax/driver/mapping/AccessorReflectionMapper.java +0 −55
| @@ -1,55 +0,0 @@ | ||
| 1 | -/* | |
| 2 | - * Copyright (C) 2012-2015 DataStax Inc. | |
| 3 | - * | |
| 4 | - * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | - * you may not use this file except in compliance with the License. | |
| 6 | - * You may obtain a copy of the License at | |
| 7 | - * | |
| 8 | - * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | - * | |
| 10 | - * Unless required by applicable law or agreed to in writing, software | |
| 11 | - * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | - * See the License for the specific language governing permissions and | |
| 14 | - * limitations under the License. | |
| 15 | - */ | |
| 16 | -package com.datastax.driver.mapping; | |
| 17 | - | |
| 18 | -import java.lang.reflect.Proxy; | |
| 19 | -import java.util.List; | |
| 20 | - | |
| 21 | -class AccessorReflectionMapper<T> extends AccessorMapper<T> { | |
| 22 | - | |
| 23 | - private static AccessorReflectionFactory factory = new AccessorReflectionFactory(); | |
| 24 | - | |
| 25 | - private final Class<T>[] proxyClasses; | |
| 26 | - private final AccessorInvocationHandler<T> handler; | |
| 27 | - | |
| 28 | - @SuppressWarnings({"unchecked", "rawtypes"}) | |
| 29 | - private AccessorReflectionMapper(Class<T> daoClass, List<MethodMapper> methods) { | |
| 30 | - super(daoClass, methods); | |
| 31 | - this.proxyClasses = (Class<T>[]) new Class[]{daoClass}; | |
| 32 | - this.handler = new AccessorInvocationHandler<T>(this); | |
| 33 | - } | |
| 34 | - | |
| 35 | - public static Factory factory() { | |
| 36 | - return factory; | |
| 37 | - } | |
| 38 | - | |
| 39 | - @SuppressWarnings("unchecked") | |
| 40 | - @Override | |
| 41 | - public T createProxy() { | |
| 42 | - try { | |
| 43 | - return (T) Proxy.newProxyInstance(daoClass.getClassLoader(), proxyClasses, handler); | |
| 44 | - } catch (Exception e) { | |
| 45 | - throw new RuntimeException("Cannot create instance for Accessor interface " + daoClass.getName()); | |
| 46 | - } | |
| 47 | - } | |
| 48 | - | |
| 49 | - private static class AccessorReflectionFactory implements Factory { | |
| 50 | - @Override | |
| 51 | - public <T> AccessorMapper<T> create(Class<T> daoClass, List<MethodMapper> methods) { | |
| 52 | - return new AccessorReflectionMapper<T>(daoClass, methods); | |
| 53 | - } | |
| 54 | - } | |
| 55 | -} |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/AnnotationChecks.java +16 −20
| @@ -61,8 +61,8 @@ | ||
| 61 | 61 | /** |
| 62 | 62 | * Checks that a field is only annotated with the given mapping annotations, and that its "frozen" annotations are valid. |
| 63 | 63 | */ |
| 64 | - static void validateAnnotations(MappedProperty<?> property, Class<? extends Annotation>... allowed) { | |
| 65 | - Class<? extends Annotation> invalid = validateAnnotations(property.annotations(), allowed); | |
| 64 | + static void validateAnnotations(PropertyMapper property, Class<? extends Annotation>... allowed) { | |
| 65 | + Class<? extends Annotation> invalid = validateAnnotations(property.getAnnotations(), allowed); | |
| 66 | 66 | if (invalid != null) |
| 67 | 67 | throw new IllegalArgumentException(String.format("Annotation @%s is not allowed on property %s", |
| 68 | 68 | invalid.getSimpleName(), |
| @@ -88,16 +88,16 @@ | ||
| 88 | 88 | return false; |
| 89 | 89 | } |
| 90 | 90 | |
| 91 | - private static void checkValidPrimaryKey(MappedProperty<?> property) { | |
| 91 | + private static void checkValidPrimaryKey(PropertyMapper property) { | |
| 92 | 92 | if (property.isPartitionKey() && property.isClusteringColumn()) |
| 93 | - throw new IllegalArgumentException("Property " + property.name() + " cannot have both the @PartitionKey and @ClusteringColumn annotations"); | |
| 93 | + throw new IllegalArgumentException("Property " + property + " cannot have both the @PartitionKey and @ClusteringColumn annotations"); | |
| 94 | 94 | } |
| 95 | 95 | |
| 96 | - private static void checkValidComputed(MappedProperty<?> property) { | |
| 96 | + private static void checkValidComputed(PropertyMapper property) { | |
| 97 | 97 | if (property.isComputed()) { |
| 98 | 98 | Computed computed = property.annotation(Computed.class); |
| 99 | 99 | if (computed.value().isEmpty()) { |
| 100 | - throw new IllegalArgumentException(String.format("Property %s: attribute 'value' of annotation @Computed is mandatory for computed properties", property.name())); | |
| 100 | + throw new IllegalArgumentException(String.format("Property %s: attribute 'value' of annotation @Computed is mandatory for computed properties", property)); | |
| 101 | 101 | } |
| 102 | 102 | if (property.hasAnnotation(Column.class)) { |
| 103 | 103 | throw new IllegalArgumentException("Cannot use @Column and @Computed on the same property"); |
| @@ -105,24 +105,20 @@ | ||
| 105 | 105 | } |
| 106 | 106 | } |
| 107 | 107 | |
| 108 | - static <T> void validatePrimaryKeyOnUDT(MappedProperty<T> property) { | |
| 109 | - switch (property.kind()) { | |
| 110 | - case PARTITION_KEY: | |
| 111 | - throw new IllegalArgumentException("Annotation @PartitionKey is not allowed in a class annotated by @UDT"); | |
| 112 | - case CLUSTERING_COLUMN: | |
| 113 | - throw new IllegalArgumentException("Annotation @ClusteringColumn is not allowed in a class annotated by @UDT"); | |
| 114 | - default: | |
| 115 | - break; | |
| 116 | - } | |
| 108 | + static void validatePrimaryKeyOnUDT(PropertyMapper property) { | |
| 109 | + if (property.isPartitionKey()) | |
| 110 | + throw new IllegalArgumentException("Annotation @PartitionKey is not allowed in a class annotated by @UDT"); | |
| 111 | + else if (property.isClusteringColumn()) | |
| 112 | + throw new IllegalArgumentException("Annotation @ClusteringColumn is not allowed in a class annotated by @UDT"); | |
| 117 | 113 | } |
| 118 | 114 | |
| 119 | - static <T> void validateOrder(List<MappedProperty<T>> properties, String annotation) { | |
| 115 | + static void validateOrder(List<PropertyMapper> properties, String annotation) { | |
| 120 | 116 | for (int i = 0; i < properties.size(); i++) { |
| 121 | - MappedProperty<?> property = properties.get(i); | |
| 122 | - int pos = property.position(); | |
| 117 | + PropertyMapper property = properties.get(i); | |
| 118 | + int pos = property.getPosition(); | |
| 123 | 119 | if (pos != i) |
| 124 | - throw new IllegalArgumentException(String.format("Invalid ordering value %d for annotation %s of column %s, was expecting %d", | |
| 125 | - pos, annotation, property.name(), i)); | |
| 120 | + throw new IllegalArgumentException(String.format("Invalid ordering value %d for annotation %s of property %s, was expecting %d", | |
| 121 | + pos, annotation, property, i)); | |
| 126 | 122 | } |
| 127 | 123 | } |
| 128 | 124 | } |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/AnnotationParser.java +69 −90
| @@ -22,33 +22,38 @@ | ||
| 22 | 22 | import com.datastax.driver.mapping.MethodMapper.ParamMapper; |
| 23 | 23 | import com.datastax.driver.mapping.annotations.*; |
| 24 | 24 | import com.google.common.base.Strings; |
| 25 | -import com.google.common.collect.Maps; | |
| 26 | 25 | import com.google.common.reflect.TypeToken; |
| 27 | 26 | |
| 28 | -import java.beans.BeanInfo; | |
| 29 | 27 | import java.beans.PropertyDescriptor; |
| 30 | 28 | import java.lang.annotation.Annotation; |
| 31 | 29 | import java.lang.reflect.Method; |
| 32 | 30 | import java.lang.reflect.ParameterizedType; |
| 33 | 31 | import java.lang.reflect.Type; |
| 34 | -import java.util.ArrayList; | |
| 35 | -import java.util.Collections; | |
| 36 | -import java.util.List; | |
| 37 | -import java.util.Map; | |
| 32 | +import java.util.*; | |
| 38 | 33 | import java.util.concurrent.atomic.AtomicInteger; |
| 39 | 34 | |
| 40 | 35 | import static com.datastax.driver.core.Metadata.quote; |
| 41 | 36 | |
| 42 | 37 | /** |
| 43 | - * Static methods that facilitates parsing class annotations into the corresponding {@link EntityMapper}. | |
| 38 | + * Static methods that facilitates parsing: | |
| 39 | + * - {@link #parseEntity(Class, MappingManager)}: entity classes into {@link EntityMapper} instances | |
| 40 | + * - {@link #parseUDT(Class, MappingManager)}: UDT classes into {@link MappedUDTCodec} instances. | |
| 41 | + * - {@link #parseAccessor(Class, MappingManager)}: Accessor interfaces into {@link AccessorMapper} instances. | |
| 44 | 42 | */ |
| 45 | 43 | @SuppressWarnings("unchecked") |
| 46 | 44 | class AnnotationParser { |
| 47 | 45 | |
| 46 | + private static final Comparator<PropertyMapper> POSITION_COMPARATOR = new Comparator<PropertyMapper>() { | |
| 47 | + @Override | |
| 48 | + public int compare(PropertyMapper o1, PropertyMapper o2) { | |
| 49 | + return o1.getPosition() - o2.getPosition(); | |
| 50 | + } | |
| 51 | + }; | |
| 52 | + | |
| 48 | 53 | private AnnotationParser() { |
| 49 | 54 | } |
| 50 | 55 | |
| 51 | - static <T> EntityMapper<T> parseEntity(final Class<T> entityClass, EntityMapper.Factory factory, MappingManager mappingManager) { | |
| 56 | + static <T> EntityMapper<T> parseEntity(final Class<T> entityClass, MappingManager mappingManager) { | |
| 52 | 57 | Table table = AnnotationChecks.getTypeAnnotation(Table.class, entityClass); |
| 53 | 58 | |
| 54 | 59 | String ksName = table.caseSensitiveKeyspace() ? table.keyspace() : table.keyspace().toLowerCase(); |
| @@ -67,79 +72,67 @@ | ||
| 67 | 72 | )); |
| 68 | 73 | } |
| 69 | 74 | |
| 70 | - EntityMapper<T> mapper = factory.create(entityClass, ksName, tableName, writeConsistency, readConsistency); | |
| 75 | + EntityMapper<T> mapper = new EntityMapper<T>(entityClass, ksName, tableName, writeConsistency, readConsistency); | |
| 71 | 76 | TableMetadata tableMetadata = mappingManager.getSession().getCluster().getMetadata().getKeyspace(ksName).getTable(tableName); |
| 72 | 77 | |
| 73 | 78 | if (tableMetadata == null) |
| 74 | 79 | throw new IllegalArgumentException(String.format("Table %s does not exist in keyspace %s", tableName, ksName)); |
| 75 | 80 | |
| 76 | - List<MappedProperty<T>> pks = new ArrayList<MappedProperty<T>>(); | |
| 77 | - List<MappedProperty<T>> ccs = new ArrayList<MappedProperty<T>>(); | |
| 78 | - List<MappedProperty<T>> rgs = new ArrayList<MappedProperty<T>>(); | |
| 81 | + List<PropertyMapper> pks = new ArrayList<PropertyMapper>(); | |
| 82 | + List<PropertyMapper> ccs = new ArrayList<PropertyMapper>(); | |
| 83 | + List<PropertyMapper> rgs = new ArrayList<PropertyMapper>(); | |
| 79 | 84 | |
| 80 | - BeanInfo beanInfo = ReflectionUtils.getBeanInfo(entityClass); | |
| 85 | + Map<String, Object[]> fieldsAndProperties = ReflectionUtils.scanFieldsAndProperties(entityClass); | |
| 86 | + AtomicInteger columnCounter = mappingManager.isCassandraV1 ? null : new AtomicInteger(0); | |
| 81 | 87 | |
| 82 | - for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) { | |
| 88 | + for (Map.Entry<String, Object[]> entry : fieldsAndProperties.entrySet()) { | |
| 83 | 89 | |
| 84 | - if (descriptor.getName().equals("class")) | |
| 85 | - continue; | |
| 90 | + String propertyName = entry.getKey(); | |
| 91 | + java.lang.reflect.Field field = (java.lang.reflect.Field) entry.getValue()[0]; | |
| 92 | + PropertyDescriptor property = (PropertyDescriptor) entry.getValue()[1]; | |
| 93 | + String alias = (columnCounter != null) | |
| 94 | + ? newAlias(columnCounter.incrementAndGet()) | |
| 95 | + : null; | |
| 86 | 96 | |
| 87 | - MappedProperty<T> property = new MappedProperty<T>(descriptor, entityClass); | |
| 97 | + PropertyMapper propertyMapper = new PropertyMapper(propertyName, alias, field, property); | |
| 88 | 98 | |
| 89 | - if (mappingManager.isCassandraV1 && property.isComputed()) | |
| 99 | + if (mappingManager.isCassandraV1 && propertyMapper.isComputed()) | |
| 90 | 100 | throw new UnsupportedOperationException("Computed properties are not supported with native protocol v1"); |
| 91 | 101 | |
| 92 | - AnnotationChecks.validateAnnotations(property, | |
| 102 | + AnnotationChecks.validateAnnotations(propertyMapper, | |
| 93 | 103 | Column.class, ClusteringColumn.class, Frozen.class, FrozenKey.class, |
| 94 | 104 | FrozenValue.class, PartitionKey.class, Transient.class, Computed.class); |
| 95 | 105 | |
| 96 | - if (property.isTransient()) | |
| 106 | + if (propertyMapper.isTransient()) | |
| 97 | 107 | continue; |
| 98 | 108 | |
| 99 | - switch (property.kind()) { | |
| 100 | - case PARTITION_KEY: | |
| 101 | - pks.add(property); | |
| 102 | - break; | |
| 103 | - case CLUSTERING_COLUMN: | |
| 104 | - ccs.add(property); | |
| 105 | - break; | |
| 106 | - default: | |
| 107 | - rgs.add(property); | |
| 108 | - break; | |
| 109 | - } | |
| 109 | + if (!propertyMapper.isComputed() && tableMetadata.getColumn(propertyMapper.columnName) == null) | |
| 110 | + throw new IllegalArgumentException(String.format("Column %s does not exist in table %s.%s", | |
| 111 | + propertyMapper.columnName, ksName, tableName)); | |
| 112 | + | |
| 113 | + if (propertyMapper.isPartitionKey()) | |
| 114 | + pks.add(propertyMapper); | |
| 115 | + else if (propertyMapper.isClusteringColumn()) | |
| 116 | + ccs.add(propertyMapper); | |
| 117 | + else | |
| 118 | + rgs.add(propertyMapper); | |
| 119 | + | |
| 120 | + // if the property is of a UDT type, parse it now | |
| 121 | + for (Class<?> udt : TypeMappings.findUDTs(propertyMapper.javaType.getType())) | |
| 122 | + mappingManager.getUDTCodec(udt); | |
| 110 | 123 | } |
| 111 | 124 | |
| 112 | - AtomicInteger columnCounter = mappingManager.isCassandraV1 ? null : new AtomicInteger(0); | |
| 113 | - | |
| 114 | - Collections.sort(pks); | |
| 115 | - Collections.sort(ccs); | |
| 125 | + Collections.sort(pks, POSITION_COMPARATOR); | |
| 126 | + Collections.sort(ccs, POSITION_COMPARATOR); | |
| 116 | 127 | |
| 117 | 128 | AnnotationChecks.validateOrder(pks, "@PartitionKey"); |
| 118 | 129 | AnnotationChecks.validateOrder(ccs, "@ClusteringColumn"); |
| 119 | 130 | |
| 120 | - mapper.addColumns( | |
| 121 | - createColumnMappers(pks, factory, mappingManager, columnCounter, tableMetadata, ksName, tableName), | |
| 122 | - createColumnMappers(ccs, factory, mappingManager, columnCounter, tableMetadata, ksName, tableName), | |
| 123 | - createColumnMappers(rgs, factory, mappingManager, columnCounter, tableMetadata, ksName, tableName)); | |
| 131 | + mapper.addColumns(pks, ccs, rgs); | |
| 124 | 132 | return mapper; |
| 125 | 133 | } |
| 126 | 134 | |
| 127 | - private static <T> List<ColumnMapper<T>> createColumnMappers(List<MappedProperty<T>> properties, EntityMapper.Factory factory, MappingManager mappingManager, AtomicInteger columnCounter, TableMetadata tableMetadata, String ksName, String tableName) { | |
| 128 | - List<ColumnMapper<T>> mappers = new ArrayList<ColumnMapper<T>>(properties.size()); | |
| 129 | - for (int i = 0; i < properties.size(); i++) { | |
| 130 | - MappedProperty<T> property = properties.get(i); | |
| 131 | - int pos = property.position(); | |
| 132 | - ColumnMapper<T> columnMapper = factory.createColumnMapper(property, pos < 0 ? i : pos, mappingManager, columnCounter); | |
| 133 | - if (property.isComputed() || tableMetadata.getColumn(columnMapper.getColumnName()) != null) | |
| 134 | - mappers.add(columnMapper); | |
| 135 | - else | |
| 136 | - throw new IllegalArgumentException(String.format("Column %s does not exist in table %s.%s", | |
| 137 | - columnMapper.getColumnName(), ksName, tableName)); | |
| 138 | - } | |
| 139 | - return mappers; | |
| 140 | - } | |
| 141 | - | |
| 142 | - static <T> MappedUDTCodec<T> parseUDT(Class<T> udtClass, EntityMapper.Factory factory, MappingManager mappingManager) { | |
| 135 | + static <T> MappedUDTCodec<T> parseUDT(Class<T> udtClass, MappingManager mappingManager) { | |
| 143 | 136 | UDT udt = AnnotationChecks.getTypeAnnotation(UDT.class, udtClass); |
| 144 | 137 | |
| 145 | 138 | String ksName = udt.caseSensitiveKeyspace() ? udt.keyspace() : udt.keyspace().toLowerCase(); |
| @@ -159,54 +152,36 @@ | ||
| 159 | 152 | if (userType == null) |
| 160 | 153 | throw new IllegalArgumentException(String.format("User type %s does not exist in keyspace %s", udtName, ksName)); |
| 161 | 154 | |
| 162 | - List<MappedProperty<T>> columns = new ArrayList<MappedProperty<T>>(); | |
| 155 | + Map<String, PropertyMapper> propertyMappers = new HashMap<String, PropertyMapper>(); | |
| 163 | 156 | |
| 164 | - BeanInfo beanInfo = ReflectionUtils.getBeanInfo(udtClass); | |
| 157 | + Map<String, Object[]> fieldsAndProperties = ReflectionUtils.scanFieldsAndProperties(udtClass); | |
| 165 | 158 | |
| 166 | - for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) { | |
| 159 | + for (Map.Entry<String, Object[]> entry : fieldsAndProperties.entrySet()) { | |
| 167 | 160 | |
| 168 | - if (descriptor.getName().equals("class")) | |
| 169 | - continue; | |
| 161 | + String propertyName = entry.getKey(); | |
| 162 | + java.lang.reflect.Field field = (java.lang.reflect.Field) entry.getValue()[0]; | |
| 163 | + PropertyDescriptor property = (PropertyDescriptor) entry.getValue()[1]; | |
| 170 | 164 | |
| 171 | - MappedProperty<T> property = new MappedProperty<T>(descriptor, udtClass); | |
| 165 | + PropertyMapper propertyMapper = new PropertyMapper(propertyName, null, field, property); | |
| 172 | 166 | |
| 173 | - AnnotationChecks.validateAnnotations(property, | |
| 167 | + AnnotationChecks.validateAnnotations(propertyMapper, | |
| 174 | 168 | Field.class, Frozen.class, FrozenKey.class, |
| 175 | 169 | FrozenValue.class, Transient.class); |
| 176 | 170 | |
| 177 | - if (property.isTransient()) | |
| 171 | + if (propertyMapper.isTransient()) | |
| 178 | 172 | continue; |
| 179 | 173 | |
| 180 | - AnnotationChecks.validatePrimaryKeyOnUDT(property); | |
| 181 | - columns.add(property); | |
| 182 | - } | |
| 183 | - Map<String, ColumnMapper<T>> columnMappers = createFieldMappers(columns, factory, udtClass, mappingManager, userType, ksName); | |
| 184 | - return new MappedUDTCodec<T>(userType, udtClass, columnMappers, mappingManager); | |
| 185 | - } | |
| 186 | - | |
| 187 | - private static <T> Map<String, ColumnMapper<T>> createFieldMappers(List<MappedProperty<T>> properties, EntityMapper.Factory factory, Class<T> udtClass, MappingManager mappingManager, UserType userType, String ksName) { | |
| 188 | - Map<String, ColumnMapper<T>> mappers = Maps.newHashMapWithExpectedSize(properties.size()); | |
| 189 | - for (int i = 0; i < properties.size(); i++) { | |
| 190 | - MappedProperty<T> property = properties.get(i); | |
| 191 | - int pos = property.position(); | |
| 192 | - ColumnMapper<T> mapper = factory.createColumnMapper(property, pos < 0 ? i : pos, mappingManager, null); | |
| 193 | - if (userType.contains(mapper.getColumnName())) | |
| 194 | - mappers.put(mapper.getColumnName(), mapper); | |
| 195 | - else | |
| 174 | + if (!userType.contains(propertyMapper.columnName)) | |
| 196 | 175 | throw new IllegalArgumentException(String.format("Field %s does not exist in type %s.%s", |
| 197 | - mapper.getColumnName(), ksName, userType.getTypeName())); | |
| 198 | - } | |
| 199 | - return mappers; | |
| 200 | - } | |
| 201 | - | |
| 202 | - | |
| 203 | - static String newAlias(int columnNumber) { | |
| 204 | - return "col" + columnNumber; | |
| 176 | + propertyMapper.columnName, ksName, userType.getTypeName())); | |
| 205 | 177 | |
| 178 | + AnnotationChecks.validatePrimaryKeyOnUDT(propertyMapper); | |
| 179 | + propertyMappers.put(propertyMapper.columnName, propertyMapper); | |
| 180 | + } | |
| 181 | + return new MappedUDTCodec<T>(userType, udtClass, propertyMappers, mappingManager); | |
| 206 | 182 | } |
| 207 | 183 | |
| 208 | - | |
| 209 | - static <T> AccessorMapper<T> parseAccessor(Class<T> accClass, AccessorMapper.Factory factory, MappingManager mappingManager) { | |
| 184 | + static <T> AccessorMapper<T> parseAccessor(Class<T> accClass, MappingManager mappingManager) { | |
| 210 | 185 | if (!accClass.isInterface()) |
| 211 | 186 | throw new IllegalArgumentException("@Accessor annotation is only allowed on interfaces"); |
| 212 | 187 | |
| @@ -267,7 +242,11 @@ | ||
| 267 | 242 | methods.add(new MethodMapper(m, queryString, paramMappers, cl, fetchSize, tracing, idempotent)); |
| 268 | 243 | } |
| 269 | 244 | |
| 270 | - return factory.create(accClass, methods); | |
| 245 | + return new AccessorMapper<T>(accClass, methods); | |
| 246 | + } | |
| 247 | + | |
| 248 | + private static String newAlias(int columnNumber) { | |
| 249 | + return "col" + columnNumber; | |
| 271 | 250 | } |
| 272 | 251 | |
| 273 | 252 | @SuppressWarnings({"unchecked", "rawtypes"}) |
deleted driver-mapping/src/main/java/com/datastax/driver/mapping/ColumnMapper.java +0 −62
| @@ -1,62 +0,0 @@ | ||
| 1 | -/* | |
| 2 | - * Copyright (C) 2012-2015 DataStax Inc. | |
| 3 | - * | |
| 4 | - * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | - * you may not use this file except in compliance with the License. | |
| 6 | - * You may obtain a copy of the License at | |
| 7 | - * | |
| 8 | - * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | - * | |
| 10 | - * Unless required by applicable law or agreed to in writing, software | |
| 11 | - * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | - * See the License for the specific language governing permissions and | |
| 14 | - * limitations under the License. | |
| 15 | - */ | |
| 16 | -package com.datastax.driver.mapping; | |
| 17 | - | |
| 18 | -import com.datastax.driver.core.TypeCodec; | |
| 19 | -import com.google.common.reflect.TypeToken; | |
| 20 | - | |
| 21 | -import java.util.concurrent.atomic.AtomicInteger; | |
| 22 | - | |
| 23 | -abstract class ColumnMapper<T> { | |
| 24 | - | |
| 25 | - final MappedProperty<T> property; | |
| 26 | - final String alias; | |
| 27 | - final int position; | |
| 28 | - | |
| 29 | - @SuppressWarnings("unchecked") | |
| 30 | - protected ColumnMapper(MappedProperty<T> property, int position, AtomicInteger columnCounter) { | |
| 31 | - this.property = property; | |
| 32 | - this.position = position; | |
| 33 | - this.alias = (columnCounter != null) | |
| 34 | - ? AnnotationParser.newAlias(columnCounter.incrementAndGet()) | |
| 35 | - : null; | |
| 36 | - } | |
| 37 | - | |
| 38 | - abstract Object getValue(T entity); | |
| 39 | - | |
| 40 | - abstract void setValue(T entity, Object value); | |
| 41 | - | |
| 42 | - String getColumnName() { | |
| 43 | - return property.columnName(); | |
| 44 | - } | |
| 45 | - | |
| 46 | - String getAlias() { | |
| 47 | - return alias; | |
| 48 | - } | |
| 49 | - | |
| 50 | - public TypeCodec<Object> getCustomCodec() { | |
| 51 | - return property.customCodec(); | |
| 52 | - } | |
| 53 | - | |
| 54 | - /** | |
| 55 | - * The Java type of this column. | |
| 56 | - */ | |
| 57 | - @SuppressWarnings("unchecked") | |
| 58 | - public TypeToken<Object> getJavaType() { | |
| 59 | - return (TypeToken<Object>) property.type(); | |
| 60 | - } | |
| 61 | - | |
| 62 | -} |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/EntityMapper.java +11 −27
| @@ -19,26 +19,24 @@ | ||
| 19 | 19 | |
| 20 | 20 | import java.util.ArrayList; |
| 21 | 21 | import java.util.List; |
| 22 | -import java.util.concurrent.atomic.AtomicInteger; | |
| 23 | 22 | |
| 24 | 23 | import static com.datastax.driver.core.querybuilder.QueryBuilder.quote; |
| 25 | 24 | |
| 26 | -abstract class EntityMapper<T> { | |
| 25 | +class EntityMapper<T> { | |
| 27 | 26 | |
| 28 | - final Class<T> entityClass; | |
| 27 | + private final Class<T> entityClass; | |
| 29 | 28 | private final String keyspace; |
| 30 | 29 | private final String table; |
| 31 | 30 | |
| 32 | 31 | final ConsistencyLevel writeConsistency; |
| 33 | 32 | final ConsistencyLevel readConsistency; |
| 34 | 33 | |
| 35 | - final List<ColumnMapper<T>> partitionKeys = new ArrayList<ColumnMapper<T>>(); | |
| 36 | - final List<ColumnMapper<T>> clusteringColumns = new ArrayList<ColumnMapper<T>>(); | |
| 37 | - final List<ColumnMapper<T>> regularColumns = new ArrayList<ColumnMapper<T>>(); | |
| 34 | + final List<PropertyMapper> partitionKeys = new ArrayList<PropertyMapper>(); | |
| 35 | + final List<PropertyMapper> clusteringColumns = new ArrayList<PropertyMapper>(); | |
| 38 | 36 | |
| 39 | - private final List<ColumnMapper<T>> allColumns = new ArrayList<ColumnMapper<T>>(); | |
| 37 | + final List<PropertyMapper> allColumns = new ArrayList<PropertyMapper>(); | |
| 40 | 38 | |
| 41 | - protected EntityMapper(Class<T> entityClass, String keyspace, String table, ConsistencyLevel writeConsistency, ConsistencyLevel readConsistency) { | |
| 39 | + EntityMapper(Class<T> entityClass, String keyspace, String table, ConsistencyLevel writeConsistency, ConsistencyLevel readConsistency) { | |
| 42 | 40 | this.entityClass = entityClass; |
| 43 | 41 | this.keyspace = keyspace; |
| 44 | 42 | this.table = table; |
| @@ -58,34 +56,20 @@ | ||
| 58 | 56 | return partitionKeys.size() + clusteringColumns.size(); |
| 59 | 57 | } |
| 60 | 58 | |
| 61 | - ColumnMapper<T> getPrimaryKeyColumn(int i) { | |
| 59 | + PropertyMapper getPrimaryKeyColumn(int i) { | |
| 62 | 60 | return i < partitionKeys.size() ? partitionKeys.get(i) : clusteringColumns.get(i - partitionKeys.size()); |
| 63 | 61 | } |
| 64 | 62 | |
| 65 | - void addColumns(List<ColumnMapper<T>> pks, List<ColumnMapper<T>> ccs, List<ColumnMapper<T>> rgs) { | |
| 63 | + void addColumns(List<PropertyMapper> pks, List<PropertyMapper> ccs, List<PropertyMapper> rgs) { | |
| 66 | 64 | partitionKeys.addAll(pks); |
| 67 | - allColumns.addAll(pks); | |
| 68 | - | |
| 69 | 65 | clusteringColumns.addAll(ccs); |
| 66 | + allColumns.addAll(pks); | |
| 70 | 67 | allColumns.addAll(ccs); |
| 71 | - | |
| 72 | - addColumns(rgs); | |
| 73 | - } | |
| 74 | - | |
| 75 | - void addColumns(List<ColumnMapper<T>> rgs) { | |
| 76 | - regularColumns.addAll(rgs); | |
| 77 | 68 | allColumns.addAll(rgs); |
| 78 | 69 | } |
| 79 | 70 | |
| 80 | - abstract T newEntity(); | |
| 81 | - | |
| 82 | - List<ColumnMapper<T>> allColumns() { | |
| 83 | - return allColumns; | |
| 71 | + T newEntity() { | |
| 72 | + return ReflectionUtils.newInstance(entityClass); | |
| 84 | 73 | } |
| 85 | 74 | |
| 86 | - interface Factory { | |
| 87 | - public <T> EntityMapper<T> create(Class<T> entityClass, String keyspace, String table, ConsistencyLevel writeConsistency, ConsistencyLevel readConsistency); | |
| 88 | - | |
| 89 | - public <T> ColumnMapper<T> createColumnMapper(MappedProperty<T> property, int position, MappingManager mappingManager, AtomicInteger columnCounter); | |
| 90 | - } | |
| 91 | 75 | } |
deleted driver-mapping/src/main/java/com/datastax/driver/mapping/MappedProperty.java +0 −203
| @@ -1,203 +0,0 @@ | ||
| 1 | -/* | |
| 2 | - * Copyright (C) 2012-2015 DataStax Inc. | |
| 3 | - * | |
| 4 | - * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | - * you may not use this file except in compliance with the License. | |
| 6 | - * You may obtain a copy of the License at | |
| 7 | - * | |
| 8 | - * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | - * | |
| 10 | - * Unless required by applicable law or agreed to in writing, software | |
| 11 | - * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | - * See the License for the specific language governing permissions and | |
| 14 | - * limitations under the License. | |
| 15 | - */ | |
| 16 | -package com.datastax.driver.mapping; | |
| 17 | - | |
| 18 | -import com.datastax.driver.core.Metadata; | |
| 19 | -import com.datastax.driver.core.TypeCodec; | |
| 20 | -import com.datastax.driver.mapping.annotations.*; | |
| 21 | -import com.google.common.collect.ComparisonChain; | |
| 22 | -import com.google.common.reflect.TypeToken; | |
| 23 | - | |
| 24 | -import java.beans.PropertyDescriptor; | |
| 25 | -import java.lang.annotation.Annotation; | |
| 26 | -import java.lang.reflect.Field; | |
| 27 | -import java.lang.reflect.Method; | |
| 28 | -import java.lang.reflect.Type; | |
| 29 | -import java.util.Collection; | |
| 30 | -import java.util.Map; | |
| 31 | - | |
| 32 | -/** | |
| 33 | - * A bean property mapped to a table column or a UDT field. | |
| 34 | - * | |
| 35 | - * @param <T> The component classe where this property belongs (either | |
| 36 | - * a {@link com.datastax.driver.mapping.annotations.Table @Table} | |
| 37 | - * or {@link com.datastax.driver.mapping.annotations.UDT @UDT} | |
| 38 | - * annotated class). | |
| 39 | - */ | |
| 40 | -class MappedProperty<T> implements Comparable<MappedProperty<T>> { | |
| 41 | - | |
| 42 | - enum Kind {PARTITION_KEY, CLUSTERING_COLUMN, REGULAR, COMPUTED} | |
| 43 | - | |
| 44 | - private final PropertyDescriptor property; | |
| 45 | - private final Field field; | |
| 46 | - private final Method getter; | |
| 47 | - private final Method setter; | |
| 48 | - private final Map<Class<? extends Annotation>, Annotation> annotations; | |
| 49 | - private final String columnName; | |
| 50 | - private final TypeToken<Object> type; | |
| 51 | - private final TypeCodec<Object> customCodec; | |
| 52 | - | |
| 53 | - MappedProperty(PropertyDescriptor property, Class<T> componentClass) { | |
| 54 | - this.property = property; | |
| 55 | - field = ReflectionUtils.findField(property.getName(), componentClass); | |
| 56 | - getter = ReflectionUtils.findGetter(property); | |
| 57 | - setter = ReflectionUtils.findSetter(property); | |
| 58 | - annotations = ReflectionUtils.findAnnotations(property, componentClass); | |
| 59 | - columnName = createColumnName(); | |
| 60 | - type = inferGenericType(); | |
| 61 | - customCodec = createCustomCodec(); | |
| 62 | - } | |
| 63 | - | |
| 64 | - boolean hasAnnotation(Class<? extends Annotation> annotationClass) { | |
| 65 | - return annotations.containsKey(annotationClass); | |
| 66 | - } | |
| 67 | - | |
| 68 | - Collection<Annotation> annotations() { | |
| 69 | - return annotations.values(); | |
| 70 | - } | |
| 71 | - | |
| 72 | - @SuppressWarnings("unchecked") | |
| 73 | - <A extends Annotation> A annotation(Class<A> annotationClass) { | |
| 74 | - return (A) annotations.get(annotationClass); | |
| 75 | - } | |
| 76 | - | |
| 77 | - boolean isComputed() { | |
| 78 | - return hasAnnotation(Computed.class); | |
| 79 | - } | |
| 80 | - | |
| 81 | - boolean isTransient() { | |
| 82 | - return hasAnnotation(Transient.class); | |
| 83 | - } | |
| 84 | - | |
| 85 | - boolean isPartitionKey() { | |
| 86 | - return hasAnnotation(PartitionKey.class); | |
| 87 | - } | |
| 88 | - | |
| 89 | - boolean isClusteringColumn() { | |
| 90 | - return hasAnnotation(ClusteringColumn.class); | |
| 91 | - } | |
| 92 | - | |
| 93 | - Method getter() { | |
| 94 | - return getter; | |
| 95 | - } | |
| 96 | - | |
| 97 | - Method setter() { | |
| 98 | - return setter; | |
| 99 | - } | |
| 100 | - | |
| 101 | - String name() { | |
| 102 | - return property.getName(); | |
| 103 | - } | |
| 104 | - | |
| 105 | - TypeToken<?> type() { | |
| 106 | - return type; | |
| 107 | - } | |
| 108 | - | |
| 109 | - String columnName() { | |
| 110 | - return columnName; | |
| 111 | - } | |
| 112 | - | |
| 113 | - TypeCodec<Object> customCodec() { | |
| 114 | - return customCodec; | |
| 115 | - } | |
| 116 | - | |
| 117 | - int position() { | |
| 118 | - if (isPartitionKey()) { | |
| 119 | - return annotation(PartitionKey.class).value(); | |
| 120 | - } | |
| 121 | - if (isClusteringColumn()) { | |
| 122 | - return annotation(ClusteringColumn.class).value(); | |
| 123 | - } | |
| 124 | - return -1; | |
| 125 | - } | |
| 126 | - | |
| 127 | - Kind kind() { | |
| 128 | - if (isPartitionKey()) { | |
| 129 | - return Kind.PARTITION_KEY; | |
| 130 | - } | |
| 131 | - if (isClusteringColumn()) { | |
| 132 | - return Kind.CLUSTERING_COLUMN; | |
| 133 | - } | |
| 134 | - if (isComputed()) { | |
| 135 | - return Kind.COMPUTED; | |
| 136 | - } | |
| 137 | - return Kind.REGULAR; | |
| 138 | - } | |
| 139 | - | |
| 140 | - private String createColumnName() { | |
| 141 | - Column column = annotation(Column.class); | |
| 142 | - if (column != null && !column.name().isEmpty()) { | |
| 143 | - return Metadata.quote(column.caseSensitive() ? column.name() : column.name().toLowerCase()); | |
| 144 | - } | |
| 145 | - com.datastax.driver.mapping.annotations.Field udtField = annotation(com.datastax.driver.mapping.annotations.Field.class); | |
| 146 | - if (udtField != null && !udtField.name().isEmpty()) { | |
| 147 | - return Metadata.quote(udtField.caseSensitive() ? udtField.name() : udtField.name().toLowerCase()); | |
| 148 | - } | |
| 149 | - if (isComputed()) { | |
| 150 | - return annotation(Computed.class).value(); | |
| 151 | - } | |
| 152 | - return Metadata.quote(name().toLowerCase()); | |
| 153 | - } | |
| 154 | - | |
| 155 | - @SuppressWarnings("unchecked") | |
| 156 | - private TypeToken<Object> inferGenericType() { | |
| 157 | - Type type; | |
| 158 | - if (field != null) | |
| 159 | - type = field.getGenericType(); | |
| 160 | - else if (getter != null) | |
| 161 | - type = getter.getGenericReturnType(); | |
| 162 | - else | |
| 163 | - // this will not work for generic types | |
| 164 | - type = property.getPropertyType(); | |
| 165 | - return (TypeToken<Object>) TypeToken.of(type); | |
| 166 | - } | |
| 167 | - | |
| 168 | - private TypeCodec<Object> createCustomCodec() { | |
| 169 | - Class<? extends TypeCodec<?>> codecClass = getCustomCodecClass(); | |
| 170 | - if (codecClass.equals(Defaults.NoCodec.class)) | |
| 171 | - return null; | |
| 172 | - try { | |
| 173 | - @SuppressWarnings("unchecked") | |
| 174 | - TypeCodec<Object> instance = (TypeCodec<Object>) codecClass.newInstance(); | |
| 175 | - return instance; | |
| 176 | - } catch (Exception e) { | |
| 177 | - throw new IllegalArgumentException(String.format( | |
| 178 | - "Cannot create an instance of custom codec %s for property %s", | |
| 179 | - codecClass, property | |
| 180 | - ), e); | |
| 181 | - } | |
| 182 | - } | |
| 183 | - | |
| 184 | - private Class<? extends TypeCodec<?>> getCustomCodecClass() { | |
| 185 | - Column column = annotation(Column.class); | |
| 186 | - if (column != null) | |
| 187 | - return column.codec(); | |
| 188 | - com.datastax.driver.mapping.annotations.Field udtField = annotation(com.datastax.driver.mapping.annotations.Field.class); | |
| 189 | - if (udtField != null) | |
| 190 | - return udtField.codec(); | |
| 191 | - return Defaults.NoCodec.class; | |
| 192 | - } | |
| 193 | - | |
| 194 | - @Override | |
| 195 | - public int compareTo(MappedProperty<T> that) { | |
| 196 | - return ComparisonChain.start() | |
| 197 | - .compare(this.kind(), that.kind()) | |
| 198 | - .compare(this.position(), that.position()) | |
| 199 | - .compare(this.name(), that.name()) | |
| 200 | - .result(); | |
| 201 | - } | |
| 202 | - | |
| 203 | -} |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MappedUDTCodec.java +13 −17
| @@ -26,10 +26,10 @@ | ||
| 26 | 26 | class MappedUDTCodec<T> extends TypeCodec.AbstractUDTCodec<T> { |
| 27 | 27 | private final UserType cqlUserType; |
| 28 | 28 | private final Class<T> udtClass; |
| 29 | - private final Map<String, ColumnMapper<T>> columnMappers; | |
| 29 | + private final Map<String, PropertyMapper> columnMappers; | |
| 30 | 30 | private final CodecRegistry codecRegistry; |
| 31 | 31 | |
| 32 | - public MappedUDTCodec(UserType cqlUserType, Class<T> udtClass, Map<String, ColumnMapper<T>> columnMappers, MappingManager mappingManager) { | |
| 32 | + MappedUDTCodec(UserType cqlUserType, Class<T> udtClass, Map<String, PropertyMapper> columnMappers, MappingManager mappingManager) { | |
| 33 | 33 | super(cqlUserType, udtClass); |
| 34 | 34 | this.cqlUserType = cqlUserType; |
| 35 | 35 | this.udtClass = udtClass; |
| @@ -39,11 +39,7 @@ | ||
| 39 | 39 | |
| 40 | 40 | @Override |
| 41 | 41 | protected T newInstance() { |
| 42 | - try { | |
| 43 | - return udtClass.newInstance(); | |
| 44 | - } catch (Exception e) { | |
| 45 | - throw new IllegalArgumentException("Error creating instance of @UDT-annotated class " + udtClass, e); | |
| 46 | - } | |
| 42 | + return ReflectionUtils.newInstance(udtClass); | |
| 47 | 43 | } |
| 48 | 44 | |
| 49 | 45 | Class<T> getUdtClass() { |
| @@ -56,16 +52,16 @@ | ||
| 56 | 52 | if (!fieldName.startsWith("\"")) |
| 57 | 53 | fieldName = Metadata.quote(fieldName); |
| 58 | 54 | |
| 59 | - ColumnMapper<T> columnMapper = columnMappers.get(fieldName); | |
| 55 | + PropertyMapper propertyMapper = columnMappers.get(fieldName); | |
| 60 | 56 | |
| 61 | - if (columnMapper == null) | |
| 57 | + if (propertyMapper == null) | |
| 62 | 58 | return null; |
| 63 | 59 | |
| 64 | - Object value = columnMapper.getValue(source); | |
| 60 | + Object value = propertyMapper.getValue(source); | |
| 65 | 61 | |
| 66 | - TypeCodec<Object> codec = columnMapper.getCustomCodec(); | |
| 62 | + TypeCodec<Object> codec = propertyMapper.customCodec; | |
| 67 | 63 | if (codec == null) |
| 68 | - codec = codecRegistry.codecFor(cqlUserType.getFieldType(columnMapper.getColumnName()), columnMapper.getJavaType()); | |
| 64 | + codec = codecRegistry.codecFor(cqlUserType.getFieldType(propertyMapper.columnName), propertyMapper.javaType); | |
| 69 | 65 | |
| 70 | 66 | return codec.serialize(value, protocolVersion); |
| 71 | 67 | } |
| @@ -75,12 +71,12 @@ | ||
| 75 | 71 | if (!fieldName.startsWith("\"")) |
| 76 | 72 | fieldName = Metadata.quote(fieldName); |
| 77 | 73 | |
| 78 | - ColumnMapper<T> columnMapper = columnMappers.get(fieldName); | |
| 79 | - if (columnMapper != null) { | |
| 80 | - TypeCodec<Object> codec = columnMapper.getCustomCodec(); | |
| 74 | + PropertyMapper propertyMapper = columnMappers.get(fieldName); | |
| 75 | + if (propertyMapper != null) { | |
| 76 | + TypeCodec<Object> codec = propertyMapper.customCodec; | |
| 81 | 77 | if (codec == null) |
| 82 | - codec = codecRegistry.codecFor(cqlUserType.getFieldType(columnMapper.getColumnName()), columnMapper.getJavaType()); | |
| 83 | - columnMapper.setValue(target, codec.deserialize(input, protocolVersion)); | |
| 78 | + codec = codecRegistry.codecFor(cqlUserType.getFieldType(propertyMapper.columnName), propertyMapper.javaType); | |
| 79 | + propertyMapper.setValue(target, codec.deserialize(input, protocolVersion)); | |
| 84 | 80 | } |
| 85 | 81 | return target; |
| 86 | 82 | } |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/Mapper.java +25 −27
| @@ -49,11 +49,10 @@ | ||
| 49 | 49 | private static final Logger logger = LoggerFactory.getLogger(Mapper.class); |
| 50 | 50 | private static final Function<Object, Void> TO_NULL = Functions.constant(null); |
| 51 | 51 | |
| 52 | - final MappingManager manager; | |
| 53 | - final ProtocolVersion protocolVersion; | |
| 54 | - final Class<T> klass; | |
| 55 | - final EntityMapper<T> mapper; | |
| 56 | - final TableMetadata tableMetadata; | |
| 52 | + private final MappingManager manager; | |
| 53 | + private final Class<T> klass; | |
| 54 | + private final EntityMapper<T> mapper; | |
| 55 | + private final TableMetadata tableMetadata; | |
| 57 | 56 | |
| 58 | 57 | // Cache prepared statements for each type of query we use. |
| 59 | 58 | private final ConcurrentMap<MapperQueryKey, ListenableFuture<PreparedStatement>> preparedQueries = new ConcurrentHashMap<MapperQueryKey, ListenableFuture<PreparedStatement>>(); |
| @@ -64,7 +63,7 @@ | ||
| 64 | 63 | |
| 65 | 64 | private static final EnumMap<Option.Type, Option> NO_OPTIONS = new EnumMap<Option.Type, Option>(Option.Type.class); |
| 66 | 65 | |
| 67 | - final Function<ResultSet, T> mapOneFunction; | |
| 66 | + private final Function<ResultSet, T> mapOneFunction; | |
| 68 | 67 | final Function<ResultSet, T> mapOneFunctionWithoutAliases; |
| 69 | 68 | final Function<ResultSet, Result<T>> mapAllFunctionWithoutAliases; |
| 70 | 69 | |
| @@ -76,7 +75,6 @@ | ||
| 76 | 75 | KeyspaceMetadata keyspace = session().getCluster().getMetadata().getKeyspace(mapper.getKeyspace()); |
| 77 | 76 | this.tableMetadata = keyspace == null ? null : keyspace.getTable(mapper.getTable()); |
| 78 | 77 | |
| 79 | - this.protocolVersion = manager.getSession().getCluster().getConfiguration().getProtocolOptions().getProtocolVersion(); | |
| 80 | 78 | this.mapOneFunction = new Function<ResultSet, T>() { |
| 81 | 79 | @Override |
| 82 | 80 | public T apply(ResultSet rs) { |
| @@ -105,7 +103,7 @@ | ||
| 105 | 103 | return manager.getSession(); |
| 106 | 104 | } |
| 107 | 105 | |
| 108 | - ListenableFuture<PreparedStatement> getPreparedQueryAsync(QueryType type, Set<ColumnMapper<?>> columns, EnumMap<Option.Type, Option> options) { | |
| 106 | + ListenableFuture<PreparedStatement> getPreparedQueryAsync(QueryType type, Set<PropertyMapper> columns, EnumMap<Option.Type, Option> options) { | |
| 109 | 107 | |
| 110 | 108 | final MapperQueryKey pqk = new MapperQueryKey(type, columns, options); |
| 111 | 109 | ListenableFuture<PreparedStatement> existingFuture = preparedQueries.get(pqk); |
| @@ -139,7 +137,7 @@ | ||
| 139 | 137 | } |
| 140 | 138 | |
| 141 | 139 | ListenableFuture<PreparedStatement> getPreparedQueryAsync(QueryType type, EnumMap<Option.Type, Option> options) { |
| 142 | - return getPreparedQueryAsync(type, Collections.<ColumnMapper<?>>emptySet(), options); | |
| 140 | + return getPreparedQueryAsync(type, Collections.<PropertyMapper>emptySet(), options); | |
| 143 | 141 | } |
| 144 | 142 | |
| 145 | 143 | Class<T> getMappedClass() { |
| @@ -213,13 +211,13 @@ | ||
| 213 | 211 | } |
| 214 | 212 | |
| 215 | 213 | private ListenableFuture<BoundStatement> saveQueryAsync(T entity, final EnumMap<Option.Type, Option> options) { |
| 216 | - final Map<ColumnMapper<?>, Object> values = new HashMap<ColumnMapper<?>, Object>(); | |
| 214 | + final Map<PropertyMapper, Object> values = new HashMap<PropertyMapper, Object>(); | |
| 217 | 215 | boolean saveNullFields = shouldSaveNullFields(options); |
| 218 | 216 | |
| 219 | - for (ColumnMapper<T> cm : mapper.allColumns()) { | |
| 220 | - Object value = cm.getValue(entity); | |
| 221 | - if (!cm.property.isComputed() && (saveNullFields || value != null)) { | |
| 222 | - values.put(cm, value); | |
| 217 | + for (PropertyMapper col : mapper.allColumns) { | |
| 218 | + Object value = col.getValue(entity); | |
| 219 | + if (!col.isComputed() && (saveNullFields || value != null)) { | |
| 220 | + values.put(col, value); | |
| 223 | 221 | } |
| 224 | 222 | } |
| 225 | 223 | |
| @@ -228,8 +226,8 @@ | ||
| 228 | 226 | public BoundStatement apply(PreparedStatement input) { |
| 229 | 227 | BoundStatement bs = input.bind(); |
| 230 | 228 | int i = 0; |
| 231 | - for (Map.Entry<ColumnMapper<?>, Object> entry : values.entrySet()) { | |
| 232 | - ColumnMapper<?> mapper = entry.getKey(); | |
| 229 | + for (Map.Entry<PropertyMapper, Object> entry : values.entrySet()) { | |
| 230 | + PropertyMapper mapper = entry.getKey(); | |
| 233 | 231 | Object value = entry.getValue(); |
| 234 | 232 | setObject(bs, i++, value, mapper); |
| 235 | 233 | } |
| @@ -252,12 +250,12 @@ | ||
| 252 | 250 | return option == null || option.saveNullFields; |
| 253 | 251 | } |
| 254 | 252 | |
| 255 | - private static void setObject(BoundStatement bs, int i, Object value, ColumnMapper<?> mapper) { | |
| 256 | - TypeCodec<Object> customCodec = mapper.getCustomCodec(); | |
| 253 | + private static void setObject(BoundStatement bs, int i, Object value, PropertyMapper mapper) { | |
| 254 | + TypeCodec<Object> customCodec = mapper.customCodec; | |
| 257 | 255 | if (customCodec != null) |
| 258 | 256 | bs.set(i, value, customCodec); |
| 259 | 257 | else |
| 260 | - bs.set(i, value, mapper.getJavaType()); | |
| 258 | + bs.set(i, value, mapper.javaType); | |
| 261 | 259 | } |
| 262 | 260 | |
| 263 | 261 | /** |
| @@ -390,9 +388,9 @@ | ||
| 390 | 388 | BoundStatement bs = new MapperBoundStatement(input); |
| 391 | 389 | int i = 0; |
| 392 | 390 | for (Object value : primaryKeys) { |
| 393 | - ColumnMapper<T> column = mapper.getPrimaryKeyColumn(i); | |
| 391 | + PropertyMapper column = mapper.getPrimaryKeyColumn(i); | |
| 394 | 392 | if (value == null) { |
| 395 | - throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i)); | |
| 393 | + throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.columnName, i)); | |
| 396 | 394 | } |
| 397 | 395 | setObject(bs, i++, value, column); |
| 398 | 396 | } |
| @@ -599,9 +597,9 @@ | ||
| 599 | 597 | |
| 600 | 598 | int columnNumber = 0; |
| 601 | 599 | for (Object value : primaryKey) { |
| 602 | - ColumnMapper<T> column = mapper.getPrimaryKeyColumn(columnNumber); | |
| 600 | + PropertyMapper column = mapper.getPrimaryKeyColumn(columnNumber); | |
| 603 | 601 | if (value == null) { |
| 604 | - throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i)); | |
| 602 | + throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.columnName, i)); | |
| 605 | 603 | } |
| 606 | 604 | setObject(bs, i++, value, column); |
| 607 | 605 | columnNumber++; |
| @@ -1130,14 +1128,14 @@ | ||
| 1130 | 1128 | private static class MapperQueryKey { |
| 1131 | 1129 | private final QueryType queryType; |
| 1132 | 1130 | private final EnumSet<Option.Type> optionTypes; |
| 1133 | - private final Set<ColumnMapper<?>> columns; | |
| 1131 | + private final Set<PropertyMapper> columns; | |
| 1134 | 1132 | |
| 1135 | - MapperQueryKey(QueryType queryType, Set<ColumnMapper<?>> columnMappers, EnumMap<Option.Type, Option> options) { | |
| 1133 | + MapperQueryKey(QueryType queryType, Set<PropertyMapper> propertyMappers, EnumMap<Option.Type, Option> options) { | |
| 1136 | 1134 | Preconditions.checkNotNull(queryType); |
| 1137 | 1135 | Preconditions.checkNotNull(options); |
| 1138 | - Preconditions.checkNotNull(columnMappers); | |
| 1136 | + Preconditions.checkNotNull(propertyMappers); | |
| 1139 | 1137 | this.queryType = queryType; |
| 1140 | - this.columns = columnMappers; | |
| 1138 | + this.columns = propertyMappers; | |
| 1141 | 1139 | this.optionTypes = EnumSet.noneOf(Option.Type.class); |
| 1142 | 1140 | for (Option opt : options.values()) { |
| 1143 | 1141 | if (opt.isIncludedInQuery()) |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MappingManager.java +3 −3
| @@ -223,7 +223,7 @@ | ||
| 223 | 223 | synchronized (mappers) { |
| 224 | 224 | mapper = (Mapper<T>) mappers.get(klass); |
| 225 | 225 | if (mapper == null) { |
| 226 | - EntityMapper<T> entityMapper = AnnotationParser.parseEntity(klass, ReflectionMapper.factory(), this); | |
| 226 | + EntityMapper<T> entityMapper = AnnotationParser.parseEntity(klass, this); | |
| 227 | 227 | mapper = new Mapper<T>(this, klass, entityMapper); |
| 228 | 228 | Map<Class<?>, Mapper<?>> newMappers = new HashMap<Class<?>, Mapper<?>>(mappers); |
| 229 | 229 | newMappers.put(klass, mapper); |
| @@ -241,7 +241,7 @@ | ||
| 241 | 241 | synchronized (udtCodecs) { |
| 242 | 242 | codec = (MappedUDTCodec<T>) udtCodecs.get(mappedClass); |
| 243 | 243 | if (codec == null) { |
| 244 | - codec = AnnotationParser.parseUDT(mappedClass, ReflectionMapper.factory(), this); | |
| 244 | + codec = AnnotationParser.parseUDT(mappedClass, this); | |
| 245 | 245 | session.getCluster().getConfiguration().getCodecRegistry().register(codec); |
| 246 | 246 | |
| 247 | 247 | HashMap<Class<?>, MappedUDTCodec<?>> newCodecs = new HashMap<Class<?>, MappedUDTCodec<?>>(udtCodecs); |
| @@ -260,7 +260,7 @@ | ||
| 260 | 260 | synchronized (accessors) { |
| 261 | 261 | accessor = (T) accessors.get(klass); |
| 262 | 262 | if (accessor == null) { |
| 263 | - AccessorMapper<T> mapper = AnnotationParser.parseAccessor(klass, AccessorReflectionMapper.factory(), this); | |
| 263 | + AccessorMapper<T> mapper = AnnotationParser.parseAccessor(klass, this); | |
| 264 | 264 | mapper.prepare(this); |
| 265 | 265 | accessor = mapper.createProxy(); |
| 266 | 266 | Map<Class<?>, Object> newAccessors = new HashMap<Class<?>, Object>(accessors); |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MethodMapper.java +6 −9
| @@ -26,13 +26,11 @@ | ||
| 26 | 26 | import java.lang.reflect.Type; |
| 27 | 27 | import java.util.Set; |
| 28 | 28 | |
| 29 | -// TODO: we probably should make that an abstract class and move some bit in a "ReflexionMethodMapper" | |
| 30 | -// subclass for consistency with the rest, but we can see to that later | |
| 31 | 29 | class MethodMapper { |
| 32 | 30 | |
| 33 | - public final Method method; | |
| 34 | - public final String queryString; | |
| 35 | - public final ParamMapper[] paramMappers; | |
| 31 | + final Method method; | |
| 32 | + final String queryString; | |
| 33 | + private final ParamMapper[] paramMappers; | |
| 36 | 34 | |
| 37 | 35 | private final ConsistencyLevel consistency; |
| 38 | 36 | private final int fetchSize; |
| @@ -132,17 +130,16 @@ | ||
| 132 | 130 | throw new RuntimeException(String.format("Cannot map return of method %s to unsupported type %s", method, type)); |
| 133 | 131 | |
| 134 | 132 | try { |
| 135 | - this.returnMapper = (Mapper<?>) manager.mapper((Class<?>) type); | |
| 133 | + this.returnMapper = manager.mapper((Class<?>) type); | |
| 136 | 134 | } catch (Exception e) { |
| 137 | 135 | throw new RuntimeException("Cannot map return to class " + fullReturnType, e); |
| 138 | 136 | } |
| 139 | 137 | } |
| 140 | 138 | |
| 141 | - public Object invoke(Object[] args) { | |
| 139 | + Object invoke(Object[] args) { | |
| 142 | 140 | |
| 143 | 141 | BoundStatement bs = statement.bind(); |
| 144 | 142 | |
| 145 | - ProtocolVersion protocolVersion = session.getCluster().getConfiguration().getProtocolOptions().getProtocolVersion(); | |
| 146 | 143 | for (int i = 0; i < args.length; i++) { |
| 147 | 144 | paramMappers[i].setValue(bs, args[i]); |
| 148 | 145 | } |
| @@ -185,7 +182,7 @@ | ||
| 185 | 182 | private final TypeCodec<Object> codec; |
| 186 | 183 | |
| 187 | 184 | @SuppressWarnings("unchecked") |
| 188 | - public ParamMapper(String paramName, int paramIdx, TypeToken<?> paramType, Class<? extends TypeCodec<?>> codecClass) { | |
| 185 | + ParamMapper(String paramName, int paramIdx, TypeToken<?> paramType, Class<? extends TypeCodec<?>> codecClass) { | |
| 189 | 186 | this.paramName = paramName; |
| 190 | 187 | this.paramIdx = paramIdx; |
| 191 | 188 | this.paramType = (TypeToken<Object>) paramType; |
added driver-mapping/src/main/java/com/datastax/driver/mapping/PropertyMapper.java +184 −0
| @@ -0,0 +1,184 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2015 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | +package com.datastax.driver.mapping; | |
| 17 | + | |
| 18 | +import com.datastax.driver.core.Metadata; | |
| 19 | +import com.datastax.driver.core.TypeCodec; | |
| 20 | +import com.datastax.driver.mapping.annotations.*; | |
| 21 | +import com.google.common.reflect.TypeToken; | |
| 22 | + | |
| 23 | +import java.beans.PropertyDescriptor; | |
| 24 | +import java.lang.annotation.Annotation; | |
| 25 | +import java.lang.reflect.Field; | |
| 26 | +import java.lang.reflect.Method; | |
| 27 | +import java.lang.reflect.Type; | |
| 28 | +import java.util.Collection; | |
| 29 | +import java.util.Map; | |
| 30 | + | |
| 31 | +/** | |
| 32 | + * Maps a Java bean property to a table column or a UDT field. | |
| 33 | + * <p> | |
| 34 | + * Properties can be either accessed through getter and setter pairs, | |
| 35 | + * or by direct field access, depending on what is available in the | |
| 36 | + * entity/UDT class. | |
| 37 | + */ | |
| 38 | +class PropertyMapper { | |
| 39 | + | |
| 40 | + private final String propertyName; | |
| 41 | + final String alias; | |
| 42 | + final String columnName; | |
| 43 | + final TypeToken<Object> javaType; | |
| 44 | + final TypeCodec<Object> customCodec; | |
| 45 | + | |
| 46 | + private final Field field; | |
| 47 | + private final Method getter; | |
| 48 | + private final Method setter; | |
| 49 | + private final int position; | |
| 50 | + private final Map<Class<? extends Annotation>, Annotation> annotations; | |
| 51 | + | |
| 52 | + PropertyMapper(String propertyName, String alias, Field field, PropertyDescriptor property) { | |
| 53 | + this.propertyName = propertyName; | |
| 54 | + this.alias = alias; | |
| 55 | + this.field = field; | |
| 56 | + getter = ReflectionUtils.findGetter(property); | |
| 57 | + setter = ReflectionUtils.findSetter(property); | |
| 58 | + annotations = ReflectionUtils.scanPropertyAnnotations(field, property); | |
| 59 | + columnName = inferColumnName(); | |
| 60 | + position = inferPosition(); | |
| 61 | + javaType = inferJavaType(property); | |
| 62 | + customCodec = createCustomCodec(); | |
| 63 | + } | |
| 64 | + | |
| 65 | + Object getValue(Object entity) { | |
| 66 | + try { | |
| 67 | + // try getter first, if available, otherwise direct field access | |
| 68 | + if (getter != null) | |
| 69 | + return getter.invoke(entity); | |
| 70 | + else | |
| 71 | + return field.get(entity); | |
| 72 | + } catch (Exception e) { | |
| 73 | + throw new IllegalStateException("Unable to read property '" + propertyName + "' in " + entity.getClass().getName(), e); | |
| 74 | + } | |
| 75 | + } | |
| 76 | + | |
| 77 | + void setValue(Object entity, Object value) { | |
| 78 | + try { | |
| 79 | + // try setter first, if available, otherwise direct field access | |
| 80 | + if (setter != null) | |
| 81 | + setter.invoke(entity, value); | |
| 82 | + else | |
| 83 | + field.set(entity, value); | |
| 84 | + } catch (Exception e) { | |
| 85 | + throw new IllegalStateException("Unable to write property '" + propertyName + "' in " + entity.getClass().getName(), e); | |
| 86 | + } | |
| 87 | + } | |
| 88 | + | |
| 89 | + boolean hasAnnotation(Class<? extends Annotation> annotationClass) { | |
| 90 | + return annotations.containsKey(annotationClass); | |
| 91 | + } | |
| 92 | + | |
| 93 | + Collection<Annotation> getAnnotations() { | |
| 94 | + return annotations.values(); | |
| 95 | + } | |
| 96 | + | |
| 97 | + @SuppressWarnings("unchecked") | |
| 98 | + <A extends Annotation> A annotation(Class<A> annotationClass) { | |
| 99 | + return (A) annotations.get(annotationClass); | |
| 100 | + } | |
| 101 | + | |
| 102 | + boolean isComputed() { | |
| 103 | + return hasAnnotation(Computed.class); | |
| 104 | + } | |
| 105 | + | |
| 106 | + boolean isTransient() { | |
| 107 | + return hasAnnotation(Transient.class); | |
| 108 | + } | |
| 109 | + | |
| 110 | + boolean isPartitionKey() { | |
| 111 | + return hasAnnotation(PartitionKey.class); | |
| 112 | + } | |
| 113 | + | |
| 114 | + boolean isClusteringColumn() { | |
| 115 | + return hasAnnotation(ClusteringColumn.class); | |
| 116 | + } | |
| 117 | + | |
| 118 | + int getPosition() { | |
| 119 | + return position; | |
| 120 | + } | |
| 121 | + | |
| 122 | + private String inferColumnName() { | |
| 123 | + Column column = annotation(Column.class); | |
| 124 | + if (column != null && !column.name().isEmpty()) { | |
| 125 | + return Metadata.quote(column.caseSensitive() ? column.name() : column.name().toLowerCase()); | |
| 126 | + } | |
| 127 | + com.datastax.driver.mapping.annotations.Field udtField = annotation(com.datastax.driver.mapping.annotations.Field.class); | |
| 128 | + if (udtField != null && !udtField.name().isEmpty()) { | |
| 129 | + return Metadata.quote(udtField.caseSensitive() ? udtField.name() : udtField.name().toLowerCase()); | |
| 130 | + } | |
| 131 | + if (isComputed()) { | |
| 132 | + return annotation(Computed.class).value(); | |
| 133 | + } | |
| 134 | + return Metadata.quote(propertyName.toLowerCase()); | |
| 135 | + } | |
| 136 | + | |
| 137 | + @SuppressWarnings("unchecked") | |
| 138 | + private TypeToken<Object> inferJavaType(PropertyDescriptor property) { | |
| 139 | + Type type; | |
| 140 | + if (getter != null) | |
| 141 | + type = getter.getGenericReturnType(); | |
| 142 | + else if (field != null) | |
| 143 | + type = field.getGenericType(); | |
| 144 | + else | |
| 145 | + // this will not work for generic types | |
| 146 | + type = property.getPropertyType(); | |
| 147 | + return (TypeToken<Object>) TypeToken.of(type); | |
| 148 | + } | |
| 149 | + | |
| 150 | + private int inferPosition() { | |
| 151 | + if (isPartitionKey()) { | |
| 152 | + return annotation(PartitionKey.class).value(); | |
| 153 | + } | |
| 154 | + if (isClusteringColumn()) { | |
| 155 | + return annotation(ClusteringColumn.class).value(); | |
| 156 | + } | |
| 157 | + return -1; | |
| 158 | + } | |
| 159 | + | |
| 160 | + private TypeCodec<Object> createCustomCodec() { | |
| 161 | + Class<? extends TypeCodec<?>> codecClass = getCustomCodecClass(); | |
| 162 | + if (codecClass.equals(Defaults.NoCodec.class)) | |
| 163 | + return null; | |
| 164 | + @SuppressWarnings("unchecked") | |
| 165 | + TypeCodec<Object> instance = (TypeCodec<Object>) ReflectionUtils.newInstance(codecClass); | |
| 166 | + return instance; | |
| 167 | + } | |
| 168 | + | |
| 169 | + private Class<? extends TypeCodec<?>> getCustomCodecClass() { | |
| 170 | + Column column = annotation(Column.class); | |
| 171 | + if (column != null) | |
| 172 | + return column.codec(); | |
| 173 | + com.datastax.driver.mapping.annotations.Field udtField = annotation(com.datastax.driver.mapping.annotations.Field.class); | |
| 174 | + if (udtField != null) | |
| 175 | + return udtField.codec(); | |
| 176 | + return Defaults.NoCodec.class; | |
| 177 | + } | |
| 178 | + | |
| 179 | + @Override | |
| 180 | + public String toString() { | |
| 181 | + return propertyName; | |
| 182 | + } | |
| 183 | + | |
| 184 | +} |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/QueryType.java +22 −22
| @@ -40,9 +40,9 @@ | ||
| 40 | 40 | private final int endBoundSize; |
| 41 | 41 | private final boolean endInclusive; |
| 42 | 42 | |
| 43 | - public static final QueryType SAVE = new QueryType(Kind.SAVE); | |
| 44 | - public static final QueryType DEL = new QueryType(Kind.DEL); | |
| 45 | - public static final QueryType GET = new QueryType(Kind.GET); | |
| 43 | + static final QueryType SAVE = new QueryType(Kind.SAVE); | |
| 44 | + static final QueryType DEL = new QueryType(Kind.DEL); | |
| 45 | + static final QueryType GET = new QueryType(Kind.GET); | |
| 46 | 46 | |
| 47 | 47 | private QueryType(Kind kind) { |
| 48 | 48 | this(kind, 0, false, 0, false); |
| @@ -56,15 +56,15 @@ | ||
| 56 | 56 | this.endInclusive = endInclusive; |
| 57 | 57 | } |
| 58 | 58 | |
| 59 | - String makePreparedQueryString(TableMetadata table, EntityMapper<?> mapper, MappingManager manager, Set<ColumnMapper<?>> columns, Collection<Mapper.Option> options) { | |
| 59 | + String makePreparedQueryString(TableMetadata table, EntityMapper<?> mapper, MappingManager manager, Set<PropertyMapper> columns, Collection<Mapper.Option> options) { | |
| 60 | 60 | switch (kind) { |
| 61 | 61 | case SAVE: { |
| 62 | 62 | Insert insert = table == null |
| 63 | 63 | ? insertInto(mapper.getKeyspace(), mapper.getTable()) |
| 64 | 64 | : insertInto(table); |
| 65 | - for (ColumnMapper<?> cm : columns) | |
| 66 | - if (!cm.property.isComputed()) | |
| 67 | - insert.value(cm.getColumnName(), bindMarker()); | |
| 65 | + for (PropertyMapper col : columns) | |
| 66 | + if (!col.isComputed()) | |
| 67 | + insert.value(col.columnName, bindMarker()); | |
| 68 | 68 | |
| 69 | 69 | Insert.Options usings = insert.using(); |
| 70 | 70 | for (Mapper.Option opt : options) { |
| @@ -76,15 +76,15 @@ | ||
| 76 | 76 | } |
| 77 | 77 | case GET: { |
| 78 | 78 | Select.Selection selection = select(); |
| 79 | - for (ColumnMapper cm : mapper.allColumns()) { | |
| 80 | - Select.SelectionOrAlias column = cm.property.isComputed() | |
| 81 | - ? selection.raw(cm.getColumnName()) | |
| 82 | - : selection.column(cm.getColumnName()); | |
| 83 | - | |
| 84 | - if (cm.getAlias() == null) { | |
| 79 | + for (PropertyMapper col : mapper.allColumns) { | |
| 80 | + Select.SelectionOrAlias column = col.isComputed() | |
| 81 | + ? selection.raw(col.columnName) | |
| 82 | + : selection.column(col.columnName); | |
| 83 | + | |
| 84 | + if (col.alias == null) { | |
| 85 | 85 | selection = column; |
| 86 | 86 | } else { |
| 87 | - selection = column.as(cm.getAlias()); | |
| 87 | + selection = column.as(col.alias); | |
| 88 | 88 | } |
| 89 | 89 | } |
| 90 | 90 | Select select; |
| @@ -95,7 +95,7 @@ | ||
| 95 | 95 | } |
| 96 | 96 | Select.Where where = select.where(); |
| 97 | 97 | for (int i = 0; i < mapper.primaryKeySize(); i++) |
| 98 | - where.and(eq(mapper.getPrimaryKeyColumn(i).getColumnName(), bindMarker())); | |
| 98 | + where.and(eq(mapper.getPrimaryKeyColumn(i).columnName, bindMarker())); | |
| 99 | 99 | |
| 100 | 100 | for (Mapper.Option opt : options) |
| 101 | 101 | opt.checkValidFor(QueryType.GET, manager); |
| @@ -107,7 +107,7 @@ | ||
| 107 | 107 | : delete().all().from(table); |
| 108 | 108 | Delete.Where where = delete.where(); |
| 109 | 109 | for (int i = 0; i < mapper.primaryKeySize(); i++) |
| 110 | - where.and(eq(mapper.getPrimaryKeyColumn(i).getColumnName(), bindMarker())); | |
| 110 | + where.and(eq(mapper.getPrimaryKeyColumn(i).columnName, bindMarker())); | |
| 111 | 111 | Delete.Options usings = delete.using(); |
| 112 | 112 | for (Mapper.Option opt : options) { |
| 113 | 113 | opt.checkValidFor(QueryType.DEL, manager); |
| @@ -123,17 +123,17 @@ | ||
| 123 | 123 | : select().all().from(table); |
| 124 | 124 | Select.Where where = select.where(); |
| 125 | 125 | for (int i = 0; i < mapper.partitionKeys.size(); i++) |
| 126 | - where.and(eq(mapper.partitionKeys.get(i).getColumnName(), bindMarker())); | |
| 126 | + where.and(eq(mapper.partitionKeys.get(i).columnName, bindMarker())); | |
| 127 | 127 | |
| 128 | 128 | if (startBoundSize > 0) { |
| 129 | 129 | if (startBoundSize == 1) { |
| 130 | - String name = mapper.clusteringColumns.get(0).getColumnName(); | |
| 130 | + String name = mapper.clusteringColumns.get(0).columnName; | |
| 131 | 131 | where.and(startInclusive ? gte(name, bindMarker()) : gt(name, bindMarker())); |
| 132 | 132 | } else { |
| 133 | 133 | List<String> names = new ArrayList<String>(startBoundSize); |
| 134 | 134 | List<Object> values = new ArrayList<Object>(startBoundSize); |
| 135 | 135 | for (int i = 0; i < startBoundSize; i++) { |
| 136 | - names.add(mapper.clusteringColumns.get(i).getColumnName()); | |
| 136 | + names.add(mapper.clusteringColumns.get(i).columnName); | |
| 137 | 137 | values.add(bindMarker()); |
| 138 | 138 | } |
| 139 | 139 | where.and(startInclusive ? gte(names, values) : gt(names, values)); |
| @@ -142,13 +142,13 @@ | ||
| 142 | 142 | |
| 143 | 143 | if (endBoundSize > 0) { |
| 144 | 144 | if (endBoundSize == 1) { |
| 145 | - String name = mapper.clusteringColumns.get(0).getColumnName(); | |
| 145 | + String name = mapper.clusteringColumns.get(0).columnName; | |
| 146 | 146 | where.and(endInclusive ? gte(name, bindMarker()) : gt(name, bindMarker())); |
| 147 | 147 | } else { |
| 148 | 148 | List<String> names = new ArrayList<String>(endBoundSize); |
| 149 | 149 | List<Object> values = new ArrayList<Object>(endBoundSize); |
| 150 | 150 | for (int i = 0; i < endBoundSize; i++) { |
| 151 | - names.add(mapper.clusteringColumns.get(i).getColumnName()); | |
| 151 | + names.add(mapper.clusteringColumns.get(i).columnName); | |
| 152 | 152 | values.add(bindMarker()); |
| 153 | 153 | } |
| 154 | 154 | where.and(endInclusive ? lte(names, values) : lt(names, values)); |
| @@ -158,7 +158,7 @@ | ||
| 158 | 158 | select = select.limit(bindMarker()); |
| 159 | 159 | |
| 160 | 160 | if (kind == Kind.REVERSED_SLICE) |
| 161 | - select = select.orderBy(desc(mapper.clusteringColumns.get(0).getColumnName())); | |
| 161 | + select = select.orderBy(desc(mapper.clusteringColumns.get(0).columnName)); | |
| 162 | 162 | |
| 163 | 163 | return select.toString(); |
| 164 | 164 | } |
deleted driver-mapping/src/main/java/com/datastax/driver/mapping/ReflectionMapper.java +0 −90
| @@ -1,90 +0,0 @@ | ||
| 1 | -/* | |
| 2 | - * Copyright (C) 2012-2015 DataStax Inc. | |
| 3 | - * | |
| 4 | - * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | - * you may not use this file except in compliance with the License. | |
| 6 | - * You may obtain a copy of the License at | |
| 7 | - * | |
| 8 | - * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | - * | |
| 10 | - * Unless required by applicable law or agreed to in writing, software | |
| 11 | - * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | - * See the License for the specific language governing permissions and | |
| 14 | - * limitations under the License. | |
| 15 | - */ | |
| 16 | -package com.datastax.driver.mapping; | |
| 17 | - | |
| 18 | -import com.datastax.driver.core.ConsistencyLevel; | |
| 19 | - | |
| 20 | -import java.util.concurrent.atomic.AtomicInteger; | |
| 21 | - | |
| 22 | -/** | |
| 23 | - * An {@link EntityMapper} implementation that use reflection to read and write fields | |
| 24 | - * of an entity. | |
| 25 | - */ | |
| 26 | -class ReflectionMapper<T> extends EntityMapper<T> { | |
| 27 | - | |
| 28 | - private static final ReflectionFactory factory = new ReflectionFactory(); | |
| 29 | - | |
| 30 | - private ReflectionMapper(Class<T> entityClass, String keyspace, String table, ConsistencyLevel writeConsistency, ConsistencyLevel readConsistency) { | |
| 31 | - super(entityClass, keyspace, table, writeConsistency, readConsistency); | |
| 32 | - } | |
| 33 | - | |
| 34 | - public static Factory factory() { | |
| 35 | - return factory; | |
| 36 | - } | |
| 37 | - | |
| 38 | - @Override | |
| 39 | - public T newEntity() { | |
| 40 | - try { | |
| 41 | - return entityClass.newInstance(); | |
| 42 | - } catch (Exception e) { | |
| 43 | - throw new RuntimeException("Can't create an instance of " + entityClass.getName()); | |
| 44 | - } | |
| 45 | - } | |
| 46 | - | |
| 47 | - private static class LiteralMapper<T> extends ColumnMapper<T> { | |
| 48 | - | |
| 49 | - private LiteralMapper(MappedProperty<T> property, int position, AtomicInteger columnCounter) { | |
| 50 | - super(property, position, columnCounter); | |
| 51 | - } | |
| 52 | - | |
| 53 | - @Override | |
| 54 | - Object getValue(T entity) { | |
| 55 | - try { | |
| 56 | - return property.getter().invoke(entity); | |
| 57 | - } catch (IllegalArgumentException e) { | |
| 58 | - throw new IllegalArgumentException("Could not get field '" + property.name() + "'"); | |
| 59 | - } catch (Exception e) { | |
| 60 | - throw new IllegalStateException("Unable to access getter for '" + property.name() + "' in " + entity.getClass().getName(), e); | |
| 61 | - } | |
| 62 | - } | |
| 63 | - | |
| 64 | - @Override | |
| 65 | - void setValue(Object entity, Object value) { | |
| 66 | - try { | |
| 67 | - property.setter().invoke(entity, value); | |
| 68 | - } catch (IllegalArgumentException e) { | |
| 69 | - throw new IllegalArgumentException("Could not set field '" + property.name() + "' to value '" + value + "'"); | |
| 70 | - } catch (Exception e) { | |
| 71 | - throw new IllegalStateException("Unable to access setter for '" + property.name() + "' in " + entity.getClass().getName(), e); | |
| 72 | - } | |
| 73 | - } | |
| 74 | - } | |
| 75 | - | |
| 76 | - private static class ReflectionFactory implements Factory { | |
| 77 | - | |
| 78 | - @Override | |
| 79 | - public <T> EntityMapper<T> create(Class<T> entityClass, String keyspace, String table, ConsistencyLevel writeConsistency, ConsistencyLevel readConsistency) { | |
| 80 | - return new ReflectionMapper<T>(entityClass, keyspace, table, writeConsistency, readConsistency); | |
| 81 | - } | |
| 82 | - | |
| 83 | - @Override | |
| 84 | - public <T> ColumnMapper<T> createColumnMapper(MappedProperty<T> property, int position, MappingManager mappingManager, AtomicInteger columnCounter) { | |
| 85 | - for (Class<?> udt : TypeMappings.findUDTs(property.type().getType())) | |
| 86 | - mappingManager.getUDTCodec(udt); | |
| 87 | - return new LiteralMapper<T>(property, position, columnCounter); | |
| 88 | - } | |
| 89 | - } | |
| 90 | -} |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/ReflectionUtils.java +102 −25
| @@ -22,6 +22,7 @@ | ||
| 22 | 22 | import java.beans.Introspector; |
| 23 | 23 | import java.beans.PropertyDescriptor; |
| 24 | 24 | import java.lang.annotation.Annotation; |
| 25 | +import java.lang.reflect.Constructor; | |
| 25 | 26 | import java.lang.reflect.Field; |
| 26 | 27 | import java.lang.reflect.Method; |
| 27 | 28 | import java.lang.reflect.Modifier; |
| @@ -33,36 +34,125 @@ | ||
| 33 | 34 | */ |
| 34 | 35 | class ReflectionUtils { |
| 35 | 36 | |
| 36 | - static <T> BeanInfo getBeanInfo(Class<T> udtClass) { | |
| 37 | + static <T> T newInstance(Class<T> clazz) { | |
| 38 | + try { | |
| 39 | + return clazz.newInstance(); | |
| 40 | + } catch (Exception e) { | |
| 41 | + try { | |
| 42 | + // try private constructor | |
| 43 | + Constructor<T> constructor = clazz.getDeclaredConstructor(); | |
| 44 | + constructor.setAccessible(true); | |
| 45 | + return constructor.newInstance(); | |
| 46 | + } catch (Exception e1) { | |
| 47 | + throw new IllegalArgumentException("Can't create an instance of " + clazz.getName()); | |
| 48 | + } | |
| 49 | + } | |
| 50 | + } | |
| 51 | + | |
| 52 | + static <T> Map<String, Object[]> scanFieldsAndProperties(Class<T> baseClass) { | |
| 53 | + Map<String, Object[]> fieldsAndProperties = new HashMap<String, Object[]>(); | |
| 54 | + Map<String, Field> fields = scanFields(baseClass); | |
| 55 | + for (Map.Entry<String, Field> entry : fields.entrySet()) { | |
| 56 | + fieldsAndProperties.put(entry.getKey(), new Object[]{entry.getValue(), null}); | |
| 57 | + } | |
| 58 | + Map<String, PropertyDescriptor> properties = scanProperties(baseClass); | |
| 59 | + for (Map.Entry<String, PropertyDescriptor> entry : properties.entrySet()) { | |
| 60 | + Object[] value = fieldsAndProperties.get(entry.getKey()); | |
| 61 | + if (value == null) | |
| 62 | + fieldsAndProperties.put(entry.getKey(), new Object[]{null, entry.getValue()}); | |
| 63 | + else value[1] = entry.getValue(); | |
| 64 | + } | |
| 65 | + return fieldsAndProperties; | |
| 66 | + } | |
| 67 | + | |
| 68 | + private static <T> Map<String, Field> scanFields(Class<T> baseClass) { | |
| 69 | + HashMap<String, Field> fields = new HashMap<String, Field>(); | |
| 70 | + for (Class<?> clazz = baseClass; !clazz.equals(Object.class); clazz = clazz.getSuperclass()) { | |
| 71 | + for (Field field : clazz.getDeclaredFields()) { | |
| 72 | + if (field.getName().equals("class") || field.isSynthetic() || (field.getModifiers() & Modifier.STATIC) == Modifier.STATIC) | |
| 73 | + continue; | |
| 74 | + field.setAccessible(true); | |
| 75 | + // never override a more specific field masking another one declared in a superclass | |
| 76 | + if (!fields.containsKey(field.getName())) | |
| 77 | + fields.put(field.getName(), field); | |
| 78 | + } | |
| 79 | + } | |
| 80 | + return fields; | |
| 81 | + } | |
| 82 | + | |
| 83 | + private static <T> Map<String, PropertyDescriptor> scanProperties(Class<T> baseClass) { | |
| 37 | 84 | BeanInfo beanInfo; |
| 38 | 85 | try { |
| 39 | - beanInfo = Introspector.getBeanInfo(udtClass); | |
| 86 | + beanInfo = Introspector.getBeanInfo(baseClass); | |
| 40 | 87 | } catch (IntrospectionException e) { |
| 41 | 88 | throw Throwables.propagate(e); |
| 42 | 89 | } |
| 43 | - return beanInfo; | |
| 90 | + Map<String, PropertyDescriptor> properties = new HashMap<String, PropertyDescriptor>(); | |
| 91 | + for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) { | |
| 92 | + if (property.getName().equals("class")) | |
| 93 | + continue; | |
| 94 | + properties.put(property.getName(), property); | |
| 95 | + } | |
| 96 | + return properties; | |
| 44 | 97 | } |
| 45 | 98 | |
| 46 | - static Map<Class<? extends Annotation>, Annotation> findAnnotations(PropertyDescriptor property, Class<?> baseClass) { | |
| 47 | - // try field | |
| 99 | + static Map<Class<? extends Annotation>, Annotation> scanPropertyAnnotations(Field field, PropertyDescriptor property) { | |
| 48 | 100 | Map<Class<? extends Annotation>, Annotation> annotations = new HashMap<Class<? extends Annotation>, Annotation>(); |
| 49 | - Field field = findField(property.getName(), baseClass); | |
| 101 | + // annotations on getters should have precedence over annotations on fields | |
| 102 | + scanFieldAnnotations(field, annotations); | |
| 103 | + if (property != null) { | |
| 104 | + Method getter = property.getReadMethod(); | |
| 105 | + scanMethodAnnotations(getter, annotations); | |
| 106 | + } | |
| 107 | + return annotations; | |
| 108 | + } | |
| 109 | + | |
| 110 | + private static Map<Class<? extends Annotation>, Annotation> scanFieldAnnotations(Field field, Map<Class<? extends Annotation>, Annotation> annotations) { | |
| 50 | 111 | if (field != null) { |
| 51 | 112 | for (Annotation annotation : field.getAnnotations()) { |
| 52 | 113 | annotations.put(annotation.annotationType(), annotation); |
| 53 | 114 | } |
| 54 | 115 | } |
| 55 | - // try getter | |
| 56 | - Method getter = findGetter(property); | |
| 57 | - if (getter != null) { | |
| 58 | - for (Annotation annotation : getter.getAnnotations()) { | |
| 116 | + return annotations; | |
| 117 | + } | |
| 118 | + | |
| 119 | + private static Map<Class<? extends Annotation>, Annotation> scanMethodAnnotations(Method method, Map<Class<? extends Annotation>, Annotation> annotations) { | |
| 120 | + if (method != null) { | |
| 121 | + // 1. direct method annotations | |
| 122 | + for (Annotation annotation : method.getAnnotations()) { | |
| 59 | 123 | annotations.put(annotation.annotationType(), annotation); |
| 60 | 124 | } |
| 125 | + // 2. Class hierarchy: check for annotations in overridden methods in superclasses | |
| 126 | + Class<?> getterClass = method.getDeclaringClass(); | |
| 127 | + for (Class<?> clazz = getterClass.getSuperclass(); !clazz.equals(Object.class); clazz = clazz.getSuperclass()) { | |
| 128 | + maybeAddOverriddenMethodAnnotations(annotations, method, clazz); | |
| 129 | + } | |
| 130 | + // 3. Interfaces: check for annotations in implemented interfaces | |
| 131 | + for (Class<?> clazz = getterClass; !clazz.equals(Object.class); clazz = clazz.getSuperclass()) { | |
| 132 | + for (Class<?> itf : clazz.getInterfaces()) { | |
| 133 | + maybeAddOverriddenMethodAnnotations(annotations, method, itf); | |
| 134 | + } | |
| 135 | + } | |
| 61 | 136 | } |
| 62 | 137 | return annotations; |
| 63 | 138 | } |
| 64 | 139 | |
| 140 | + private static void maybeAddOverriddenMethodAnnotations(Map<Class<? extends Annotation>, Annotation> annotations, Method getter, Class<?> clazz) { | |
| 141 | + try { | |
| 142 | + Method overriddenGetter = clazz.getDeclaredMethod(getter.getName(), getter.getParameterTypes()); | |
| 143 | + for (Annotation annotation : overriddenGetter.getAnnotations()) { | |
| 144 | + // do not override a more specific version of the annotation type being scanned | |
| 145 | + if (!annotations.containsKey(annotation.annotationType())) | |
| 146 | + annotations.put(annotation.annotationType(), annotation); | |
| 147 | + } | |
| 148 | + } catch (NoSuchMethodException e) { | |
| 149 | + //ok | |
| 150 | + } | |
| 151 | + } | |
| 152 | + | |
| 65 | 153 | static Method findGetter(PropertyDescriptor property) { |
| 154 | + if (property == null) | |
| 155 | + return null; | |
| 66 | 156 | Method getter = property.getReadMethod(); |
| 67 | 157 | if (getter == null) |
| 68 | 158 | return null; |
| @@ -71,6 +161,8 @@ | ||
| 71 | 161 | } |
| 72 | 162 | |
| 73 | 163 | static Method findSetter(PropertyDescriptor property) { |
| 164 | + if (property == null) | |
| 165 | + return null; | |
| 74 | 166 | Method setter = property.getWriteMethod(); |
| 75 | 167 | if (setter == null) |
| 76 | 168 | return null; |
| @@ -78,19 +170,4 @@ | ||
| 78 | 170 | return setter; |
| 79 | 171 | } |
| 80 | 172 | |
| 81 | - static Field findField(String name, Class<?> baseClass) { | |
| 82 | - for (Class<?> clazz = baseClass; !clazz.equals(Object.class); clazz = clazz.getSuperclass()) { | |
| 83 | - try { | |
| 84 | - Field field = clazz.getDeclaredField(name); | |
| 85 | - if (field.isSynthetic() || (field.getModifiers() & Modifier.STATIC) == Modifier.STATIC) | |
| 86 | - continue; | |
| 87 | - field.setAccessible(true); | |
| 88 | - return field; | |
| 89 | - } catch (NoSuchFieldException e) { | |
| 90 | - //ok | |
| 91 | - } | |
| 92 | - } | |
| 93 | - return null; | |
| 94 | - } | |
| 95 | - | |
| 96 | 173 | } |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/Result.java +5 −5
| @@ -43,20 +43,20 @@ | ||
| 43 | 43 | |
| 44 | 44 | private T map(Row row) { |
| 45 | 45 | T entity = mapper.newEntity(); |
| 46 | - for (ColumnMapper<T> cm : mapper.allColumns()) { | |
| 47 | - String name = cm.getAlias() != null && this.useAlias ? cm.getAlias() : cm.getColumnName(); | |
| 46 | + for (PropertyMapper col : mapper.allColumns) { | |
| 47 | + String name = col.alias != null && this.useAlias ? col.alias : col.columnName; | |
| 48 | 48 | if (!row.getColumnDefinitions().contains(name)) |
| 49 | 49 | continue; |
| 50 | 50 | |
| 51 | 51 | Object value; |
| 52 | - TypeCodec<Object> customCodec = cm.getCustomCodec(); | |
| 52 | + TypeCodec<Object> customCodec = col.customCodec; | |
| 53 | 53 | if (customCodec != null) |
| 54 | 54 | value = row.get(name, customCodec); |
| 55 | 55 | else |
| 56 | - value = row.get(name, cm.getJavaType()); | |
| 56 | + value = row.get(name, col.javaType); | |
| 57 | 57 | |
| 58 | 58 | if (shouldSetValue(value)) { |
| 59 | - cm.setValue(entity, value); | |
| 59 | + col.setValue(entity, value); | |
| 60 | 60 | } |
| 61 | 61 | } |
| 62 | 62 | return entity; |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/TypeMappings.java +1 −1
| @@ -30,7 +30,7 @@ | ||
| 30 | 30 | */ |
| 31 | 31 | class TypeMappings { |
| 32 | 32 | |
| 33 | - static boolean mapsToCollection(Class<?> klass) { | |
| 33 | + private static boolean mapsToCollection(Class<?> klass) { | |
| 34 | 34 | return mapsToList(klass) || mapsToSet(klass) || mapsToMap(klass); |
| 35 | 35 | } |
| 36 | 36 |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/ClusteringColumn.java +2 −2
| @@ -21,12 +21,12 @@ | ||
| 21 | 21 | import java.lang.annotation.Target; |
| 22 | 22 | |
| 23 | 23 | /** |
| 24 | - * Annotation for fields that map to a CQL clustering column. | |
| 24 | + * Annotation for properties that map to a CQL clustering column. | |
| 25 | 25 | * <p/> |
| 26 | 26 | * If the mapped table has multiple clustering columns, it is mandatory |
| 27 | 27 | * to specify the ordinal parameter to avoid ordering ambiguity. |
| 28 | 28 | */ |
| 29 | -@Target(ElementType.FIELD) | |
| 29 | +@Target({ElementType.FIELD, ElementType.METHOD}) | |
| 30 | 30 | @Retention(RetentionPolicy.RUNTIME) |
| 31 | 31 | public @interface ClusteringColumn { |
| 32 | 32 | /** |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Column.java +7 −7
| @@ -24,21 +24,21 @@ | ||
| 24 | 24 | |
| 25 | 25 | /** |
| 26 | 26 | * Annotation that allows to specify the name of the CQL column to which the |
| 27 | - * field should be mapped. | |
| 27 | + * property should be mapped. | |
| 28 | 28 | * <p/> |
| 29 | 29 | * Note that this annotation is generally optional in the sense that any field |
| 30 | - * of a class annotated by {@link Table} will be mapped by default to a column | |
| 31 | - * having the same name than this field unless that field has the | |
| 30 | + * or any getter method of a Java bean property of a class annotated by {@link Table} | |
| 31 | + * will be mapped by default to a column | |
| 32 | + * having the same name than this field / property, unless that field or method has the | |
| 32 | 33 | * {@link Transient} annotation. As such, this annotation is mainly useful when |
| 33 | - * the name to map the field to is not the same one that the field itself (but | |
| 34 | - * can be added without it's name parameter for documentation sake). | |
| 34 | + * the CQL column name does not correspond to the field or property name itself. | |
| 35 | 35 | */ |
| 36 | -@Target(ElementType.FIELD) | |
| 36 | +@Target({ElementType.FIELD, ElementType.METHOD}) | |
| 37 | 37 | @Retention(RetentionPolicy.RUNTIME) |
| 38 | 38 | public @interface Column { |
| 39 | 39 | /** |
| 40 | 40 | * Name of the column being mapped in Cassandra. By default, the name of the |
| 41 | - * field will be used. | |
| 41 | + * field or Java bean property will be used. | |
| 42 | 42 | * |
| 43 | 43 | * @return the name of the mapped column in Cassandra, or {@code ""} to use |
| 44 | 44 | * the field name. |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Computed.java +6 −6
| @@ -24,26 +24,26 @@ | ||
| 24 | 24 | import java.lang.annotation.Target; |
| 25 | 25 | |
| 26 | 26 | /** |
| 27 | - * Annotates a "computed" field, which gets filled from a CQL expression in the SELECT query | |
| 27 | + * Annotates a "computed" property, which gets filled from a CQL expression in the SELECT query | |
| 28 | 28 | * used to retrieve an entity. |
| 29 | 29 | * <p/> |
| 30 | - * Note that such fields are only filled by default mapper operations ({@link Mapper#get(Object...)}), | |
| 30 | + * Note that such properties are only filled by default mapper operations ({@link Mapper#get(Object...)}), | |
| 31 | 31 | * they will be ignored in accessor queries and save operations. |
| 32 | 32 | * <p/> |
| 33 | - * As opposed to other mapper annotation, this one doesn't handle case sensitivity. If your expression | |
| 33 | + * As opposed to other mapper annotations, this one doesn't handle case sensitivity. If your expression | |
| 34 | 34 | * contains case-sensitive names, you'll need to quote them explicitly: |
| 35 | 35 | * <pre> |
| 36 | 36 | * {@code @Computed("\"caseSensitiveFunction\"(v)")} |
| 37 | 37 | * </pre> |
| 38 | 38 | */ |
| 39 | -@Target(ElementType.FIELD) | |
| 39 | +@Target({ElementType.FIELD, ElementType.METHOD}) | |
| 40 | 40 | @Retention(RetentionPolicy.RUNTIME) |
| 41 | 41 | public @interface Computed { |
| 42 | 42 | /** |
| 43 | - * The formula used to compute the field. | |
| 43 | + * The formula used to compute the property. | |
| 44 | 44 | * <p/> |
| 45 | 45 | * This is a CQL expression like you would use directly in a query, for instance |
| 46 | - * "writetime(v)". | |
| 46 | + * {@code "writetime(v)"}. | |
| 47 | 47 | * |
| 48 | 48 | * @return the formula. |
| 49 | 49 | */ |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Field.java +7 −7
| @@ -24,21 +24,21 @@ | ||
| 24 | 24 | |
| 25 | 25 | /** |
| 26 | 26 | * Annotation that allows to specify the name of the CQL UDT field to which the |
| 27 | - * Java field should be mapped. | |
| 27 | + * Java field or bean property should be mapped. | |
| 28 | 28 | * <p/> |
| 29 | 29 | * Note that this annotation is generally optional in the sense that any field |
| 30 | - * of a class annotated by {@link UDT} will be mapped by default to a UDT field | |
| 31 | - * having the same name than this Java field unless that Java field has the | |
| 30 | + * or any getter method of a Java bean property of a class annotated by {@link UDT} | |
| 31 | + * will be mapped by default to a UDT field | |
| 32 | + * having the same name than this Java field / bean property unless that Java field or method has the | |
| 32 | 33 | * {@link Transient} annotation. As such, this annotation is mainly useful when |
| 33 | - * the name to map the field to is not the same one that the field itself (but | |
| 34 | - * can be added without it's name parameter for documentation sake). | |
| 34 | + * the UDT field name does not correspond to the Java field or property name itself. | |
| 35 | 35 | */ |
| 36 | -@Target(ElementType.FIELD) | |
| 36 | +@Target({ElementType.FIELD, ElementType.METHOD}) | |
| 37 | 37 | @Retention(RetentionPolicy.RUNTIME) |
| 38 | 38 | public @interface Field { |
| 39 | 39 | /** |
| 40 | 40 | * Name of the column being mapped in Cassandra. By default, the name of the |
| 41 | - * field will be used. | |
| 41 | + * Java field or bean property will be used. | |
| 42 | 42 | * |
| 43 | 43 | * @return the name of the mapped column in Cassandra, or {@code ""} to use |
| 44 | 44 | * the field name. |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Frozen.java +2 −2
| @@ -23,7 +23,7 @@ | ||
| 23 | 23 | import java.lang.annotation.Target; |
| 24 | 24 | |
| 25 | 25 | /** |
| 26 | - * Specifies that the field decorated with this annotation maps to a CQL type that is {@link DataType#isFrozen() frozen}, | |
| 26 | + * Specifies that the property decorated with this annotation maps to a CQL type that is {@link DataType#isFrozen() frozen}, | |
| 27 | 27 | * or contains frozen subtypes. |
| 28 | 28 | * <p/> |
| 29 | 29 | * This annotation is purely informational at this stage, the validity of the declaration is not checked. |
| @@ -33,7 +33,7 @@ | ||
| 33 | 33 | * @see FrozenKey |
| 34 | 34 | * @see FrozenValue |
| 35 | 35 | */ |
| 36 | -@Target(ElementType.FIELD) | |
| 36 | +@Target({ElementType.FIELD, ElementType.METHOD}) | |
| 37 | 37 | @Retention(RetentionPolicy.RUNTIME) |
| 38 | 38 | public @interface Frozen { |
| 39 | 39 |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/FrozenKey.java +2 −2
| @@ -21,13 +21,13 @@ | ||
| 21 | 21 | import java.lang.annotation.Target; |
| 22 | 22 | |
| 23 | 23 | /** |
| 24 | - * Shorthand to specify that the key type of a MAP field is frozen. | |
| 24 | + * Shorthand to specify that the key type of a MAP property is frozen. | |
| 25 | 25 | * <p/> |
| 26 | 26 | * This is equivalent to {@code @Frozen("map<frozen<foo>, bar>")}. |
| 27 | 27 | * |
| 28 | 28 | * @see Frozen |
| 29 | 29 | */ |
| 30 | -@Target(ElementType.FIELD) | |
| 30 | +@Target({ElementType.FIELD, ElementType.METHOD}) | |
| 31 | 31 | @Retention(RetentionPolicy.RUNTIME) |
| 32 | 32 | public @interface FrozenKey { |
| 33 | 33 | } |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/FrozenValue.java +2 −2
| @@ -21,7 +21,7 @@ | ||
| 21 | 21 | import java.lang.annotation.Target; |
| 22 | 22 | |
| 23 | 23 | /** |
| 24 | - * Shorthand to specify that the value type of a collection field is frozen. | |
| 24 | + * Shorthand to specify that the value type of a collection property is frozen. | |
| 25 | 25 | * <p/> |
| 26 | 26 | * This is equivalent to any of the following: |
| 27 | 27 | * <ul> |
| @@ -32,7 +32,7 @@ | ||
| 32 | 32 | * |
| 33 | 33 | * @see Frozen |
| 34 | 34 | */ |
| 35 | -@Target(ElementType.FIELD) | |
| 35 | +@Target({ElementType.FIELD, ElementType.METHOD}) | |
| 36 | 36 | @Retention(RetentionPolicy.RUNTIME) |
| 37 | 37 | public @interface FrozenValue { |
| 38 | 38 | } |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/PartitionKey.java +2 −2
| @@ -21,13 +21,13 @@ | ||
| 21 | 21 | import java.lang.annotation.Target; |
| 22 | 22 | |
| 23 | 23 | /** |
| 24 | - * Annotation for fields that map to a CQL partition key (or one of it's | |
| 24 | + * Annotation for properties that map to a CQL partition key (or one of it's | |
| 25 | 25 | * component if the partition key is composite). |
| 26 | 26 | * <p/> |
| 27 | 27 | * If the partition key of the mapped table is composite, it is mandatory |
| 28 | 28 | * to specify the ordinal parameter to avoid ordering ambiguity. |
| 29 | 29 | */ |
| 30 | -@Target(ElementType.FIELD) | |
| 30 | +@Target({ElementType.FIELD, ElementType.METHOD}) | |
| 31 | 31 | @Retention(RetentionPolicy.RUNTIME) |
| 32 | 32 | public @interface PartitionKey { |
| 33 | 33 | /** |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Transient.java +4 −4
| @@ -21,14 +21,14 @@ | ||
| 21 | 21 | import java.lang.annotation.Target; |
| 22 | 22 | |
| 23 | 23 | /** |
| 24 | - * Whenever this annotation is added on a field, the field will not be mapped | |
| 24 | + * Whenever this annotation is added on a property, the property will not be mapped | |
| 25 | 25 | * to any column (neither during reads nor writes). |
| 26 | 26 | * <p/> |
| 27 | 27 | * Please note that it is thus illegal to have a field that has both the |
| 28 | - * {@code Transcient} annotation and one of the {@link Column}, {@link PartitionKey} | |
| 29 | - * or {@link ClusteringColumn} annotation. | |
| 28 | + * {@code Transient} annotation and one of the following annotations: | |
| 29 | + * {@link Column}, {@link PartitionKey}, {@link ClusteringColumn}. | |
| 30 | 30 | */ |
| 31 | -@Target(ElementType.FIELD) | |
| 31 | +@Target({ElementType.FIELD, ElementType.METHOD}) | |
| 32 | 32 | @Retention(RetentionPolicy.RUNTIME) |
| 33 | 33 | public @interface Transient { |
| 34 | 34 | } |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperPolymorphismTest.java +206 −53
| @@ -16,51 +16,72 @@ | ||
| 16 | 16 | package com.datastax.driver.mapping; |
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.CCMTestsSupport; |
| 19 | -import com.datastax.driver.mapping.annotations.Column; | |
| 20 | -import com.datastax.driver.mapping.annotations.PartitionKey; | |
| 21 | -import com.datastax.driver.mapping.annotations.Table; | |
| 22 | -import com.datastax.driver.mapping.annotations.UDT; | |
| 19 | +import com.datastax.driver.mapping.annotations.*; | |
| 23 | 20 | import com.google.common.base.Objects; |
| 24 | -import org.testng.annotations.BeforeMethod; | |
| 21 | +import com.google.common.collect.Sets; | |
| 22 | +import org.testng.annotations.AfterMethod; | |
| 23 | +import org.testng.annotations.BeforeClass; | |
| 25 | 24 | import org.testng.annotations.Test; |
| 26 | 25 | |
| 26 | +import java.util.Set; | |
| 27 | 27 | import java.util.UUID; |
| 28 | 28 | |
| 29 | 29 | import static org.assertj.core.api.Assertions.assertThat; |
| 30 | 30 | |
| 31 | -@SuppressWarnings("unused") | |
| 31 | +/** | |
| 32 | + * Tests for | |
| 33 | + * JAVA-541 Add polymorphism support to object mapper | |
| 34 | + * JAVA-636 Allow @Column annotations on getters/setters as well as fields | |
| 35 | + */ | |
| 36 | +@SuppressWarnings({"unused", "WeakerAccess"}) | |
| 32 | 37 | public class MapperPolymorphismTest extends CCMTestsSupport { |
| 33 | 38 | |
| 34 | - private final Circle circle = new Circle(new Point2D(11, 22), 12.34); | |
| 35 | - private final Rectangle rectangle = new Rectangle(new Point2D(20, 30), new Point2D(50, 60)); | |
| 36 | - private final Sphere sphere = new Sphere(new Point3D(11, 22, 33), 34.56); | |
| 37 | - private Mapper<Circle> circleMapper; | |
| 38 | - private Mapper<Rectangle> rectangleMapper; | |
| 39 | - private Mapper<Sphere> sphereMapper; | |
| 39 | + Circle circle = new Circle(new Point2D(11, 22), 12.34); | |
| 40 | + Rectangle rectangle = new Rectangle(new Point2D(20, 30), new Point2D(50, 60)); | |
| 41 | + Square square = new Square(new Point2D(20, 30), new Point2D(50, 60)); | |
| 42 | + Sphere sphere = new Sphere(new Point3D(11, 22, 33), 34.56); | |
| 43 | + | |
| 44 | + Mapper<Circle> circleMapper; | |
| 45 | + Mapper<Rectangle> rectangleMapper; | |
| 46 | + Mapper<Square> squareMapper; | |
| 47 | + Mapper<Sphere> sphereMapper; | |
| 40 | 48 | |
| 41 | 49 | @Override |
| 42 | 50 | public void onTestContextInitialized() { |
| 43 | 51 | execute( |
| 44 | - "CREATE TYPE point2d (x int, y int)", | |
| 45 | - "CREATE TYPE point3d (x int, y int, z int)", | |
| 46 | - "CREATE TABLE circles (id uuid PRIMARY KEY, center frozen<point2d>, radius double)", | |
| 47 | - "CREATE TABLE rectangles (id uuid PRIMARY KEY, bottom_left frozen<point2d>, top_right frozen<point2d>)", | |
| 48 | - "CREATE TABLE spheres (id uuid PRIMARY KEY, center frozen<point3d>, radius double)"); | |
| 52 | + "CREATE TYPE point2d (\"X\" int, \"Y\" int)", | |
| 53 | + "CREATE TYPE point3d (\"X\" int, \"Y\" int, \"Z\" int)", | |
| 54 | + "CREATE TABLE circles (circle_id uuid PRIMARY KEY, center2d frozen<point2d>, radius double, tags set<text>)", | |
| 55 | + "CREATE TABLE rectangles (rect_id uuid PRIMARY KEY, bottom_left frozen<point2d>, top_right frozen<point2d>, tags set<text>)", | |
| 56 | + "CREATE TABLE squares (square_id uuid PRIMARY KEY, bottom_left frozen<point2d>, top_right frozen<point2d>, tags set<text>)", | |
| 57 | + "CREATE TABLE spheres (sphere_id uuid PRIMARY KEY, center3d frozen<point3d>, radius double, tags set<text>)"); | |
| 58 | + } | |
| 59 | + | |
| 60 | + @BeforeClass(groups = "short") | |
| 61 | + public void createMappers() throws Exception { | |
| 62 | + MappingManager mappingManager = new MappingManager(session()); | |
| 63 | + circleMapper = mappingManager.mapper(Circle.class); | |
| 64 | + rectangleMapper = mappingManager.mapper(Rectangle.class); | |
| 65 | + squareMapper = mappingManager.mapper(Square.class); | |
| 66 | + sphereMapper = mappingManager.mapper(Sphere.class); | |
| 49 | 67 | } |
| 50 | 68 | |
| 51 | - @BeforeMethod(groups = "short") | |
| 69 | + @AfterMethod(groups = "short") | |
| 52 | 70 | public void clean() { |
| 53 | - execute("TRUNCATE circles", "TRUNCATE rectangles", "TRUNCATE spheres"); | |
| 71 | + execute("TRUNCATE circles", "TRUNCATE rectangles", "TRUNCATE squares", "TRUNCATE spheres"); | |
| 54 | 72 | } |
| 55 | 73 | |
| 56 | 74 | @UDT(name = "point2d") |
| 57 | 75 | static class Point2D { |
| 58 | 76 | |
| 77 | + // test mix of field and getter - getter should win | |
| 78 | + @Field(name = "wrong") | |
| 59 | 79 | private int x; |
| 60 | 80 | |
| 61 | 81 | private int y; |
| 62 | 82 | |
| 63 | - public Point2D() { | |
| 83 | + // test private constructor + "immutability" | |
| 84 | + private Point2D() { | |
| 64 | 85 | } |
| 65 | 86 | |
| 66 | 87 | public Point2D(int x, int y) { |
| @@ -68,22 +89,16 @@ | ||
| 68 | 89 | this.y = y; |
| 69 | 90 | } |
| 70 | 91 | |
| 92 | + @Field(name = "X", caseSensitive = true) | |
| 71 | 93 | public int getX() { |
| 72 | 94 | return x; |
| 73 | 95 | } |
| 74 | 96 | |
| 75 | - public void setX(int x) { | |
| 76 | - this.x = x; | |
| 77 | - } | |
| 78 | - | |
| 97 | + @Field(name = "Y", caseSensitive = true) | |
| 79 | 98 | public int getY() { |
| 80 | 99 | return y; |
| 81 | 100 | } |
| 82 | 101 | |
| 83 | - public void setY(int y) { | |
| 84 | - this.y = y; | |
| 85 | - } | |
| 86 | - | |
| 87 | 102 | @Override |
| 88 | 103 | public boolean equals(Object o) { |
| 89 | 104 | if (this == o) return true; |
| @@ -104,7 +119,8 @@ | ||
| 104 | 119 | |
| 105 | 120 | private int z; |
| 106 | 121 | |
| 107 | - public Point3D() { | |
| 122 | + // test private constructor + "immutability" | |
| 123 | + private Point3D() { | |
| 108 | 124 | } |
| 109 | 125 | |
| 110 | 126 | public Point3D(int x, int y, int z) { |
| @@ -112,14 +128,11 @@ | ||
| 112 | 128 | this.z = z; |
| 113 | 129 | } |
| 114 | 130 | |
| 131 | + @Field(name = "Z", caseSensitive = true) | |
| 115 | 132 | public int getZ() { |
| 116 | 133 | return z; |
| 117 | 134 | } |
| 118 | 135 | |
| 119 | - public void setZ(int z) { | |
| 120 | - this.z = z; | |
| 121 | - } | |
| 122 | - | |
| 123 | 136 | @Override |
| 124 | 137 | public boolean equals(Object o) { |
| 125 | 138 | if (this == o) return true; |
| @@ -135,23 +148,46 @@ | ||
| 135 | 148 | } |
| 136 | 149 | } |
| 137 | 150 | |
| 138 | - static class Shape { | |
| 151 | + interface Shape2D { | |
| 152 | + | |
| 153 | + Set<String> getTags(); | |
| 154 | + | |
| 155 | + // test annotation on interface method, should get inherited everywhere | |
| 156 | + @Transient | |
| 157 | + double getArea(); | |
| 158 | + | |
| 159 | + } | |
| 160 | + | |
| 161 | + interface Shape3D { | |
| 162 | + | |
| 163 | + double getVolume(); | |
| 164 | + | |
| 165 | + } | |
| 166 | + | |
| 167 | + static abstract class Shape implements Shape2D { | |
| 139 | 168 | |
| 140 | - @PartitionKey | |
| 141 | - private UUID id; | |
| 169 | + @PartitionKey // annotated field on superclass; annotation will get inherited in all subclasses | |
| 170 | + protected UUID id; | |
| 171 | + | |
| 172 | + protected Set<String> tags; | |
| 142 | 173 | |
| 143 | 174 | public Shape() { |
| 144 | 175 | this.id = UUID.randomUUID(); |
| 176 | + this.tags = Sets.newHashSet("cool", "awesome"); | |
| 145 | 177 | } |
| 146 | 178 | |
| 147 | - public UUID getId() { | |
| 148 | - return id; | |
| 149 | - } | |
| 179 | + @Column(name = "wrong") // gets overridden in all subclasses | |
| 180 | + public abstract UUID getId(); | |
| 150 | 181 | |
| 151 | 182 | public void setId(UUID id) { |
| 152 | 183 | this.id = id; |
| 153 | 184 | } |
| 154 | 185 | |
| 186 | + @Override | |
| 187 | + public Set<String> getTags() { | |
| 188 | + return tags; | |
| 189 | + } | |
| 190 | + | |
| 155 | 191 | @Override |
| 156 | 192 | public boolean equals(Object o) { |
| 157 | 193 | if (this == o) return true; |
| @@ -169,16 +205,30 @@ | ||
| 169 | 205 | @Table(name = "circles") |
| 170 | 206 | static class Circle extends Shape { |
| 171 | 207 | |
| 208 | + @Column(name = "center2d") // overridden by a getter in Sphere | |
| 209 | + @Frozen | |
| 172 | 210 | private Point2D center; |
| 173 | 211 | |
| 174 | - private double radius; | |
| 212 | + // tests unusual field name (i.e. does not correspond to getter/setter) | |
| 213 | + // will be considered as a separate "property" with no getter nor setter; | |
| 214 | + // thus needs to be annotated with @Transient | |
| 215 | + @Transient | |
| 216 | + private double _radius; | |
| 217 | + | |
| 218 | + private long writeTime; | |
| 175 | 219 | |
| 176 | 220 | public Circle() { |
| 177 | 221 | } |
| 178 | 222 | |
| 179 | 223 | public Circle(Point2D center, double radius) { |
| 180 | 224 | this.center = center; |
| 181 | - this.radius = radius; | |
| 225 | + this._radius = radius; | |
| 226 | + } | |
| 227 | + | |
| 228 | + @Column(name = "circle_id") | |
| 229 | + @Override | |
| 230 | + public UUID getId() { | |
| 231 | + return id; | |
| 182 | 232 | } |
| 183 | 233 | |
| 184 | 234 | public Point2D getCenter() { |
| @@ -190,11 +240,28 @@ | ||
| 190 | 240 | } |
| 191 | 241 | |
| 192 | 242 | public double getRadius() { |
| 193 | - return radius; | |
| 243 | + return _radius; | |
| 194 | 244 | } |
| 195 | 245 | |
| 196 | 246 | public void setRadius(double radius) { |
| 197 | - this.radius = radius; | |
| 247 | + this._radius = radius; | |
| 248 | + } | |
| 249 | + | |
| 250 | + @Override | |
| 251 | + // inherits @Transient | |
| 252 | + public double getArea() { | |
| 253 | + return Math.PI * (Math.pow(getRadius(), 2)); | |
| 254 | + } | |
| 255 | + | |
| 256 | + // tests computed columns - no setter | |
| 257 | + @Computed(value = "writetime(\"radius\")") | |
| 258 | + public long getWriteTime() { | |
| 259 | + return writeTime; | |
| 260 | + } | |
| 261 | + | |
| 262 | + // mismatched setter - getter is declared in Shape | |
| 263 | + public void setTags(Set<String> tags) { | |
| 264 | + this.tags = tags; | |
| 198 | 265 | } |
| 199 | 266 | |
| 200 | 267 | @Override |
| @@ -216,10 +283,8 @@ | ||
| 216 | 283 | @Table(name = "rectangles") |
| 217 | 284 | static class Rectangle extends Shape { |
| 218 | 285 | |
| 219 | - @Column(name = "bottom_left") | |
| 220 | 286 | private Point2D bottomLeft; |
| 221 | 287 | |
| 222 | - @Column(name = "top_right") | |
| 223 | 288 | private Point2D topRight; |
| 224 | 289 | |
| 225 | 290 | public Rectangle() { |
| @@ -230,6 +295,14 @@ | ||
| 230 | 295 | this.topRight = topRight; |
| 231 | 296 | } |
| 232 | 297 | |
| 298 | + @Column(name = "rect_id") | |
| 299 | + @Override | |
| 300 | + public UUID getId() { | |
| 301 | + return id; | |
| 302 | + } | |
| 303 | + | |
| 304 | + @Column(name = "bottom_left") | |
| 305 | + @Frozen | |
| 233 | 306 | public Point2D getBottomLeft() { |
| 234 | 307 | return bottomLeft; |
| 235 | 308 | } |
| @@ -238,6 +311,8 @@ | ||
| 238 | 311 | this.bottomLeft = bottomLeft; |
| 239 | 312 | } |
| 240 | 313 | |
| 314 | + @Column(name = "top_right") | |
| 315 | + @Frozen | |
| 241 | 316 | public Point2D getTopRight() { |
| 242 | 317 | return topRight; |
| 243 | 318 | } |
| @@ -246,6 +321,23 @@ | ||
| 246 | 321 | this.topRight = topRight; |
| 247 | 322 | } |
| 248 | 323 | |
| 324 | + // test annotation in class method | |
| 325 | + @Transient | |
| 326 | + public double getWidth() { | |
| 327 | + return Math.abs(topRight.getX() - bottomLeft.getX()); | |
| 328 | + } | |
| 329 | + | |
| 330 | + @Transient | |
| 331 | + public double getHeight() { | |
| 332 | + return Math.abs(topRight.getY() - bottomLeft.getY()); | |
| 333 | + } | |
| 334 | + | |
| 335 | + @Override | |
| 336 | + // inherits @Transient | |
| 337 | + public double getArea() { | |
| 338 | + return getWidth() * getHeight(); | |
| 339 | + } | |
| 340 | + | |
| 249 | 341 | @Override |
| 250 | 342 | public boolean equals(Object o) { |
| 251 | 343 | if (this == o) return true; |
| @@ -262,11 +354,56 @@ | ||
| 262 | 354 | } |
| 263 | 355 | } |
| 264 | 356 | |
| 357 | + @Table(name = "squares") | |
| 358 | + static class Square extends Rectangle { | |
| 359 | + | |
| 360 | + public Square() { | |
| 361 | + } | |
| 362 | + | |
| 363 | + public Square(Point2D bottomLeft, Point2D topRight) { | |
| 364 | + super(bottomLeft, topRight); | |
| 365 | + assert getHeight() == getWidth(); | |
| 366 | + } | |
| 367 | + | |
| 368 | + @Column(name = "square_id") | |
| 369 | + @Override | |
| 370 | + public UUID getId() { | |
| 371 | + return id; | |
| 372 | + } | |
| 373 | + | |
| 374 | + @Override | |
| 375 | + // inherits @Column and @Frozen | |
| 376 | + public Point2D getBottomLeft() { | |
| 377 | + return super.getBottomLeft(); | |
| 378 | + } | |
| 379 | + | |
| 380 | + @Override | |
| 381 | + // inherits @Transient | |
| 382 | + public double getHeight() { | |
| 383 | + return getWidth(); | |
| 384 | + } | |
| 385 | + | |
| 386 | + @Override | |
| 387 | + public boolean equals(Object o) { | |
| 388 | + if (this == o) return true; | |
| 389 | + if (o == null || getClass() != o.getClass()) return false; | |
| 390 | + if (!super.equals(o)) return false; | |
| 391 | + Square square = (Square) o; | |
| 392 | + return Objects.equal(getBottomLeft(), square.getBottomLeft()) && | |
| 393 | + Objects.equal(getTopRight(), square.getTopRight()); | |
| 394 | + } | |
| 395 | + | |
| 396 | + } | |
| 397 | + | |
| 265 | 398 | @Table(name = "spheres") |
| 266 | - static class Sphere extends Circle { | |
| 399 | + static class Sphere extends Circle implements Shape3D { | |
| 267 | 400 | |
| 401 | + // masks field Circle.center | |
| 402 | + @Frozen | |
| 268 | 403 | private Point3D center; |
| 269 | 404 | |
| 405 | + private long writeTime; | |
| 406 | + | |
| 270 | 407 | public Sphere() { |
| 271 | 408 | } |
| 272 | 409 | |
| @@ -274,6 +411,16 @@ | ||
| 274 | 411 | this.center = center; |
| 275 | 412 | } |
| 276 | 413 | |
| 414 | + @Column(name = "sphere_id") | |
| 415 | + @Override | |
| 416 | + public UUID getId() { | |
| 417 | + return id; | |
| 418 | + } | |
| 419 | + | |
| 420 | + // overrides field annotation in Circle, | |
| 421 | + // note that the property type is narrowed down to Point3D | |
| 422 | + @Column(name = "center3d") | |
| 423 | + @Frozen | |
| 277 | 424 | @Override |
| 278 | 425 | public Point3D getCenter() { |
| 279 | 426 | return center; |
| @@ -296,14 +443,14 @@ | ||
| 296 | 443 | public int hashCode() { |
| 297 | 444 | return Objects.hashCode(super.hashCode(), getCenter()); |
| 298 | 445 | } |
| 299 | - } | |
| 300 | 446 | |
| 301 | - @BeforeMethod(groups = "short") | |
| 302 | - public void createMappers() throws Exception { | |
| 303 | - MappingManager mappingManager = new MappingManager(session()); | |
| 304 | - circleMapper = mappingManager.mapper(Circle.class); | |
| 305 | - rectangleMapper = mappingManager.mapper(Rectangle.class); | |
| 306 | - sphereMapper = mappingManager.mapper(Sphere.class); | |
| 447 | + // test annotation on implementation | |
| 448 | + @Override | |
| 449 | + @Transient | |
| 450 | + public double getVolume() { | |
| 451 | + return 4d / 3d * Math.PI * Math.pow(getRadius(), 3); | |
| 452 | + } | |
| 453 | + | |
| 307 | 454 | } |
| 308 | 455 | |
| 309 | 456 | @Test(groups = "short") |
| @@ -318,6 +465,12 @@ | ||
| 318 | 465 | assertThat(rectangleMapper.get(rectangle.getId())).isEqualTo(rectangle); |
| 319 | 466 | } |
| 320 | 467 | |
| 468 | + @Test(groups = "short") | |
| 469 | + public void should_save_and_retrieve_square() throws Exception { | |
| 470 | + squareMapper.save(square); | |
| 471 | + assertThat(squareMapper.get(square.getId())).isEqualTo(square); | |
| 472 | + } | |
| 473 | + | |
| 321 | 474 | @Test(groups = "short") |
| 322 | 475 | public void should_save_and_retrieve_sphere() throws Exception { |
| 323 | 476 | sphereMapper.save(sphere); |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperTest.java +1 −2
| @@ -36,7 +36,7 @@ | ||
| 36 | 36 | /** |
| 37 | 37 | * Basic tests for the mapping module. |
| 38 | 38 | */ |
| 39 | -@SuppressWarnings("unused") | |
| 39 | +@SuppressWarnings({"unused", "WeakerAccess"}) | |
| 40 | 40 | public class MapperTest extends CCMTestsSupport { |
| 41 | 41 | |
| 42 | 42 | @Override |
| @@ -58,7 +58,6 @@ | ||
| 58 | 58 | * |
| 59 | 59 | * And the next step will be to support UDT (which should be relatively simple). |
| 60 | 60 | */ |
| 61 | - @SuppressWarnings("unused") | |
| 62 | 61 | @Table(name = "users", |
| 63 | 62 | readConsistency = "QUORUM", |
| 64 | 63 | writeConsistency = "QUORUM") |
modified manual/object_mapper/creating/README.md +226 −18
| @@ -39,20 +39,76 @@ | ||
| 39 | 39 | save, or delete operation in the mapper. (if unspecified, it defaults |
| 40 | 40 | to the cluster-wide setting) |
| 41 | 41 | |
| 42 | -The class must provide a default constructor, and all fields (except the | |
| 43 | -ones annotated `@Transient`) must have corresponding setters and | |
| 44 | -getters. | |
| 42 | +The class must provide a default constructor (it can however be private). | |
| 43 | + | |
| 44 | +The mapping of each table column can be customized through annotations placed on either a field declaration, | |
| 45 | +or on a Java bean property getter method. _Annotations on setters are not supported and will be | |
| 46 | +silently ignored by the mapper_. | |
| 47 | + | |
| 48 | +The following mappings are thus equivalent: | |
| 49 | + | |
| 50 | +```java | |
| 51 | +@Table(name = "users") | |
| 52 | +public static class User { | |
| 53 | + | |
| 54 | + // annotation on a field | |
| 55 | + @PartitionKey | |
| 56 | + @Column(name = "user_id") | |
| 57 | + private UUID userId; | |
| 58 | + | |
| 59 | + public UUID getUserId() { | |
| 60 | + return userId; | |
| 61 | + } | |
| 62 | + | |
| 63 | + public void setUserId(UUID userId) { | |
| 64 | + this.userId = userId; | |
| 65 | + } | |
| 66 | + | |
| 67 | +} | |
| 68 | + | |
| 69 | +@Table(name = "users") | |
| 70 | +public static class User { | |
| 71 | + | |
| 72 | + private UUID userId; | |
| 73 | + | |
| 74 | + // annotation on a getter method | |
| 75 | + @PartitionKey | |
| 76 | + @Column(name = "user_id") | |
| 77 | + public UUID getUserId() { | |
| 78 | + return userId; | |
| 79 | + } | |
| 80 | + | |
| 81 | + public void setUserId(UUID userId) { | |
| 82 | + this.userId = userId; | |
| 83 | + } | |
| 84 | + | |
| 85 | +} | |
| 86 | + | |
| 87 | +``` | |
| 88 | + | |
| 89 | +To explicitly exclude a Java bean property or a field from being mapped, | |
| 90 | +annotate either the field or the property getter method with `@Transient`. | |
| 91 | + | |
| 92 | +The mapper tries to "bind" fields and accessor methods (getters and setters) together | |
| 93 | +into a single logical abstraction; | |
| 94 | +it is therefore advised that users follow the [Java bean property conventions] | |
| 95 | +(java-beans) when designing mapped classes. | |
| 96 | + | |
| 97 | +In particular, when reading or writing mapped property values, the mapper will first | |
| 98 | +try the property getter and setter methods, if they are available; | |
| 99 | +and if they are not, the mapper will try a direct access to the property's corresponding field. | |
| 45 | 100 | |
| 46 | 101 | [table]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Table.html |
| 47 | 102 | [case-sensitive]:http://docs.datastax.com/en/cql/3.3/cql/cql_reference/ucase-lcase_r.html |
| 48 | 103 | [consistency level]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/ConsistencyLevel.html |
| 104 | +[java-beans]:https://docs.oracle.com/javase/tutorial/javabeans/writing/properties.html | |
| 49 | 105 | |
| 50 | 106 | #### Column names |
| 51 | 107 | |
| 52 | 108 | By default, the mapper tries to map each Java property to a |
| 53 | 109 | case insensitive column of the same name. If you want to use a different |
| 54 | 110 | name, or [case-sensitive] names, use the [@Column][column] annotation on |
| 55 | -the field. | |
| 111 | +the property. | |
| 56 | 112 | |
| 57 | 113 | [column]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Column.html |
| 58 | 114 | |
| @@ -84,8 +140,8 @@ | ||
| 84 | 140 | |
| 85 | 141 | #### Computed fields |
| 86 | 142 | |
| 87 | -[@Computed][computed] can be used on fields that are the result of a | |
| 88 | -computation on the Cassandra side. Typically a function call. Native | |
| 143 | +[@Computed][computed] can be used on properties that are the result of a | |
| 144 | +computation on the Cassandra side, typically a function call. Native | |
| 89 | 145 | functions in Cassandra like `writetime()` or [User Defined Functions] are |
| 90 | 146 | supported. |
| 91 | 147 | |
| @@ -94,7 +150,7 @@ | ||
| 94 | 150 | Integer ttl; |
| 95 | 151 | ``` |
| 96 | 152 | |
| 97 | -The CQL return type of function must match the type of the field, | |
| 153 | +The CQL return type of function must match the type of the property, | |
| 98 | 154 | otherwise an exception will be thrown. |
| 99 | 155 | |
| 100 | 156 | Computed fields are ignored when saving an entity. |
| @@ -108,18 +164,19 @@ | ||
| 108 | 164 | int f; |
| 109 | 165 | ``` |
| 110 | 166 | |
| 111 | -Finally, computed fields are only supported with [basic read | |
| 167 | +Finally, computed properties are only supported with [basic read | |
| 112 | 168 | operations](../using/#basic-crud-operations) at this time. |
| 113 | -Support in [accessors](../using/#accessors) in planned for a future | |
| 169 | +Support in [accessors](../using/#accessors) is planned for a future | |
| 114 | 170 | version (see |
| 115 | 171 | [JAVA-832](https://datastax-oss.atlassian.net/browse/JAVA-832)). |
| 116 | 172 | |
| 117 | 173 | [User Defined Functions]:http://www.planetcassandra.org/blog/user-defined-functions-in-cassandra-3-0/ |
| 118 | 174 | [computed]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Computed.html |
| 119 | 175 | |
| 120 | -#### Transient fields | |
| 176 | +#### Transient properties | |
| 121 | 177 | |
| 122 | -[@Transient][transient] can be used to prevent a field from being mapped. | |
| 178 | +[@Transient][transient] can be used to prevent a field or a Java bean property from being mapped. | |
| 179 | +It should be placed on either the field declaration or the property getter method. | |
| 123 | 180 | |
| 124 | 181 | [transient]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Transient.html |
| 125 | 182 | |
| @@ -148,12 +205,12 @@ | ||
| 148 | 205 | - `caseSensitiveKeyspace`: whether the keyspace name is case-sensitive. |
| 149 | 206 | - `caseSensitiveType`: whether the UDT name is case-sensitive. |
| 150 | 207 | |
| 151 | -The class must provide a default constructor, and all fields (except the | |
| 152 | -ones annotated `@Transient`) must have corresponding setters and | |
| 153 | -getters. | |
| 208 | +The class must provide a default constructor (it can however be private). | |
| 154 | 209 | |
| 155 | -As in table entities, fields are mapped to an UDT field of the same | |
| 156 | -name by default. To declare a different name or use case-sensitivity, | |
| 210 | +As for table entities, properties in UDT classes are mapped to an UDT field of the same | |
| 211 | +name by default. | |
| 212 | + | |
| 213 | +To declare a different name or use case-sensitivity, | |
| 157 | 214 | use the [@Field][field] annotation: |
| 158 | 215 | |
| 159 | 216 | ```java |
| @@ -178,8 +235,8 @@ | ||
| 178 | 235 | } |
| 179 | 236 | ``` |
| 180 | 237 | |
| 181 | -(this also works with UDTs inside collections or other UDTs, with | |
| 182 | -arbitrary level of nesting) | |
| 238 | +This also works with UDTs inside collections or other UDTs, with any arbitrary | |
| 239 | +nesting level. | |
| 183 | 240 | |
| 184 | 241 | [User Defined Types]: ../../udts/ |
| 185 | 242 | [udt]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/UDT.html |
| @@ -222,3 +279,154 @@ | ||
| 222 | 279 | [frozen]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Frozen.html |
| 223 | 280 | [frozenkey]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/FrozenKey.html |
| 224 | 281 | [frozenvalue]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/FrozenValue.html |
| 282 | + | |
| 283 | + | |
| 284 | +### Polymorphism support | |
| 285 | + | |
| 286 | +By default, the mapper will consider all Java bean properties and all fields | |
| 287 | +(including private ones) found in an entity class or in a UDT class, | |
| 288 | +as well as in their superclasses and superinterfaces. | |
| 289 | + | |
| 290 | +This allows for a (basic) polymorphic mapping of a given class hierarchy | |
| 291 | +into different CQL tables or UDTs. | |
| 292 | + | |
| 293 | +Currently, each concrete class must correspond to a table or a UDT, | |
| 294 | +and should be annotated accordingly. This corresponds to the so called | |
| 295 | +"Table per concrete class" mapping strategy provided by | |
| 296 | +some popular SQL mapping frameworks such as Hibernate. | |
| 297 | + | |
| 298 | +Here is an example of a polymorphic mapping: | |
| 299 | + | |
| 300 | +```sql | |
| 301 | +CREATE TYPE point2d (x int, y int); | |
| 302 | +CREATE TYPE point3d (x int, y int, z int); | |
| 303 | +CREATE TABLE rectangles (id uuid PRIMARY KEY, bottom_left frozen<point2d>, top_right frozen<point2d>); | |
| 304 | +CREATE TABLE spheres (id uuid PRIMARY KEY, center frozen<point3d>, radius double); | |
| 305 | +``` | |
| 306 | + | |
| 307 | +```java | |
| 308 | +@UDT(name = "point2d") | |
| 309 | +public class Point2D { | |
| 310 | + public int x; | |
| 311 | + public int y; | |
| 312 | +} | |
| 313 | + | |
| 314 | +@UDT(name = "point3d") | |
| 315 | +public class Point3D extends Point2D { | |
| 316 | + public int z; | |
| 317 | +} | |
| 318 | + | |
| 319 | +public interface Shape2D { | |
| 320 | + | |
| 321 | + @Transient | |
| 322 | + double getArea(); | |
| 323 | + | |
| 324 | +} | |
| 325 | + | |
| 326 | +public interface Shape3D { | |
| 327 | + | |
| 328 | + @Transient | |
| 329 | + double getVolume(); | |
| 330 | + | |
| 331 | +} | |
| 332 | + | |
| 333 | +public abstract class Shape { | |
| 334 | + | |
| 335 | + private UUID id; | |
| 336 | + | |
| 337 | + @PartitionKey | |
| 338 | + public UUID getId() { | |
| 339 | + return id; | |
| 340 | + } | |
| 341 | + | |
| 342 | + public void setId(UUID id) { | |
| 343 | + this.id = id; | |
| 344 | + } | |
| 345 | + | |
| 346 | +} | |
| 347 | + | |
| 348 | +@Table(name = "rectangles") | |
| 349 | +public class Rectangle extends Shape implements Shape2D { | |
| 350 | + | |
| 351 | + private Point2D bottomLeft; | |
| 352 | + private Point2D topRight; | |
| 353 | + | |
| 354 | + @Column(name = "bottom_left") | |
| 355 | + @Frozen | |
| 356 | + public Point2D getBottomLeft() { | |
| 357 | + return bottomLeft; | |
| 358 | + } | |
| 359 | + | |
| 360 | + public void setBottomLeft(Point2D bottomLeft) { | |
| 361 | + this.bottomLeft = bottomLeft; | |
| 362 | + } | |
| 363 | + | |
| 364 | + @Column(name = "top_right") | |
| 365 | + @Frozen | |
| 366 | + public Point2D getTopRight() { | |
| 367 | + return topRight; | |
| 368 | + } | |
| 369 | + | |
| 370 | + public void setTopRight(Point2D topRight) { | |
| 371 | + this.topRight = topRight; | |
| 372 | + } | |
| 373 | + | |
| 374 | + @Transient | |
| 375 | + public double getWidth() { | |
| 376 | + return Math.abs(topRight.x - bottomLeft.x); | |
| 377 | + } | |
| 378 | + | |
| 379 | + @Transient | |
| 380 | + public double getHeight() { | |
| 381 | + return Math.abs(topRight.y - bottomLeft.y); | |
| 382 | + } | |
| 383 | + | |
| 384 | + @Override | |
| 385 | + public double getArea() { | |
| 386 | + return getWidth() * getHeight(); | |
| 387 | + } | |
| 388 | + | |
| 389 | +} | |
| 390 | + | |
| 391 | +@Table(name = "spheres") | |
| 392 | +public class Sphere extends Shape implements Shape3D { | |
| 393 | + | |
| 394 | + private Point3D center; | |
| 395 | + private double radius; | |
| 396 | + | |
| 397 | + @Frozen | |
| 398 | + public Point3D getCenter() { | |
| 399 | + return center; | |
| 400 | + } | |
| 401 | + | |
| 402 | + public void setCenter(Point3D center) { | |
| 403 | + this.center = center; | |
| 404 | + } | |
| 405 | + | |
| 406 | + public double getRadius() { | |
| 407 | + return radius; | |
| 408 | + } | |
| 409 | + | |
| 410 | + public void setRadius(double radius) { | |
| 411 | + this.radius = radius; | |
| 412 | + } | |
| 413 | + | |
| 414 | + @Override | |
| 415 | + public double getVolume() { | |
| 416 | + return 4d / 3d * Math.PI * Math.pow(getRadius(), 3); | |
| 417 | + } | |
| 418 | + | |
| 419 | +} | |
| 420 | +``` | |
| 421 | + | |
| 422 | +It is usually recommended to adopt one strategy or the other for | |
| 423 | +placing annotations on class members (i.e., either always on fields, or always on getters), | |
| 424 | +but not both at the same time, unless strictly required. | |
| 425 | +Usually, annotating getters is more flexible than annotating fields. | |
| 426 | + | |
| 427 | +If the mapper needs to disambiguate a specific property mapping, | |
| 428 | +note that annotations on getters will always take precedence over annotations on fields. | |
| 429 | +Likewise, if a getter method is overridden in a subclass, annotations in both | |
| 430 | +methods will get merged together, and in case of conflict, the overriding method's annotations | |
| 431 | +will take precedence over the overridden's. | |
| 432 | + |