Elffuss BraidHub

kikocis/java-driver public

JAVA-636: Allow @Column annotations on getters/setters as well as fields

This commit also includes a refactoring of the mapper internals:
- ColumnMapper renamed to PropertyMapper;
- No more factory patterns to create mappers;
- ReflectionX classes removed and merged into their parent classes;
- QueryType class cleanup.
Changeset42b5c0e4eb367e47f64562ca0967987b122015b05a0ecd74c781be903d940014
AuthorAlexandre Dutra <alexandre.dutra@datastax.com> · 2016-05-30 18:44 +02:00
Committerolim7t <omichallat+github@gmail.com> · 2016-07-22 09:45 -07:00
Parents845bfcad3488

Browse the files at this changeset

32 files changed

modified changelog/README.md +1 −0
@@ -11,6 +11,7 @@
1111 - [improvement] JAVA-1212: Don't retry non-idempotent statements by default.
1212 - [improvement] JAVA-1192: Make EventDebouncer settings updatable at runtime.
1313 - [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.
1415
1516 Merged from 3.0.x branch:
1617
modified clirr-ignores.xml +7 −0
@@ -13,6 +13,13 @@
1313 -->
1414 <differences>
1515
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+
1623 <difference>
1724 <differenceType>1001</differenceType> <!-- decreased visibility -->
1825 <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 @@
2525
2626 ASC, DESC;
2727
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 @@
1919 import com.google.common.util.concurrent.Futures;
2020 import com.google.common.util.concurrent.ListenableFuture;
2121
22+import java.lang.reflect.Proxy;
2223 import java.util.ArrayList;
2324 import java.util.List;
2425
25-abstract class AccessorMapper<T> {
26+class AccessorMapper<T> {
2627
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;
2932
30- protected AccessorMapper(Class<T> daoClass, List<MethodMapper> methods) {
33+ @SuppressWarnings({"unchecked", "rawtypes"})
34+ AccessorMapper(Class<T> daoClass, List<MethodMapper> methods) {
3135 this.daoClass = daoClass;
3236 this.methods = methods;
37+ this.proxyClasses = (Class<T>[]) new Class[]{daoClass};
38+ this.handler = new AccessorInvocationHandler<T>(this);
3339 }
3440
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+ }
3649
37- public void prepare(MappingManager manager) {
50+ void prepare(MappingManager manager) {
3851 List<ListenableFuture<PreparedStatement>> statements = new ArrayList<ListenableFuture<PreparedStatement>>(methods.size());
3952
4053 for (MethodMapper method : methods)
@@ -49,7 +62,4 @@
4962 }
5063 }
5164
52- interface Factory {
53- public <T> AccessorMapper<T> create(Class<T> daoClass, List<MethodMapper> methods);
54- }
5565 }
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 @@
6161 /**
6262 * Checks that a field is only annotated with the given mapping annotations, and that its "frozen" annotations are valid.
6363 */
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);
6666 if (invalid != null)
6767 throw new IllegalArgumentException(String.format("Annotation @%s is not allowed on property %s",
6868 invalid.getSimpleName(),
@@ -88,16 +88,16 @@
8888 return false;
8989 }
9090
91- private static void checkValidPrimaryKey(MappedProperty<?> property) {
91+ private static void checkValidPrimaryKey(PropertyMapper property) {
9292 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");
9494 }
9595
96- private static void checkValidComputed(MappedProperty<?> property) {
96+ private static void checkValidComputed(PropertyMapper property) {
9797 if (property.isComputed()) {
9898 Computed computed = property.annotation(Computed.class);
9999 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));
101101 }
102102 if (property.hasAnnotation(Column.class)) {
103103 throw new IllegalArgumentException("Cannot use @Column and @Computed on the same property");
@@ -105,24 +105,20 @@
105105 }
106106 }
107107
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");
117113 }
118114
119- static <T> void validateOrder(List<MappedProperty<T>> properties, String annotation) {
115+ static void validateOrder(List<PropertyMapper> properties, String annotation) {
120116 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();
123119 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));
126122 }
127123 }
128124 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/AnnotationParser.java +69 −90
@@ -22,33 +22,38 @@
2222 import com.datastax.driver.mapping.MethodMapper.ParamMapper;
2323 import com.datastax.driver.mapping.annotations.*;
2424 import com.google.common.base.Strings;
25-import com.google.common.collect.Maps;
2625 import com.google.common.reflect.TypeToken;
2726
28-import java.beans.BeanInfo;
2927 import java.beans.PropertyDescriptor;
3028 import java.lang.annotation.Annotation;
3129 import java.lang.reflect.Method;
3230 import java.lang.reflect.ParameterizedType;
3331 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.*;
3833 import java.util.concurrent.atomic.AtomicInteger;
3934
4035 import static com.datastax.driver.core.Metadata.quote;
4136
4237 /**
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.
4442 */
4543 @SuppressWarnings("unchecked")
4644 class AnnotationParser {
4745
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+
4853 private AnnotationParser() {
4954 }
5055
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) {
5257 Table table = AnnotationChecks.getTypeAnnotation(Table.class, entityClass);
5358
5459 String ksName = table.caseSensitiveKeyspace() ? table.keyspace() : table.keyspace().toLowerCase();
@@ -67,79 +72,67 @@
6772 ));
6873 }
6974
70- EntityMapper<T> mapper = factory.create(entityClass, ksName, tableName, writeConsistency, readConsistency);
75+ EntityMapper<T> mapper = new EntityMapper<T>(entityClass, ksName, tableName, writeConsistency, readConsistency);
7176 TableMetadata tableMetadata = mappingManager.getSession().getCluster().getMetadata().getKeyspace(ksName).getTable(tableName);
7277
7378 if (tableMetadata == null)
7479 throw new IllegalArgumentException(String.format("Table %s does not exist in keyspace %s", tableName, ksName));
7580
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>();
7984
80- BeanInfo beanInfo = ReflectionUtils.getBeanInfo(entityClass);
85+ Map<String, Object[]> fieldsAndProperties = ReflectionUtils.scanFieldsAndProperties(entityClass);
86+ AtomicInteger columnCounter = mappingManager.isCassandraV1 ? null : new AtomicInteger(0);
8187
82- for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) {
88+ for (Map.Entry<String, Object[]> entry : fieldsAndProperties.entrySet()) {
8389
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;
8696
87- MappedProperty<T> property = new MappedProperty<T>(descriptor, entityClass);
97+ PropertyMapper propertyMapper = new PropertyMapper(propertyName, alias, field, property);
8898
89- if (mappingManager.isCassandraV1 && property.isComputed())
99+ if (mappingManager.isCassandraV1 && propertyMapper.isComputed())
90100 throw new UnsupportedOperationException("Computed properties are not supported with native protocol v1");
91101
92- AnnotationChecks.validateAnnotations(property,
102+ AnnotationChecks.validateAnnotations(propertyMapper,
93103 Column.class, ClusteringColumn.class, Frozen.class, FrozenKey.class,
94104 FrozenValue.class, PartitionKey.class, Transient.class, Computed.class);
95105
96- if (property.isTransient())
106+ if (propertyMapper.isTransient())
97107 continue;
98108
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);
110123 }
111124
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);
116127
117128 AnnotationChecks.validateOrder(pks, "@PartitionKey");
118129 AnnotationChecks.validateOrder(ccs, "@ClusteringColumn");
119130
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);
124132 return mapper;
125133 }
126134
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) {
143136 UDT udt = AnnotationChecks.getTypeAnnotation(UDT.class, udtClass);
144137
145138 String ksName = udt.caseSensitiveKeyspace() ? udt.keyspace() : udt.keyspace().toLowerCase();
@@ -159,54 +152,36 @@
159152 if (userType == null)
160153 throw new IllegalArgumentException(String.format("User type %s does not exist in keyspace %s", udtName, ksName));
161154
162- List<MappedProperty<T>> columns = new ArrayList<MappedProperty<T>>();
155+ Map<String, PropertyMapper> propertyMappers = new HashMap<String, PropertyMapper>();
163156
164- BeanInfo beanInfo = ReflectionUtils.getBeanInfo(udtClass);
157+ Map<String, Object[]> fieldsAndProperties = ReflectionUtils.scanFieldsAndProperties(udtClass);
165158
166- for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) {
159+ for (Map.Entry<String, Object[]> entry : fieldsAndProperties.entrySet()) {
167160
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];
170164
171- MappedProperty<T> property = new MappedProperty<T>(descriptor, udtClass);
165+ PropertyMapper propertyMapper = new PropertyMapper(propertyName, null, field, property);
172166
173- AnnotationChecks.validateAnnotations(property,
167+ AnnotationChecks.validateAnnotations(propertyMapper,
174168 Field.class, Frozen.class, FrozenKey.class,
175169 FrozenValue.class, Transient.class);
176170
177- if (property.isTransient())
171+ if (propertyMapper.isTransient())
178172 continue;
179173
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))
196175 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()));
205177
178+ AnnotationChecks.validatePrimaryKeyOnUDT(propertyMapper);
179+ propertyMappers.put(propertyMapper.columnName, propertyMapper);
180+ }
181+ return new MappedUDTCodec<T>(userType, udtClass, propertyMappers, mappingManager);
206182 }
207183
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) {
210185 if (!accClass.isInterface())
211186 throw new IllegalArgumentException("@Accessor annotation is only allowed on interfaces");
212187
@@ -267,7 +242,11 @@
267242 methods.add(new MethodMapper(m, queryString, paramMappers, cl, fetchSize, tracing, idempotent));
268243 }
269244
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;
271250 }
272251
273252 @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 @@
1919
2020 import java.util.ArrayList;
2121 import java.util.List;
22-import java.util.concurrent.atomic.AtomicInteger;
2322
2423 import static com.datastax.driver.core.querybuilder.QueryBuilder.quote;
2524
26-abstract class EntityMapper<T> {
25+class EntityMapper<T> {
2726
28- final Class<T> entityClass;
27+ private final Class<T> entityClass;
2928 private final String keyspace;
3029 private final String table;
3130
3231 final ConsistencyLevel writeConsistency;
3332 final ConsistencyLevel readConsistency;
3433
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>();
3836
39- private final List<ColumnMapper<T>> allColumns = new ArrayList<ColumnMapper<T>>();
37+ final List<PropertyMapper> allColumns = new ArrayList<PropertyMapper>();
4038
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) {
4240 this.entityClass = entityClass;
4341 this.keyspace = keyspace;
4442 this.table = table;
@@ -58,34 +56,20 @@
5856 return partitionKeys.size() + clusteringColumns.size();
5957 }
6058
61- ColumnMapper<T> getPrimaryKeyColumn(int i) {
59+ PropertyMapper getPrimaryKeyColumn(int i) {
6260 return i < partitionKeys.size() ? partitionKeys.get(i) : clusteringColumns.get(i - partitionKeys.size());
6361 }
6462
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) {
6664 partitionKeys.addAll(pks);
67- allColumns.addAll(pks);
68-
6965 clusteringColumns.addAll(ccs);
66+ allColumns.addAll(pks);
7067 allColumns.addAll(ccs);
71-
72- addColumns(rgs);
73- }
74-
75- void addColumns(List<ColumnMapper<T>> rgs) {
76- regularColumns.addAll(rgs);
7768 allColumns.addAll(rgs);
7869 }
7970
80- abstract T newEntity();
81-
82- List<ColumnMapper<T>> allColumns() {
83- return allColumns;
71+ T newEntity() {
72+ return ReflectionUtils.newInstance(entityClass);
8473 }
8574
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- }
9175 }
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 @@
2626 class MappedUDTCodec<T> extends TypeCodec.AbstractUDTCodec<T> {
2727 private final UserType cqlUserType;
2828 private final Class<T> udtClass;
29- private final Map<String, ColumnMapper<T>> columnMappers;
29+ private final Map<String, PropertyMapper> columnMappers;
3030 private final CodecRegistry codecRegistry;
3131
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) {
3333 super(cqlUserType, udtClass);
3434 this.cqlUserType = cqlUserType;
3535 this.udtClass = udtClass;
@@ -39,11 +39,7 @@
3939
4040 @Override
4141 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);
4743 }
4844
4945 Class<T> getUdtClass() {
@@ -56,16 +52,16 @@
5652 if (!fieldName.startsWith("\""))
5753 fieldName = Metadata.quote(fieldName);
5854
59- ColumnMapper<T> columnMapper = columnMappers.get(fieldName);
55+ PropertyMapper propertyMapper = columnMappers.get(fieldName);
6056
61- if (columnMapper == null)
57+ if (propertyMapper == null)
6258 return null;
6359
64- Object value = columnMapper.getValue(source);
60+ Object value = propertyMapper.getValue(source);
6561
66- TypeCodec<Object> codec = columnMapper.getCustomCodec();
62+ TypeCodec<Object> codec = propertyMapper.customCodec;
6763 if (codec == null)
68- codec = codecRegistry.codecFor(cqlUserType.getFieldType(columnMapper.getColumnName()), columnMapper.getJavaType());
64+ codec = codecRegistry.codecFor(cqlUserType.getFieldType(propertyMapper.columnName), propertyMapper.javaType);
6965
7066 return codec.serialize(value, protocolVersion);
7167 }
@@ -75,12 +71,12 @@
7571 if (!fieldName.startsWith("\""))
7672 fieldName = Metadata.quote(fieldName);
7773
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;
8177 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));
8480 }
8581 return target;
8682 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/Mapper.java +25 −27
@@ -49,11 +49,10 @@
4949 private static final Logger logger = LoggerFactory.getLogger(Mapper.class);
5050 private static final Function<Object, Void> TO_NULL = Functions.constant(null);
5151
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;
5756
5857 // Cache prepared statements for each type of query we use.
5958 private final ConcurrentMap<MapperQueryKey, ListenableFuture<PreparedStatement>> preparedQueries = new ConcurrentHashMap<MapperQueryKey, ListenableFuture<PreparedStatement>>();
@@ -64,7 +63,7 @@
6463
6564 private static final EnumMap<Option.Type, Option> NO_OPTIONS = new EnumMap<Option.Type, Option>(Option.Type.class);
6665
67- final Function<ResultSet, T> mapOneFunction;
66+ private final Function<ResultSet, T> mapOneFunction;
6867 final Function<ResultSet, T> mapOneFunctionWithoutAliases;
6968 final Function<ResultSet, Result<T>> mapAllFunctionWithoutAliases;
7069
@@ -76,7 +75,6 @@
7675 KeyspaceMetadata keyspace = session().getCluster().getMetadata().getKeyspace(mapper.getKeyspace());
7776 this.tableMetadata = keyspace == null ? null : keyspace.getTable(mapper.getTable());
7877
79- this.protocolVersion = manager.getSession().getCluster().getConfiguration().getProtocolOptions().getProtocolVersion();
8078 this.mapOneFunction = new Function<ResultSet, T>() {
8179 @Override
8280 public T apply(ResultSet rs) {
@@ -105,7 +103,7 @@
105103 return manager.getSession();
106104 }
107105
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) {
109107
110108 final MapperQueryKey pqk = new MapperQueryKey(type, columns, options);
111109 ListenableFuture<PreparedStatement> existingFuture = preparedQueries.get(pqk);
@@ -139,7 +137,7 @@
139137 }
140138
141139 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);
143141 }
144142
145143 Class<T> getMappedClass() {
@@ -213,13 +211,13 @@
213211 }
214212
215213 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>();
217215 boolean saveNullFields = shouldSaveNullFields(options);
218216
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);
223221 }
224222 }
225223
@@ -228,8 +226,8 @@
228226 public BoundStatement apply(PreparedStatement input) {
229227 BoundStatement bs = input.bind();
230228 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();
233231 Object value = entry.getValue();
234232 setObject(bs, i++, value, mapper);
235233 }
@@ -252,12 +250,12 @@
252250 return option == null || option.saveNullFields;
253251 }
254252
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;
257255 if (customCodec != null)
258256 bs.set(i, value, customCodec);
259257 else
260- bs.set(i, value, mapper.getJavaType());
258+ bs.set(i, value, mapper.javaType);
261259 }
262260
263261 /**
@@ -390,9 +388,9 @@
390388 BoundStatement bs = new MapperBoundStatement(input);
391389 int i = 0;
392390 for (Object value : primaryKeys) {
393- ColumnMapper<T> column = mapper.getPrimaryKeyColumn(i);
391+ PropertyMapper column = mapper.getPrimaryKeyColumn(i);
394392 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));
396394 }
397395 setObject(bs, i++, value, column);
398396 }
@@ -599,9 +597,9 @@
599597
600598 int columnNumber = 0;
601599 for (Object value : primaryKey) {
602- ColumnMapper<T> column = mapper.getPrimaryKeyColumn(columnNumber);
600+ PropertyMapper column = mapper.getPrimaryKeyColumn(columnNumber);
603601 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));
605603 }
606604 setObject(bs, i++, value, column);
607605 columnNumber++;
@@ -1130,14 +1128,14 @@
11301128 private static class MapperQueryKey {
11311129 private final QueryType queryType;
11321130 private final EnumSet<Option.Type> optionTypes;
1133- private final Set<ColumnMapper<?>> columns;
1131+ private final Set<PropertyMapper> columns;
11341132
1135- MapperQueryKey(QueryType queryType, Set<ColumnMapper<?>> columnMappers, EnumMap<Option.Type, Option> options) {
1133+ MapperQueryKey(QueryType queryType, Set<PropertyMapper> propertyMappers, EnumMap<Option.Type, Option> options) {
11361134 Preconditions.checkNotNull(queryType);
11371135 Preconditions.checkNotNull(options);
1138- Preconditions.checkNotNull(columnMappers);
1136+ Preconditions.checkNotNull(propertyMappers);
11391137 this.queryType = queryType;
1140- this.columns = columnMappers;
1138+ this.columns = propertyMappers;
11411139 this.optionTypes = EnumSet.noneOf(Option.Type.class);
11421140 for (Option opt : options.values()) {
11431141 if (opt.isIncludedInQuery())
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MappingManager.java +3 −3
@@ -223,7 +223,7 @@
223223 synchronized (mappers) {
224224 mapper = (Mapper<T>) mappers.get(klass);
225225 if (mapper == null) {
226- EntityMapper<T> entityMapper = AnnotationParser.parseEntity(klass, ReflectionMapper.factory(), this);
226+ EntityMapper<T> entityMapper = AnnotationParser.parseEntity(klass, this);
227227 mapper = new Mapper<T>(this, klass, entityMapper);
228228 Map<Class<?>, Mapper<?>> newMappers = new HashMap<Class<?>, Mapper<?>>(mappers);
229229 newMappers.put(klass, mapper);
@@ -241,7 +241,7 @@
241241 synchronized (udtCodecs) {
242242 codec = (MappedUDTCodec<T>) udtCodecs.get(mappedClass);
243243 if (codec == null) {
244- codec = AnnotationParser.parseUDT(mappedClass, ReflectionMapper.factory(), this);
244+ codec = AnnotationParser.parseUDT(mappedClass, this);
245245 session.getCluster().getConfiguration().getCodecRegistry().register(codec);
246246
247247 HashMap<Class<?>, MappedUDTCodec<?>> newCodecs = new HashMap<Class<?>, MappedUDTCodec<?>>(udtCodecs);
@@ -260,7 +260,7 @@
260260 synchronized (accessors) {
261261 accessor = (T) accessors.get(klass);
262262 if (accessor == null) {
263- AccessorMapper<T> mapper = AnnotationParser.parseAccessor(klass, AccessorReflectionMapper.factory(), this);
263+ AccessorMapper<T> mapper = AnnotationParser.parseAccessor(klass, this);
264264 mapper.prepare(this);
265265 accessor = mapper.createProxy();
266266 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 @@
2626 import java.lang.reflect.Type;
2727 import java.util.Set;
2828
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
3129 class MethodMapper {
3230
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;
3634
3735 private final ConsistencyLevel consistency;
3836 private final int fetchSize;
@@ -132,17 +130,16 @@
132130 throw new RuntimeException(String.format("Cannot map return of method %s to unsupported type %s", method, type));
133131
134132 try {
135- this.returnMapper = (Mapper<?>) manager.mapper((Class<?>) type);
133+ this.returnMapper = manager.mapper((Class<?>) type);
136134 } catch (Exception e) {
137135 throw new RuntimeException("Cannot map return to class " + fullReturnType, e);
138136 }
139137 }
140138
141- public Object invoke(Object[] args) {
139+ Object invoke(Object[] args) {
142140
143141 BoundStatement bs = statement.bind();
144142
145- ProtocolVersion protocolVersion = session.getCluster().getConfiguration().getProtocolOptions().getProtocolVersion();
146143 for (int i = 0; i < args.length; i++) {
147144 paramMappers[i].setValue(bs, args[i]);
148145 }
@@ -185,7 +182,7 @@
185182 private final TypeCodec<Object> codec;
186183
187184 @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) {
189186 this.paramName = paramName;
190187 this.paramIdx = paramIdx;
191188 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 @@
4040 private final int endBoundSize;
4141 private final boolean endInclusive;
4242
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);
4646
4747 private QueryType(Kind kind) {
4848 this(kind, 0, false, 0, false);
@@ -56,15 +56,15 @@
5656 this.endInclusive = endInclusive;
5757 }
5858
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) {
6060 switch (kind) {
6161 case SAVE: {
6262 Insert insert = table == null
6363 ? insertInto(mapper.getKeyspace(), mapper.getTable())
6464 : 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());
6868
6969 Insert.Options usings = insert.using();
7070 for (Mapper.Option opt : options) {
@@ -76,15 +76,15 @@
7676 }
7777 case GET: {
7878 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) {
8585 selection = column;
8686 } else {
87- selection = column.as(cm.getAlias());
87+ selection = column.as(col.alias);
8888 }
8989 }
9090 Select select;
@@ -95,7 +95,7 @@
9595 }
9696 Select.Where where = select.where();
9797 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()));
9999
100100 for (Mapper.Option opt : options)
101101 opt.checkValidFor(QueryType.GET, manager);
@@ -107,7 +107,7 @@
107107 : delete().all().from(table);
108108 Delete.Where where = delete.where();
109109 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()));
111111 Delete.Options usings = delete.using();
112112 for (Mapper.Option opt : options) {
113113 opt.checkValidFor(QueryType.DEL, manager);
@@ -123,17 +123,17 @@
123123 : select().all().from(table);
124124 Select.Where where = select.where();
125125 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()));
127127
128128 if (startBoundSize > 0) {
129129 if (startBoundSize == 1) {
130- String name = mapper.clusteringColumns.get(0).getColumnName();
130+ String name = mapper.clusteringColumns.get(0).columnName;
131131 where.and(startInclusive ? gte(name, bindMarker()) : gt(name, bindMarker()));
132132 } else {
133133 List<String> names = new ArrayList<String>(startBoundSize);
134134 List<Object> values = new ArrayList<Object>(startBoundSize);
135135 for (int i = 0; i < startBoundSize; i++) {
136- names.add(mapper.clusteringColumns.get(i).getColumnName());
136+ names.add(mapper.clusteringColumns.get(i).columnName);
137137 values.add(bindMarker());
138138 }
139139 where.and(startInclusive ? gte(names, values) : gt(names, values));
@@ -142,13 +142,13 @@
142142
143143 if (endBoundSize > 0) {
144144 if (endBoundSize == 1) {
145- String name = mapper.clusteringColumns.get(0).getColumnName();
145+ String name = mapper.clusteringColumns.get(0).columnName;
146146 where.and(endInclusive ? gte(name, bindMarker()) : gt(name, bindMarker()));
147147 } else {
148148 List<String> names = new ArrayList<String>(endBoundSize);
149149 List<Object> values = new ArrayList<Object>(endBoundSize);
150150 for (int i = 0; i < endBoundSize; i++) {
151- names.add(mapper.clusteringColumns.get(i).getColumnName());
151+ names.add(mapper.clusteringColumns.get(i).columnName);
152152 values.add(bindMarker());
153153 }
154154 where.and(endInclusive ? lte(names, values) : lt(names, values));
@@ -158,7 +158,7 @@
158158 select = select.limit(bindMarker());
159159
160160 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));
162162
163163 return select.toString();
164164 }
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 @@
2222 import java.beans.Introspector;
2323 import java.beans.PropertyDescriptor;
2424 import java.lang.annotation.Annotation;
25+import java.lang.reflect.Constructor;
2526 import java.lang.reflect.Field;
2627 import java.lang.reflect.Method;
2728 import java.lang.reflect.Modifier;
@@ -33,36 +34,125 @@
3334 */
3435 class ReflectionUtils {
3536
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) {
3784 BeanInfo beanInfo;
3885 try {
39- beanInfo = Introspector.getBeanInfo(udtClass);
86+ beanInfo = Introspector.getBeanInfo(baseClass);
4087 } catch (IntrospectionException e) {
4188 throw Throwables.propagate(e);
4289 }
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;
4497 }
4598
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) {
48100 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) {
50111 if (field != null) {
51112 for (Annotation annotation : field.getAnnotations()) {
52113 annotations.put(annotation.annotationType(), annotation);
53114 }
54115 }
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()) {
59123 annotations.put(annotation.annotationType(), annotation);
60124 }
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+ }
61136 }
62137 return annotations;
63138 }
64139
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+
65153 static Method findGetter(PropertyDescriptor property) {
154+ if (property == null)
155+ return null;
66156 Method getter = property.getReadMethod();
67157 if (getter == null)
68158 return null;
@@ -71,6 +161,8 @@
71161 }
72162
73163 static Method findSetter(PropertyDescriptor property) {
164+ if (property == null)
165+ return null;
74166 Method setter = property.getWriteMethod();
75167 if (setter == null)
76168 return null;
@@ -78,19 +170,4 @@
78170 return setter;
79171 }
80172
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-
96173 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/Result.java +5 −5
@@ -43,20 +43,20 @@
4343
4444 private T map(Row row) {
4545 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;
4848 if (!row.getColumnDefinitions().contains(name))
4949 continue;
5050
5151 Object value;
52- TypeCodec<Object> customCodec = cm.getCustomCodec();
52+ TypeCodec<Object> customCodec = col.customCodec;
5353 if (customCodec != null)
5454 value = row.get(name, customCodec);
5555 else
56- value = row.get(name, cm.getJavaType());
56+ value = row.get(name, col.javaType);
5757
5858 if (shouldSetValue(value)) {
59- cm.setValue(entity, value);
59+ col.setValue(entity, value);
6060 }
6161 }
6262 return entity;
modified driver-mapping/src/main/java/com/datastax/driver/mapping/TypeMappings.java +1 −1
@@ -30,7 +30,7 @@
3030 */
3131 class TypeMappings {
3232
33- static boolean mapsToCollection(Class<?> klass) {
33+ private static boolean mapsToCollection(Class<?> klass) {
3434 return mapsToList(klass) || mapsToSet(klass) || mapsToMap(klass);
3535 }
3636
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/ClusteringColumn.java +2 −2
@@ -21,12 +21,12 @@
2121 import java.lang.annotation.Target;
2222
2323 /**
24- * Annotation for fields that map to a CQL clustering column.
24+ * Annotation for properties that map to a CQL clustering column.
2525 * <p/>
2626 * If the mapped table has multiple clustering columns, it is mandatory
2727 * to specify the ordinal parameter to avoid ordering ambiguity.
2828 */
29-@Target(ElementType.FIELD)
29+@Target({ElementType.FIELD, ElementType.METHOD})
3030 @Retention(RetentionPolicy.RUNTIME)
3131 public @interface ClusteringColumn {
3232 /**
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Column.java +7 −7
@@ -24,21 +24,21 @@
2424
2525 /**
2626 * Annotation that allows to specify the name of the CQL column to which the
27- * field should be mapped.
27+ * property should be mapped.
2828 * <p/>
2929 * 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
3233 * {@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.
3535 */
36-@Target(ElementType.FIELD)
36+@Target({ElementType.FIELD, ElementType.METHOD})
3737 @Retention(RetentionPolicy.RUNTIME)
3838 public @interface Column {
3939 /**
4040 * 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.
4242 *
4343 * @return the name of the mapped column in Cassandra, or {@code ""} to use
4444 * the field name.
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Computed.java +6 −6
@@ -24,26 +24,26 @@
2424 import java.lang.annotation.Target;
2525
2626 /**
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
2828 * used to retrieve an entity.
2929 * <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...)}),
3131 * they will be ignored in accessor queries and save operations.
3232 * <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
3434 * contains case-sensitive names, you'll need to quote them explicitly:
3535 * <pre>
3636 * {@code @Computed("\"caseSensitiveFunction\"(v)")}
3737 * </pre>
3838 */
39-@Target(ElementType.FIELD)
39+@Target({ElementType.FIELD, ElementType.METHOD})
4040 @Retention(RetentionPolicy.RUNTIME)
4141 public @interface Computed {
4242 /**
43- * The formula used to compute the field.
43+ * The formula used to compute the property.
4444 * <p/>
4545 * This is a CQL expression like you would use directly in a query, for instance
46- * "writetime(v)".
46+ * {@code "writetime(v)"}.
4747 *
4848 * @return the formula.
4949 */
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Field.java +7 −7
@@ -24,21 +24,21 @@
2424
2525 /**
2626 * 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.
2828 * <p/>
2929 * 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
3233 * {@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.
3535 */
36-@Target(ElementType.FIELD)
36+@Target({ElementType.FIELD, ElementType.METHOD})
3737 @Retention(RetentionPolicy.RUNTIME)
3838 public @interface Field {
3939 /**
4040 * 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.
4242 *
4343 * @return the name of the mapped column in Cassandra, or {@code ""} to use
4444 * the field name.
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Frozen.java +2 −2
@@ -23,7 +23,7 @@
2323 import java.lang.annotation.Target;
2424
2525 /**
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},
2727 * or contains frozen subtypes.
2828 * <p/>
2929 * This annotation is purely informational at this stage, the validity of the declaration is not checked.
@@ -33,7 +33,7 @@
3333 * @see FrozenKey
3434 * @see FrozenValue
3535 */
36-@Target(ElementType.FIELD)
36+@Target({ElementType.FIELD, ElementType.METHOD})
3737 @Retention(RetentionPolicy.RUNTIME)
3838 public @interface Frozen {
3939
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/FrozenKey.java +2 −2
@@ -21,13 +21,13 @@
2121 import java.lang.annotation.Target;
2222
2323 /**
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.
2525 * <p/>
2626 * This is equivalent to {@code @Frozen("map<frozen<foo>, bar>")}.
2727 *
2828 * @see Frozen
2929 */
30-@Target(ElementType.FIELD)
30+@Target({ElementType.FIELD, ElementType.METHOD})
3131 @Retention(RetentionPolicy.RUNTIME)
3232 public @interface FrozenKey {
3333 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/FrozenValue.java +2 −2
@@ -21,7 +21,7 @@
2121 import java.lang.annotation.Target;
2222
2323 /**
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.
2525 * <p/>
2626 * This is equivalent to any of the following:
2727 * <ul>
@@ -32,7 +32,7 @@
3232 *
3333 * @see Frozen
3434 */
35-@Target(ElementType.FIELD)
35+@Target({ElementType.FIELD, ElementType.METHOD})
3636 @Retention(RetentionPolicy.RUNTIME)
3737 public @interface FrozenValue {
3838 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/PartitionKey.java +2 −2
@@ -21,13 +21,13 @@
2121 import java.lang.annotation.Target;
2222
2323 /**
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
2525 * component if the partition key is composite).
2626 * <p/>
2727 * If the partition key of the mapped table is composite, it is mandatory
2828 * to specify the ordinal parameter to avoid ordering ambiguity.
2929 */
30-@Target(ElementType.FIELD)
30+@Target({ElementType.FIELD, ElementType.METHOD})
3131 @Retention(RetentionPolicy.RUNTIME)
3232 public @interface PartitionKey {
3333 /**
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Transient.java +4 −4
@@ -21,14 +21,14 @@
2121 import java.lang.annotation.Target;
2222
2323 /**
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
2525 * to any column (neither during reads nor writes).
2626 * <p/>
2727 * 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}.
3030 */
31-@Target(ElementType.FIELD)
31+@Target({ElementType.FIELD, ElementType.METHOD})
3232 @Retention(RetentionPolicy.RUNTIME)
3333 public @interface Transient {
3434 }
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperPolymorphismTest.java +206 −53
@@ -16,51 +16,72 @@
1616 package com.datastax.driver.mapping;
1717
1818 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.*;
2320 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;
2524 import org.testng.annotations.Test;
2625
26+import java.util.Set;
2727 import java.util.UUID;
2828
2929 import static org.assertj.core.api.Assertions.assertThat;
3030
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"})
3237 public class MapperPolymorphismTest extends CCMTestsSupport {
3338
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;
4048
4149 @Override
4250 public void onTestContextInitialized() {
4351 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);
4967 }
5068
51- @BeforeMethod(groups = "short")
69+ @AfterMethod(groups = "short")
5270 public void clean() {
53- execute("TRUNCATE circles", "TRUNCATE rectangles", "TRUNCATE spheres");
71+ execute("TRUNCATE circles", "TRUNCATE rectangles", "TRUNCATE squares", "TRUNCATE spheres");
5472 }
5573
5674 @UDT(name = "point2d")
5775 static class Point2D {
5876
77+ // test mix of field and getter - getter should win
78+ @Field(name = "wrong")
5979 private int x;
6080
6181 private int y;
6282
63- public Point2D() {
83+ // test private constructor + "immutability"
84+ private Point2D() {
6485 }
6586
6687 public Point2D(int x, int y) {
@@ -68,22 +89,16 @@
6889 this.y = y;
6990 }
7091
92+ @Field(name = "X", caseSensitive = true)
7193 public int getX() {
7294 return x;
7395 }
7496
75- public void setX(int x) {
76- this.x = x;
77- }
78-
97+ @Field(name = "Y", caseSensitive = true)
7998 public int getY() {
8099 return y;
81100 }
82101
83- public void setY(int y) {
84- this.y = y;
85- }
86-
87102 @Override
88103 public boolean equals(Object o) {
89104 if (this == o) return true;
@@ -104,7 +119,8 @@
104119
105120 private int z;
106121
107- public Point3D() {
122+ // test private constructor + "immutability"
123+ private Point3D() {
108124 }
109125
110126 public Point3D(int x, int y, int z) {
@@ -112,14 +128,11 @@
112128 this.z = z;
113129 }
114130
131+ @Field(name = "Z", caseSensitive = true)
115132 public int getZ() {
116133 return z;
117134 }
118135
119- public void setZ(int z) {
120- this.z = z;
121- }
122-
123136 @Override
124137 public boolean equals(Object o) {
125138 if (this == o) return true;
@@ -135,23 +148,46 @@
135148 }
136149 }
137150
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 {
139168
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;
142173
143174 public Shape() {
144175 this.id = UUID.randomUUID();
176+ this.tags = Sets.newHashSet("cool", "awesome");
145177 }
146178
147- public UUID getId() {
148- return id;
149- }
179+ @Column(name = "wrong") // gets overridden in all subclasses
180+ public abstract UUID getId();
150181
151182 public void setId(UUID id) {
152183 this.id = id;
153184 }
154185
186+ @Override
187+ public Set<String> getTags() {
188+ return tags;
189+ }
190+
155191 @Override
156192 public boolean equals(Object o) {
157193 if (this == o) return true;
@@ -169,16 +205,30 @@
169205 @Table(name = "circles")
170206 static class Circle extends Shape {
171207
208+ @Column(name = "center2d") // overridden by a getter in Sphere
209+ @Frozen
172210 private Point2D center;
173211
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;
175219
176220 public Circle() {
177221 }
178222
179223 public Circle(Point2D center, double radius) {
180224 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;
182232 }
183233
184234 public Point2D getCenter() {
@@ -190,11 +240,28 @@
190240 }
191241
192242 public double getRadius() {
193- return radius;
243+ return _radius;
194244 }
195245
196246 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;
198265 }
199266
200267 @Override
@@ -216,10 +283,8 @@
216283 @Table(name = "rectangles")
217284 static class Rectangle extends Shape {
218285
219- @Column(name = "bottom_left")
220286 private Point2D bottomLeft;
221287
222- @Column(name = "top_right")
223288 private Point2D topRight;
224289
225290 public Rectangle() {
@@ -230,6 +295,14 @@
230295 this.topRight = topRight;
231296 }
232297
298+ @Column(name = "rect_id")
299+ @Override
300+ public UUID getId() {
301+ return id;
302+ }
303+
304+ @Column(name = "bottom_left")
305+ @Frozen
233306 public Point2D getBottomLeft() {
234307 return bottomLeft;
235308 }
@@ -238,6 +311,8 @@
238311 this.bottomLeft = bottomLeft;
239312 }
240313
314+ @Column(name = "top_right")
315+ @Frozen
241316 public Point2D getTopRight() {
242317 return topRight;
243318 }
@@ -246,6 +321,23 @@
246321 this.topRight = topRight;
247322 }
248323
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+
249341 @Override
250342 public boolean equals(Object o) {
251343 if (this == o) return true;
@@ -262,11 +354,56 @@
262354 }
263355 }
264356
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+
265398 @Table(name = "spheres")
266- static class Sphere extends Circle {
399+ static class Sphere extends Circle implements Shape3D {
267400
401+ // masks field Circle.center
402+ @Frozen
268403 private Point3D center;
269404
405+ private long writeTime;
406+
270407 public Sphere() {
271408 }
272409
@@ -274,6 +411,16 @@
274411 this.center = center;
275412 }
276413
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
277424 @Override
278425 public Point3D getCenter() {
279426 return center;
@@ -296,14 +443,14 @@
296443 public int hashCode() {
297444 return Objects.hashCode(super.hashCode(), getCenter());
298445 }
299- }
300446
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+
307454 }
308455
309456 @Test(groups = "short")
@@ -318,6 +465,12 @@
318465 assertThat(rectangleMapper.get(rectangle.getId())).isEqualTo(rectangle);
319466 }
320467
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+
321474 @Test(groups = "short")
322475 public void should_save_and_retrieve_sphere() throws Exception {
323476 sphereMapper.save(sphere);
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperTest.java +1 −2
@@ -36,7 +36,7 @@
3636 /**
3737 * Basic tests for the mapping module.
3838 */
39-@SuppressWarnings("unused")
39+@SuppressWarnings({"unused", "WeakerAccess"})
4040 public class MapperTest extends CCMTestsSupport {
4141
4242 @Override
@@ -58,7 +58,6 @@
5858 *
5959 * And the next step will be to support UDT (which should be relatively simple).
6060 */
61- @SuppressWarnings("unused")
6261 @Table(name = "users",
6362 readConsistency = "QUORUM",
6463 writeConsistency = "QUORUM")
modified manual/object_mapper/creating/README.md +226 −18
@@ -39,20 +39,76 @@
3939 save, or delete operation in the mapper. (if unspecified, it defaults
4040 to the cluster-wide setting)
4141
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.
45100
46101 [table]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Table.html
47102 [case-sensitive]:http://docs.datastax.com/en/cql/3.3/cql/cql_reference/ucase-lcase_r.html
48103 [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
49105
50106 #### Column names
51107
52108 By default, the mapper tries to map each Java property to a
53109 case insensitive column of the same name. If you want to use a different
54110 name, or [case-sensitive] names, use the [@Column][column] annotation on
55-the field.
111+the property.
56112
57113 [column]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Column.html
58114
@@ -84,8 +140,8 @@
84140
85141 #### Computed fields
86142
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
89145 functions in Cassandra like `writetime()` or [User Defined Functions] are
90146 supported.
91147
@@ -94,7 +150,7 @@
94150 Integer ttl;
95151 ```
96152
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,
98154 otherwise an exception will be thrown.
99155
100156 Computed fields are ignored when saving an entity.
@@ -108,18 +164,19 @@
108164 int f;
109165 ```
110166
111-Finally, computed fields are only supported with [basic read
167+Finally, computed properties are only supported with [basic read
112168 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
114170 version (see
115171 [JAVA-832](https://datastax-oss.atlassian.net/browse/JAVA-832)).
116172
117173 [User Defined Functions]:http://www.planetcassandra.org/blog/user-defined-functions-in-cassandra-3-0/
118174 [computed]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Computed.html
119175
120-#### Transient fields
176+#### Transient properties
121177
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.
123180
124181 [transient]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Transient.html
125182
@@ -148,12 +205,12 @@
148205 - `caseSensitiveKeyspace`: whether the keyspace name is case-sensitive.
149206 - `caseSensitiveType`: whether the UDT name is case-sensitive.
150207
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).
154209
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,
157214 use the [@Field][field] annotation:
158215
159216 ```java
@@ -178,8 +235,8 @@
178235 }
179236 ```
180237
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.
183240
184241 [User Defined Types]: ../../udts/
185242 [udt]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/UDT.html
@@ -222,3 +279,154 @@
222279 [frozen]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Frozen.html
223280 [frozenkey]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/FrozenKey.html
224281 [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+