Elffuss BraidHub

kikocis/java-driver public

JAVA-541 + JAVA-636 + JAVA-984: Polymorphism support to object mapper (#686)

* JAVA-541: Add polymorphism support to object mapper.

* 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.

* Refactor QueryType.

* Add tests for error messages.

* Reject unreadable or unwritable properties.

* Minor enhancements.

* Explicitly test if objects are accessible through reflection.

* Enhancements to documentation.

* Add tests for case-sensitivity in the mapper.

* Add explicit cast to avoid ambiguous varargs warning.

* JAVA-984: Allow non-void setters in object mapping.

* Minor doc enhancements.

* Clarify meaning of fields in AnnotationParser.

* Throw IllegalArgumentException consistently

This commit changes all places where an IllegalStateException was
thrown to throw an IllegalArgumentException instead.

* Fix failing test under JDK 7

The test "should_save_and_retrieve_sphere" was failing because
it relied on a setter declared in Sphere that overloads a setter
declared in Circle. JDK 7 fails to detect the overloading setter.

This fix simply modifies the test to avoid this edge case.

* Use a different MappingManager for each test

* Version restrict tests and add documentation

Also reorganized renamed some tests in MapperInvalidAnnotationTests for
consistency.
Changeset62c2dfe00652c1df897e2af4f7f901b5a6e28b710c7aacb4a36e7d0f5104e491
AuthorAlexandre Dutra <adutra@users.noreply.github.com> · 2016-07-22 18:52 +02:00
CommitterOlivier Michallat <olim7t@users.noreply.github.com> · 2016-07-22 09:52 -07:00
Parents4c920eab788b

Browse the files at this changeset

37 files changed

modified changelog/README.md +3 −0
@@ -10,6 +10,9 @@
1010 - [new feature] JAVA-1157: Allow asynchronous paging of Mapper Result.
1111 - [improvement] JAVA-1212: Don't retry non-idempotent statements by default.
1212 - [improvement] JAVA-1192: Make EventDebouncer settings updatable at runtime.
13+- [new feature] JAVA-541: Add polymorphism support to object mapper.
14+- [new feature] JAVA-636: Allow @Column annotations on getters/setters as well as fields.
15+- [new feature] JAVA-984: Allow non-void setters in object mapping.
1316
1417 Merged from 3.0.x branch:
1518
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 +45 −25
@@ -15,11 +15,15 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18+import com.datastax.driver.mapping.annotations.Column;
1819 import com.datastax.driver.mapping.annotations.Computed;
1920 import com.datastax.driver.mapping.annotations.Table;
2021
2122 import java.lang.annotation.Annotation;
22-import java.lang.reflect.Field;
23+import java.util.Collection;
24+import java.util.Collections;
25+import java.util.HashSet;
26+import java.util.List;
2327
2428 /**
2529 * Various checks on mapping annotations.
@@ -36,8 +40,8 @@
3640 static <T extends Annotation> T getTypeAnnotation(Class<T> annotation, Class<?> annotatedClass) {
3741 T instance = annotatedClass.getAnnotation(annotation);
3842 if (instance == null)
39- throw new IllegalArgumentException(String.format("@%s annotation was not found on type %s",
40- annotation.getSimpleName(), annotatedClass.getName()));
43+ throw new IllegalArgumentException(String.format("@%s annotation was not found on %s",
44+ annotation.getSimpleName(), annotatedClass));
4145
4246 // Check that no other mapping annotations are present
4347 validateAnnotations(annotatedClass, annotation);
@@ -45,50 +49,66 @@
4549 return instance;
4650 }
4751
52+ @SuppressWarnings("unchecked")
4853 private static void validateAnnotations(Class<?> clazz, Class<? extends Annotation> allowed) {
4954 @SuppressWarnings("unchecked")
50- Class<? extends Annotation> invalid = validateAnnotations(clazz.getAnnotations(), allowed);
55+ Collection<Annotation> classAnnotations = new HashSet<Annotation>();
56+ Collections.addAll(classAnnotations, clazz.getAnnotations());
57+ Class<? extends Annotation> invalid = validateAnnotations(classAnnotations, Collections.singleton(allowed));
5158 if (invalid != null)
52- throw new IllegalArgumentException(String.format("Cannot have both @%s and @%s on type %s",
59+ throw new IllegalArgumentException(String.format("Cannot have both @%s and @%s on %s",
5360 allowed.getSimpleName(), invalid.getSimpleName(),
54- clazz.getName()));
61+ clazz));
5562 }
5663
5764 /**
5865 * Checks that a field is only annotated with the given mapping annotations, and that its "frozen" annotations are valid.
5966 */
60- static void validateAnnotations(Field field, String classDescription, Class<? extends Annotation>... allowed) {
61- Class<? extends Annotation> invalid = validateAnnotations(field.getAnnotations(), allowed);
62- if (invalid != null)
63- throw new IllegalArgumentException(String.format("Annotation @%s is not allowed on field %s of %s %s",
67+ static void validateAnnotations(PropertyMapper property, Collection<? extends Class<? extends Annotation>> allowed) {
68+ Class<? extends Annotation> invalid = validateAnnotations(property.getAnnotations(), allowed);
69+ if (invalid != null) {
70+ throw new IllegalArgumentException(String.format("Annotation @%s is not allowed on property '%s'",
6471 invalid.getSimpleName(),
65- field.getName(), classDescription,
66- field.getDeclaringClass().getName()));
67-
68- checkValidComputed(field);
72+ property));
73+ }
74+ checkValidPrimaryKey(property);
75+ checkValidComputed(property);
6976 }
7077
7178 // Returns the offending annotation if there is one
72- private static Class<? extends Annotation> validateAnnotations(Annotation[] annotations, Class<? extends Annotation>... allowed) {
79+ private static Class<? extends Annotation> validateAnnotations(Collection<Annotation> annotations, Collection<? extends Class<? extends Annotation>> allowed) {
7380 for (Annotation annotation : annotations) {
7481 Class<? extends Annotation> actual = annotation.annotationType();
75- if (actual.getPackage().equals(MAPPING_PACKAGE) && !contains(allowed, actual))
82+ if (actual.getPackage().equals(MAPPING_PACKAGE) && !allowed.contains(actual))
7683 return actual;
7784 }
7885 return null;
7986 }
8087
81- private static boolean contains(Object[] array, Object target) {
82- for (Object element : array)
83- if (element.equals(target))
84- return true;
85- return false;
88+ private static void checkValidPrimaryKey(PropertyMapper property) {
89+ if (property.isPartitionKey() && property.isClusteringColumn())
90+ throw new IllegalArgumentException(String.format("Property '%s' cannot be annotated with both @PartitionKey and @ClusteringColumn", property));
91+ }
92+
93+ private static void checkValidComputed(PropertyMapper property) {
94+ if (property.isComputed()) {
95+ Computed computed = property.annotation(Computed.class);
96+ if (computed.value().isEmpty()) {
97+ throw new IllegalArgumentException(String.format("Property '%s': attribute 'value' of annotation @Computed is mandatory for computed properties", property));
98+ }
99+ if (property.hasAnnotation(Column.class)) {
100+ throw new IllegalArgumentException(String.format("Property '%s' cannot be annotated with both @Column and @Computed", property));
101+ }
102+ }
86103 }
87104
88- static void checkValidComputed(Field field) {
89- Computed computed = field.getAnnotation(Computed.class);
90- if (computed != null && computed.value().isEmpty()) {
91- throw new IllegalArgumentException(String.format("Field %s: attribute 'value' of annotation @Computed is mandatory for computed fields", field.getName()));
105+ static void validateOrder(List<PropertyMapper> properties, String annotation) {
106+ for (int i = 0; i < properties.size(); i++) {
107+ PropertyMapper property = properties.get(i);
108+ int pos = property.position;
109+ if (pos != i)
110+ throw new IllegalArgumentException(String.format("Invalid ordering value %d for annotation %s of property '%s', was expecting %d",
111+ pos, annotation, property, i));
92112 }
93113 }
94114 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/AnnotationParser.java +114 −208
@@ -16,286 +16,193 @@
1616 package com.datastax.driver.mapping;
1717
1818 import com.datastax.driver.core.ConsistencyLevel;
19+import com.datastax.driver.core.Metadata;
1920 import com.datastax.driver.core.TableMetadata;
2021 import com.datastax.driver.core.TypeCodec;
2122 import com.datastax.driver.core.UserType;
2223 import com.datastax.driver.mapping.MethodMapper.ParamMapper;
2324 import com.datastax.driver.mapping.annotations.*;
2425 import com.google.common.base.Strings;
25-import com.google.common.collect.Maps;
26+import com.google.common.collect.ImmutableSet;
2627 import com.google.common.reflect.TypeToken;
2728
29+import java.beans.PropertyDescriptor;
2830 import java.lang.annotation.Annotation;
29-import java.lang.reflect.Field;
30-import java.lang.reflect.*;
31+import java.lang.reflect.Method;
32+import java.lang.reflect.ParameterizedType;
33+import java.lang.reflect.Type;
3134 import java.util.*;
3235 import java.util.concurrent.atomic.AtomicInteger;
3336
34-import static com.datastax.driver.core.Metadata.quote;
35-
3637 /**
37- * Static metods 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.
3842 */
43+@SuppressWarnings({"unchecked", "WeakerAccess"})
3944 class AnnotationParser {
4045
41- private static final Comparator<Field> fieldComparator = new Comparator<Field>() {
46+ /**
47+ * Annotations allowed on a property that maps to a table column.
48+ */
49+ private static final Set<Class<? extends Annotation>> VALID_COLUMN_ANNOTATIONS = ImmutableSet.of(
50+ Column.class,
51+ Computed.class,
52+ ClusteringColumn.class,
53+ Frozen.class,
54+ FrozenKey.class,
55+ FrozenValue.class,
56+ PartitionKey.class,
57+ Transient.class);
58+
59+ /**
60+ * Annotations allowed on a property that maps to a UDT field.
61+ */
62+ private static final Set<Class<? extends Annotation>> VALID_FIELD_ANNOTATIONS = ImmutableSet.of(
63+ Field.class,
64+ Frozen.class,
65+ FrozenKey.class,
66+ FrozenValue.class,
67+ Transient.class);
68+
69+ private static final Comparator<PropertyMapper> POSITION_COMPARATOR = new Comparator<PropertyMapper>() {
4270 @Override
43- public int compare(Field f1, Field f2) {
44- return position(f1) - position(f2);
71+ public int compare(PropertyMapper o1, PropertyMapper o2) {
72+ return o1.position - o2.position;
4573 }
4674 };
4775
4876 private AnnotationParser() {
4977 }
5078
51- public static <T> EntityMapper<T> parseEntity(Class<T> entityClass, EntityMapper.Factory factory, MappingManager mappingManager) {
79+ static <T> EntityMapper<T> parseEntity(final Class<T> entityClass, MappingManager mappingManager) {
5280 Table table = AnnotationChecks.getTypeAnnotation(Table.class, entityClass);
5381
54- String ksName = table.caseSensitiveKeyspace() ? table.keyspace() : table.keyspace().toLowerCase();
55- String tableName = table.caseSensitiveTable() ? table.name() : table.name().toLowerCase();
82+ String ksName = table.caseSensitiveKeyspace() ? Metadata.quote(table.keyspace()) : table.keyspace().toLowerCase();
83+ String tableName = table.caseSensitiveTable() ? Metadata.quote(table.name()) : table.name().toLowerCase();
5684
5785 ConsistencyLevel writeConsistency = table.writeConsistency().isEmpty() ? null : ConsistencyLevel.valueOf(table.writeConsistency().toUpperCase());
5886 ConsistencyLevel readConsistency = table.readConsistency().isEmpty() ? null : ConsistencyLevel.valueOf(table.readConsistency().toUpperCase());
5987
6088 if (Strings.isNullOrEmpty(table.keyspace())) {
61- ksName = mappingManager.getSession().getLoggedKeyspace();
62- if (Strings.isNullOrEmpty(ksName))
89+ String loggedKeyspace = mappingManager.getSession().getLoggedKeyspace();
90+ if (Strings.isNullOrEmpty(loggedKeyspace))
6391 throw new IllegalArgumentException(String.format(
64- "Error creating mapper for class %s, the @%s annotation declares no default keyspace, and the session is not currently logged to any keyspace",
65- entityClass.getSimpleName(),
66- Table.class.getSimpleName()
92+ "Error creating mapper for %s, the @Table annotation declares no default keyspace, and the session is not currently logged to any keyspace",
93+ entityClass
6794 ));
95+ ksName = Metadata.quote(loggedKeyspace);
6896 }
6997
70- EntityMapper<T> mapper = factory.create(entityClass, ksName, tableName, writeConsistency, readConsistency);
98+ EntityMapper<T> mapper = new EntityMapper<T>(entityClass, ksName, tableName, writeConsistency, readConsistency);
7199 TableMetadata tableMetadata = mappingManager.getSession().getCluster().getMetadata().getKeyspace(ksName).getTable(tableName);
72100
73101 if (tableMetadata == null)
74102 throw new IllegalArgumentException(String.format("Table %s does not exist in keyspace %s", tableName, ksName));
75103
76- List<Field> pks = new ArrayList<Field>();
77- List<Field> ccs = new ArrayList<Field>();
78- List<Field> rgs = new ArrayList<Field>();
104+ List<PropertyMapper> pks = new ArrayList<PropertyMapper>();
105+ List<PropertyMapper> ccs = new ArrayList<PropertyMapper>();
106+ List<PropertyMapper> rgs = new ArrayList<PropertyMapper>();
79107
80- for (Field field : entityClass.getDeclaredFields()) {
81- if (field.isSynthetic() || (field.getModifiers() & Modifier.STATIC) == Modifier.STATIC)
82- continue;
108+ Map<String, Object[]> fieldsAndProperties = ReflectionUtils.scanFieldsAndProperties(entityClass);
109+ AtomicInteger columnCounter = mappingManager.isCassandraV1 ? null : new AtomicInteger(0);
110+
111+ for (Map.Entry<String, Object[]> entry : fieldsAndProperties.entrySet()) {
112+
113+ String propertyName = entry.getKey();
114+ java.lang.reflect.Field field = (java.lang.reflect.Field) entry.getValue()[0];
115+ PropertyDescriptor property = (PropertyDescriptor) entry.getValue()[1];
116+ String alias = (columnCounter != null)
117+ ? "col" + columnCounter.incrementAndGet()
118+ : null;
119+
120+ PropertyMapper propertyMapper = new PropertyMapper(entityClass, propertyName, alias, field, property);
83121
84- if (mappingManager.isCassandraV1 && field.getAnnotation(Computed.class) != null)
85- throw new UnsupportedOperationException("Computed fields are not supported with native protocol v1");
122+ if (mappingManager.isCassandraV1 && propertyMapper.isComputed())
123+ throw new UnsupportedOperationException("Computed properties are not supported with native protocol v1");
86124
87- AnnotationChecks.validateAnnotations(field, "entity",
88- Column.class, ClusteringColumn.class, Frozen.class, FrozenKey.class,
89- FrozenValue.class, PartitionKey.class, Transient.class, Computed.class);
125+ AnnotationChecks.validateAnnotations(propertyMapper, VALID_COLUMN_ANNOTATIONS);
90126
91- if (field.getAnnotation(Transient.class) != null)
127+ if (propertyMapper.isTransient())
92128 continue;
93129
94- switch (kind(field)) {
95- case PARTITION_KEY:
96- pks.add(field);
97- break;
98- case CLUSTERING_COLUMN:
99- ccs.add(field);
100- break;
101- default:
102- rgs.add(field);
103- break;
104- }
105- }
130+ if (!propertyMapper.isComputed() && tableMetadata.getColumn(propertyMapper.columnName) == null)
131+ throw new IllegalArgumentException(String.format("Column %s does not exist in table %s.%s",
132+ propertyMapper.columnName, ksName, tableName));
133+
134+ if (propertyMapper.isPartitionKey())
135+ pks.add(propertyMapper);
136+ else if (propertyMapper.isClusteringColumn())
137+ ccs.add(propertyMapper);
138+ else
139+ rgs.add(propertyMapper);
106140
107- AtomicInteger columnCounter = mappingManager.isCassandraV1 ? null : new AtomicInteger(0);
141+ // if the property is of a UDT type, parse it now
142+ for (Class<?> udt : TypeMappings.findUDTs(propertyMapper.javaType.getType()))
143+ mappingManager.getUDTCodec(udt);
144+ }
108145
109- Collections.sort(pks, fieldComparator);
110- Collections.sort(ccs, fieldComparator);
146+ Collections.sort(pks, POSITION_COMPARATOR);
147+ Collections.sort(ccs, POSITION_COMPARATOR);
111148
112- validateOrder(pks, "@PartitionKey");
113- validateOrder(ccs, "@ClusteringColumn");
149+ AnnotationChecks.validateOrder(pks, "@PartitionKey");
150+ AnnotationChecks.validateOrder(ccs, "@ClusteringColumn");
114151
115- mapper.addColumns(
116- createColumnMappers(pks, factory, mapper.entityClass, mappingManager, columnCounter, tableMetadata, ksName, tableName),
117- createColumnMappers(ccs, factory, mapper.entityClass, mappingManager, columnCounter, tableMetadata, ksName, tableName),
118- createColumnMappers(rgs, factory, mapper.entityClass, mappingManager, columnCounter, tableMetadata, ksName, tableName));
152+ mapper.addColumns(pks, ccs, rgs);
119153 return mapper;
120154 }
121155
122- private static <T> List<ColumnMapper<T>> createColumnMappers(List<Field> fields, EntityMapper.Factory factory, Class<T> klass, MappingManager mappingManager, AtomicInteger columnCounter, TableMetadata tableMetadata, String ksName, String tableName) {
123- List<ColumnMapper<T>> mappers = new ArrayList<ColumnMapper<T>>(fields.size());
124- for (int i = 0; i < fields.size(); i++) {
125- Field field = fields.get(i);
126- int pos = position(field);
127- ColumnMapper<T> columnMapper = factory.createColumnMapper(klass, field, pos < 0 ? i : pos, mappingManager, columnCounter);
128- if (columnMapper.kind == ColumnMapper.Kind.COMPUTED || tableMetadata.getColumn(columnMapper.getColumnName()) != null)
129- mappers.add(columnMapper);
130- else
131- throw new IllegalArgumentException(String.format("Column %s does not exist in table %s.%s",
132- columnMapper.getColumnName(), ksName, tableName));
133- }
134- return mappers;
135- }
136-
137- public static <T> MappedUDTCodec<T> parseUDT(Class<T> udtClass, EntityMapper.Factory factory, MappingManager mappingManager) {
156+ static <T> MappedUDTCodec<T> parseUDT(Class<T> udtClass, MappingManager mappingManager) {
138157 UDT udt = AnnotationChecks.getTypeAnnotation(UDT.class, udtClass);
139158
140- String ksName = udt.caseSensitiveKeyspace() ? udt.keyspace() : udt.keyspace().toLowerCase();
141- String udtName = udt.caseSensitiveType() ? quote(udt.name()) : udt.name().toLowerCase();
159+ String ksName = udt.caseSensitiveKeyspace() ? Metadata.quote(udt.keyspace()) : udt.keyspace().toLowerCase();
160+ String udtName = udt.caseSensitiveType() ? Metadata.quote(udt.name()) : udt.name().toLowerCase();
142161
143162 if (Strings.isNullOrEmpty(udt.keyspace())) {
144- ksName = mappingManager.getSession().getLoggedKeyspace();
145- if (Strings.isNullOrEmpty(ksName))
163+ String loggedKeyspace = mappingManager.getSession().getLoggedKeyspace();
164+ if (Strings.isNullOrEmpty(loggedKeyspace))
146165 throw new IllegalArgumentException(String.format(
147- "Error creating UDT codec for class %s, the @%s annotation declares no default keyspace, and the session is not currently logged to any keyspace",
148- udtClass.getSimpleName(),
149- UDT.class.getSimpleName()
166+ "Error creating UDT codec for %s, the @UDT annotation declares no default keyspace, and the session is not currently logged to any keyspace",
167+ udtClass
150168 ));
169+ ksName = Metadata.quote(loggedKeyspace);
151170 }
152171
153172 UserType userType = mappingManager.getSession().getCluster().getMetadata().getKeyspace(ksName).getUserType(udtName);
154173 if (userType == null)
155174 throw new IllegalArgumentException(String.format("User type %s does not exist in keyspace %s", udtName, ksName));
156175
157- List<Field> columns = new ArrayList<Field>();
158-
159- for (Field field : udtClass.getDeclaredFields()) {
160- if (field.isSynthetic() || (field.getModifiers() & Modifier.STATIC) == Modifier.STATIC)
161- continue;
162-
163- AnnotationChecks.validateAnnotations(field, "UDT",
164- com.datastax.driver.mapping.annotations.Field.class, Frozen.class, FrozenKey.class,
165- FrozenValue.class, Transient.class);
166-
167- if (field.getAnnotation(Transient.class) != null)
168- continue;
169-
170- switch (kind(field)) {
171- case PARTITION_KEY:
172- throw new IllegalArgumentException("Annotation @PartitionKey is not allowed in a class annotated by @UDT");
173- case CLUSTERING_COLUMN:
174- throw new IllegalArgumentException("Annotation @ClusteringColumn is not allowed in a class annotated by @UDT");
175- default:
176- columns.add(field);
177- break;
178- }
179- }
180- Map<String, ColumnMapper<T>> columnMappers = createFieldMappers(columns, factory, udtClass, mappingManager, userType, ksName);
181- return new MappedUDTCodec<T>(userType, udtClass, columnMappers, mappingManager);
182- }
183-
184- private static <T> Map<String, ColumnMapper<T>> createFieldMappers(List<Field> fields, EntityMapper.Factory factory, Class<T> klass, MappingManager mappingManager, UserType userType, String ksName) {
185- Map<String, ColumnMapper<T>> mappers = Maps.newHashMapWithExpectedSize(fields.size());
186- for (int i = 0; i < fields.size(); i++) {
187- Field field = fields.get(i);
188- int pos = position(field);
189- ColumnMapper<T> mapper = factory.createColumnMapper(klass, field, pos < 0 ? i : pos, mappingManager, null);
190- if (userType.contains(mapper.getColumnName()))
191- mappers.put(mapper.getColumnName(), mapper);
192- else
193- throw new IllegalArgumentException(String.format("Field %s does not exist in type %s.%s",
194- mapper.getColumnName(), ksName, userType.getTypeName()));
195- }
196- return mappers;
197- }
198-
199- private static void validateOrder(List<Field> fields, String annotation) {
200- for (int i = 0; i < fields.size(); i++) {
201- Field field = fields.get(i);
202- int pos = position(field);
203- if (pos != i)
204- throw new IllegalArgumentException(String.format("Invalid ordering value %d for annotation %s of column %s, was expecting %d",
205- pos, annotation, field.getName(), i));
206- }
207- }
208-
209- private static int position(Field field) {
210- switch (kind(field)) {
211- case PARTITION_KEY:
212- return field.getAnnotation(PartitionKey.class).value();
213- case CLUSTERING_COLUMN:
214- return field.getAnnotation(ClusteringColumn.class).value();
215- default:
216- return -1;
217- }
218- }
176+ Map<String, PropertyMapper> propertyMappers = new HashMap<String, PropertyMapper>();
219177
220- public static ColumnMapper.Kind kind(Field field) {
221- PartitionKey pk = field.getAnnotation(PartitionKey.class);
222- ClusteringColumn cc = field.getAnnotation(ClusteringColumn.class);
223- Computed comp = field.getAnnotation(Computed.class);
224- if (pk != null && cc != null)
225- throw new IllegalArgumentException("Field " + field.getName() + " cannot have both the @PartitionKey and @ClusteringColumn annotations");
226-
227- if (pk != null) {
228- return ColumnMapper.Kind.PARTITION_KEY;
229- }
230- if (cc != null) {
231- return ColumnMapper.Kind.CLUSTERING_COLUMN;
232- }
233- if (comp != null) {
234- return ColumnMapper.Kind.COMPUTED;
235- }
236- return ColumnMapper.Kind.REGULAR;
237- }
178+ Map<String, Object[]> fieldsAndProperties = ReflectionUtils.scanFieldsAndProperties(udtClass);
238179
239- public static String columnName(Field field) {
240- Column column = field.getAnnotation(Column.class);
241- Computed computedField = field.getAnnotation(Computed.class);
242- if (column != null && !column.name().isEmpty()) {
243- if (computedField != null) {
244- throw new IllegalArgumentException("Cannot use @Column and @Computed on the same field");
245- }
246- return column.caseSensitive() ? column.name() : column.name().toLowerCase();
247- }
180+ for (Map.Entry<String, Object[]> entry : fieldsAndProperties.entrySet()) {
248181
249- com.datastax.driver.mapping.annotations.Field udtField = field.getAnnotation(com.datastax.driver.mapping.annotations.Field.class);
250- if (udtField != null && !udtField.name().isEmpty()) {
251- return udtField.caseSensitive() ? udtField.name() : udtField.name().toLowerCase();
252- }
182+ String propertyName = entry.getKey();
183+ java.lang.reflect.Field field = (java.lang.reflect.Field) entry.getValue()[0];
184+ PropertyDescriptor property = (PropertyDescriptor) entry.getValue()[1];
253185
254- if (computedField != null) {
255- return computedField.value();
256- }
186+ PropertyMapper propertyMapper = new PropertyMapper(udtClass, propertyName, null, field, property);
257187
258- return field.getName().toLowerCase();
259- }
188+ AnnotationChecks.validateAnnotations(propertyMapper, VALID_FIELD_ANNOTATIONS);
260189
261- public static String newAlias(Field field, int columnNumber) {
262- return "col" + columnNumber;
190+ if (propertyMapper.isTransient())
191+ continue;
263192
264- }
193+ if (!userType.contains(propertyMapper.columnName))
194+ throw new IllegalArgumentException(String.format("Field %s does not exist in type %s.%s",
195+ propertyMapper.columnName, ksName, userType.getTypeName()));
265196
266- public static TypeCodec<Object> customCodec(Field field) {
267- Class<? extends TypeCodec<?>> codecClass = getCodecClass(field);
268-
269- if (codecClass.equals(Defaults.NoCodec.class))
270- return null;
271-
272- try {
273- @SuppressWarnings("unchecked")
274- TypeCodec<Object> instance = (TypeCodec<Object>) codecClass.newInstance();
275- return instance;
276- } catch (Exception e) {
277- throw new IllegalArgumentException(String.format(
278- "Cannot create an instance of custom codec %s for field %s",
279- codecClass, field
280- ), e);
197+ propertyMappers.put(propertyMapper.columnName, propertyMapper);
281198 }
282- }
283-
284- private static Class<? extends TypeCodec<?>> getCodecClass(Field field) {
285- Column column = field.getAnnotation(Column.class);
286- if (column != null)
287- return column.codec();
288-
289- com.datastax.driver.mapping.annotations.Field udtField = field.getAnnotation(com.datastax.driver.mapping.annotations.Field.class);
290- if (udtField != null)
291- return udtField.codec();
292199
293- return Defaults.NoCodec.class;
200+ return new MappedUDTCodec<T>(userType, udtClass, propertyMappers, mappingManager);
294201 }
295202
296- public static <T> AccessorMapper<T> parseAccessor(Class<T> accClass, AccessorMapper.Factory factory, MappingManager mappingManager) {
203+ static <T> AccessorMapper<T> parseAccessor(Class<T> accClass, MappingManager mappingManager) {
297204 if (!accClass.isInterface())
298- throw new IllegalArgumentException("@Accessor annotation is only allowed on interfaces");
205+ throw new IllegalArgumentException("@Accessor annotation is only allowed on interfaces, got " + accClass);
299206
300207 AnnotationChecks.getTypeAnnotation(Accessor.class, accClass);
301208
@@ -332,7 +239,7 @@
332239 else if (allParamsNamed != thisParamNamed)
333240 throw new IllegalArgumentException(String.format("For method '%s', either all or none of the parameters must be named", m.getName()));
334241
335- paramMappers[i] = newParamMapper(accClass.getName(), m.getName(), i, paramName, codecClass, paramTypes[i], paramAnnotations[i], mappingManager);
242+ paramMappers[i] = newParamMapper(accClass.getName(), m.getName(), i, paramName, codecClass, paramTypes[i], mappingManager);
336243 }
337244
338245 ConsistencyLevel cl = null;
@@ -346,7 +253,7 @@
346253 fetchSize = options.fetchSize();
347254 tracing = options.tracing();
348255 if (options.idempotent().length > 1) {
349- throw new IllegalStateException("idemtpotence() attribute can only accept one value");
256+ throw new IllegalArgumentException("idemtpotence() attribute can only accept one value");
350257 }
351258 idempotent = options.idempotent().length == 0 ? null : options.idempotent()[0];
352259 }
@@ -354,11 +261,10 @@
354261 methods.add(new MethodMapper(m, queryString, paramMappers, cl, fetchSize, tracing, idempotent));
355262 }
356263
357- return factory.create(accClass, methods);
264+ return new AccessorMapper<T>(accClass, methods);
358265 }
359266
360- @SuppressWarnings({"unchecked", "rawtypes"})
361- private static ParamMapper newParamMapper(String className, String methodName, int idx, String paramName, Class<? extends TypeCodec<?>> codecClass, Type paramType, Annotation[] paramAnnotations, MappingManager mappingManager) {
267+ private static ParamMapper newParamMapper(String className, String methodName, int idx, String paramName, Class<? extends TypeCodec<?>> codecClass, Type paramType, MappingManager mappingManager) {
362268 if (paramType instanceof Class) {
363269 Class<?> paramClass = (Class<?>) paramType;
364270 if (TypeMappings.isMappedUDT(paramClass))
deleted driver-mapping/src/main/java/com/datastax/driver/mapping/ColumnMapper.java +0 −77
@@ -1,77 +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.google.common.reflect.TypeToken;
21-
22-import java.lang.reflect.Field;
23-import java.util.concurrent.atomic.AtomicInteger;
24-
25-abstract class ColumnMapper<T> {
26-
27- enum Kind {PARTITION_KEY, CLUSTERING_COLUMN, REGULAR, COMPUTED}
28-
29- private final String columnName;
30- private final String alias;
31- protected final String fieldName;
32- /**
33- * The type of the Java field in the mapped class
34- */
35- protected final TypeToken<Object> fieldType;
36- protected final Kind kind;
37- protected final int position;
38- protected final TypeCodec<Object> customCodec;
39-
40- @SuppressWarnings("unchecked")
41- protected ColumnMapper(Field field, int position, AtomicInteger columnCounter) {
42- this.columnName = AnnotationParser.columnName(field);
43- this.alias = (columnCounter != null)
44- ? AnnotationParser.newAlias(field, columnCounter.incrementAndGet())
45- : null;
46- this.fieldName = field.getName();
47- this.fieldType = (TypeToken<Object>) TypeToken.of(field.getGenericType());
48- this.kind = AnnotationParser.kind(field);
49- this.position = position;
50- this.customCodec = AnnotationParser.customCodec(field);
51- }
52-
53- abstract Object getValue(T entity);
54-
55- abstract void setValue(T entity, Object value);
56-
57- String getColumnName() {
58- return kind == Kind.COMPUTED
59- ? columnName
60- : Metadata.quote(columnName);
61- }
62-
63- String getAlias() {
64- return alias;
65- }
66-
67- public TypeCodec<Object> getCustomCodec() {
68- return customCodec;
69- }
70-
71- /**
72- * The Java type of this column.
73- */
74- public TypeToken<Object> getJavaType() {
75- return fieldType;
76- }
77-}
modified driver-mapping/src/main/java/com/datastax/driver/mapping/EntityMapper.java +13 −40
@@ -17,29 +17,24 @@
1717
1818 import com.datastax.driver.core.ConsistencyLevel;
1919
20-import java.lang.reflect.Field;
2120 import java.util.ArrayList;
2221 import java.util.List;
23-import java.util.concurrent.atomic.AtomicInteger;
2422
25-import static com.datastax.driver.core.querybuilder.QueryBuilder.quote;
23+class EntityMapper<T> {
2624
27-abstract class EntityMapper<T> {
28-
29- final Class<T> entityClass;
30- private final String keyspace;
31- private final String table;
25+ private final Class<T> entityClass;
26+ final String keyspace;
27+ final String table;
3228
3329 final ConsistencyLevel writeConsistency;
3430 final ConsistencyLevel readConsistency;
3531
36- final List<ColumnMapper<T>> partitionKeys = new ArrayList<ColumnMapper<T>>();
37- final List<ColumnMapper<T>> clusteringColumns = new ArrayList<ColumnMapper<T>>();
38- final List<ColumnMapper<T>> regularColumns = new ArrayList<ColumnMapper<T>>();
32+ final List<PropertyMapper> partitionKeys = new ArrayList<PropertyMapper>();
33+ final List<PropertyMapper> clusteringColumns = new ArrayList<PropertyMapper>();
3934
40- private final List<ColumnMapper<T>> allColumns = new ArrayList<ColumnMapper<T>>();
35+ final List<PropertyMapper> allColumns = new ArrayList<PropertyMapper>();
4136
42- protected EntityMapper(Class<T> entityClass, String keyspace, String table, ConsistencyLevel writeConsistency, ConsistencyLevel readConsistency) {
37+ EntityMapper(Class<T> entityClass, String keyspace, String table, ConsistencyLevel writeConsistency, ConsistencyLevel readConsistency) {
4338 this.entityClass = entityClass;
4439 this.keyspace = keyspace;
4540 this.table = table;
@@ -47,46 +42,24 @@
4742 this.readConsistency = readConsistency;
4843 }
4944
50- String getKeyspace() {
51- return quote(keyspace);
52- }
53-
54- String getTable() {
55- return quote(table);
56- }
57-
5845 int primaryKeySize() {
5946 return partitionKeys.size() + clusteringColumns.size();
6047 }
6148
62- ColumnMapper<T> getPrimaryKeyColumn(int i) {
49+ PropertyMapper getPrimaryKeyColumn(int i) {
6350 return i < partitionKeys.size() ? partitionKeys.get(i) : clusteringColumns.get(i - partitionKeys.size());
6451 }
6552
66- void addColumns(List<ColumnMapper<T>> pks, List<ColumnMapper<T>> ccs, List<ColumnMapper<T>> rgs) {
53+ void addColumns(List<PropertyMapper> pks, List<PropertyMapper> ccs, List<PropertyMapper> rgs) {
6754 partitionKeys.addAll(pks);
68- allColumns.addAll(pks);
69-
7055 clusteringColumns.addAll(ccs);
56+ allColumns.addAll(pks);
7157 allColumns.addAll(ccs);
72-
73- addColumns(rgs);
74- }
75-
76- void addColumns(List<ColumnMapper<T>> rgs) {
77- regularColumns.addAll(rgs);
7858 allColumns.addAll(rgs);
7959 }
8060
81- abstract T newEntity();
82-
83- List<ColumnMapper<T>> allColumns() {
84- return allColumns;
61+ T newEntity() {
62+ return ReflectionUtils.newInstance(entityClass);
8563 }
8664
87- interface Factory {
88- public <T> EntityMapper<T> create(Class<T> entityClass, String keyspace, String table, ConsistencyLevel writeConsistency, ConsistencyLevel readConsistency);
89-
90- public <T> ColumnMapper<T> createColumnMapper(Class<T> componentClass, Field field, int position, MappingManager mappingManager, AtomicInteger columnCounter);
91- }
9265 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MappedUDTCodec.java +17 −25
@@ -15,7 +15,10 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import com.datastax.driver.core.*;
18+import com.datastax.driver.core.CodecRegistry;
19+import com.datastax.driver.core.ProtocolVersion;
20+import com.datastax.driver.core.TypeCodec;
21+import com.datastax.driver.core.UserType;
1922
2023 import java.nio.ByteBuffer;
2124 import java.util.Map;
@@ -26,10 +29,10 @@
2629 class MappedUDTCodec<T> extends TypeCodec.AbstractUDTCodec<T> {
2730 private final UserType cqlUserType;
2831 private final Class<T> udtClass;
29- private final Map<String, ColumnMapper<T>> columnMappers;
32+ private final Map<String, PropertyMapper> columnMappers;
3033 private final CodecRegistry codecRegistry;
3134
32- public MappedUDTCodec(UserType cqlUserType, Class<T> udtClass, Map<String, ColumnMapper<T>> columnMappers, MappingManager mappingManager) {
35+ MappedUDTCodec(UserType cqlUserType, Class<T> udtClass, Map<String, PropertyMapper> columnMappers, MappingManager mappingManager) {
3336 super(cqlUserType, udtClass);
3437 this.cqlUserType = cqlUserType;
3538 this.udtClass = udtClass;
@@ -39,11 +42,7 @@
3942
4043 @Override
4144 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- }
45+ return ReflectionUtils.newInstance(udtClass);
4746 }
4847
4948 Class<T> getUdtClass() {
@@ -52,35 +51,28 @@
5251
5352 @Override
5453 protected ByteBuffer serializeField(T source, String fieldName, ProtocolVersion protocolVersion) {
55- // The parent class passes lowercase names unquoted, but in our internal map of mappers they are always quoted
56- if (!fieldName.startsWith("\""))
57- fieldName = Metadata.quote(fieldName);
54+ PropertyMapper propertyMapper = columnMappers.get(fieldName);
5855
59- ColumnMapper<T> columnMapper = columnMappers.get(fieldName);
60-
61- if (columnMapper == null)
56+ if (propertyMapper == null)
6257 return null;
6358
64- Object value = columnMapper.getValue(source);
59+ Object value = propertyMapper.getValue(source);
6560
66- TypeCodec<Object> codec = columnMapper.getCustomCodec();
61+ TypeCodec<Object> codec = propertyMapper.customCodec;
6762 if (codec == null)
68- codec = codecRegistry.codecFor(cqlUserType.getFieldType(columnMapper.getColumnName()), columnMapper.getJavaType());
63+ codec = codecRegistry.codecFor(cqlUserType.getFieldType(propertyMapper.columnName), propertyMapper.javaType);
6964
7065 return codec.serialize(value, protocolVersion);
7166 }
7267
7368 @Override
7469 protected T deserializeAndSetField(ByteBuffer input, T target, String fieldName, ProtocolVersion protocolVersion) {
75- if (!fieldName.startsWith("\""))
76- fieldName = Metadata.quote(fieldName);
77-
78- ColumnMapper<T> columnMapper = columnMappers.get(fieldName);
79- if (columnMapper != null) {
80- TypeCodec<Object> codec = columnMapper.getCustomCodec();
70+ PropertyMapper propertyMapper = columnMappers.get(fieldName);
71+ if (propertyMapper != null) {
72+ TypeCodec<Object> codec = propertyMapper.customCodec;
8173 if (codec == null)
82- codec = codecRegistry.codecFor(cqlUserType.getFieldType(columnMapper.getColumnName()), columnMapper.getJavaType());
83- columnMapper.setValue(target, codec.deserialize(input, protocolVersion));
74+ codec = codecRegistry.codecFor(cqlUserType.getFieldType(propertyMapper.columnName), propertyMapper.javaType);
75+ propertyMapper.setValue(target, codec.deserialize(input, protocolVersion));
8476 }
8577 return target;
8678 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/Mapper.java +27 −29
@@ -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
@@ -73,10 +72,9 @@
7372 this.klass = klass;
7473 this.mapper = mapper;
7574
76- KeyspaceMetadata keyspace = session().getCluster().getMetadata().getKeyspace(mapper.getKeyspace());
77- this.tableMetadata = keyspace == null ? null : keyspace.getTable(mapper.getTable());
75+ KeyspaceMetadata keyspace = session().getCluster().getMetadata().getKeyspace(mapper.keyspace);
76+ this.tableMetadata = keyspace == null ? null : keyspace.getTable(mapper.table);
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.kind != ColumnMapper.Kind.COMPUTED && (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 +196 −0
@@ -0,0 +1,196 @@
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+import static com.google.common.base.Preconditions.checkArgument;
32+
33+/**
34+ * Maps a Java bean property to a table column or a UDT field.
35+ * <p>
36+ * Properties can be either accessed through getter and setter pairs,
37+ * or by direct field access, depending on what is available in the
38+ * entity/UDT class.
39+ */
40+class PropertyMapper {
41+
42+ private final String propertyName;
43+ final String alias;
44+ final String columnName;
45+ final TypeToken<Object> javaType;
46+ final TypeCodec<Object> customCodec;
47+ final int position;
48+
49+ private final Field field;
50+ private final Method getter;
51+ private final Method setter;
52+ private final Map<Class<? extends Annotation>, Annotation> annotations;
53+
54+ PropertyMapper(Class<?> baseClass, String propertyName, String alias, Field field, PropertyDescriptor property) {
55+ this.propertyName = propertyName;
56+ this.alias = alias;
57+ this.field = field;
58+ getter = ReflectionUtils.findGetter(property);
59+ setter = ReflectionUtils.findSetter(baseClass, property);
60+ annotations = ReflectionUtils.scanPropertyAnnotations(field, property);
61+ if (field != null)
62+ ReflectionUtils.tryMakeAccessible(field);
63+ if (getter != null)
64+ ReflectionUtils.tryMakeAccessible(getter);
65+ if (setter != null)
66+ ReflectionUtils.tryMakeAccessible(setter);
67+ if (!isTransient()) {
68+ checkArgument((field != null && field.isAccessible()) || (getter != null && getter.isAccessible()),
69+ "Property '%s' is not readable", propertyName);
70+ checkArgument((field != null && field.isAccessible()) || (setter != null && setter.isAccessible()),
71+ "Property '%s' is not writable", propertyName);
72+ }
73+ columnName = inferColumnName();
74+ position = inferPosition();
75+ javaType = inferJavaType();
76+ customCodec = createCustomCodec();
77+ }
78+
79+ Object getValue(Object entity) {
80+ try {
81+ // try getter first, if available, otherwise direct field access
82+ if (getter != null && getter.isAccessible())
83+ return getter.invoke(entity);
84+ else
85+ return field.get(entity);
86+ } catch (Exception e) {
87+ throw new IllegalArgumentException("Unable to read property '" + propertyName + "' in " + entity.getClass(), e);
88+ }
89+ }
90+
91+ void setValue(Object entity, Object value) {
92+ try {
93+ // try setter first, if available, otherwise direct field access
94+ if (setter != null && setter.isAccessible())
95+ setter.invoke(entity, value);
96+ else
97+ field.set(entity, value);
98+ } catch (Exception e) {
99+ throw new IllegalArgumentException("Unable to write property '" + propertyName + "' in " + entity.getClass(), e);
100+ }
101+ }
102+
103+ boolean hasAnnotation(Class<? extends Annotation> annotationClass) {
104+ return annotations.containsKey(annotationClass);
105+ }
106+
107+ Collection<Annotation> getAnnotations() {
108+ return annotations.values();
109+ }
110+
111+ @SuppressWarnings("unchecked")
112+ <A extends Annotation> A annotation(Class<A> annotationClass) {
113+ return (A) annotations.get(annotationClass);
114+ }
115+
116+ boolean isComputed() {
117+ return hasAnnotation(Computed.class);
118+ }
119+
120+ boolean isTransient() {
121+ return hasAnnotation(Transient.class);
122+ }
123+
124+ boolean isPartitionKey() {
125+ return hasAnnotation(PartitionKey.class);
126+ }
127+
128+ boolean isClusteringColumn() {
129+ return hasAnnotation(ClusteringColumn.class);
130+ }
131+
132+ private String inferColumnName() {
133+ if (isComputed()) {
134+ return annotation(Computed.class).value();
135+ }
136+ boolean caseSensitive = false;
137+ String columnName = propertyName;
138+ if (hasAnnotation(Column.class)) {
139+ Column column = annotation(Column.class);
140+ caseSensitive = column.caseSensitive();
141+ if (!column.name().isEmpty())
142+ columnName = column.name();
143+ } else if (hasAnnotation(com.datastax.driver.mapping.annotations.Field.class)) {
144+ com.datastax.driver.mapping.annotations.Field udtField = annotation(com.datastax.driver.mapping.annotations.Field.class);
145+ caseSensitive = udtField.caseSensitive();
146+ if (!udtField.name().isEmpty())
147+ columnName = udtField.name();
148+ }
149+ return caseSensitive ? Metadata.quote(columnName) : columnName.toLowerCase();
150+ }
151+
152+ @SuppressWarnings("unchecked")
153+ private TypeToken<Object> inferJavaType() {
154+ Type type;
155+ if (getter != null)
156+ type = getter.getGenericReturnType();
157+ else
158+ type = field.getGenericType();
159+ return (TypeToken<Object>) TypeToken.of(type);
160+ }
161+
162+ private int inferPosition() {
163+ if (isPartitionKey()) {
164+ return annotation(PartitionKey.class).value();
165+ }
166+ if (isClusteringColumn()) {
167+ return annotation(ClusteringColumn.class).value();
168+ }
169+ return -1;
170+ }
171+
172+ private TypeCodec<Object> createCustomCodec() {
173+ Class<? extends TypeCodec<?>> codecClass = getCustomCodecClass();
174+ if (codecClass.equals(Defaults.NoCodec.class))
175+ return null;
176+ @SuppressWarnings("unchecked")
177+ TypeCodec<Object> instance = (TypeCodec<Object>) ReflectionUtils.newInstance(codecClass);
178+ return instance;
179+ }
180+
181+ private Class<? extends TypeCodec<?>> getCustomCodecClass() {
182+ Column column = annotation(Column.class);
183+ if (column != null)
184+ return column.codec();
185+ com.datastax.driver.mapping.annotations.Field udtField = annotation(com.datastax.driver.mapping.annotations.Field.class);
186+ if (udtField != null)
187+ return udtField.codec();
188+ return Defaults.NoCodec.class;
189+ }
190+
191+ @Override
192+ public String toString() {
193+ return propertyName;
194+ }
195+
196+}
modified driver-mapping/src/main/java/com/datastax/driver/mapping/QueryType.java +65 −151
@@ -19,171 +19,85 @@
1919 import com.datastax.driver.core.querybuilder.Delete;
2020 import com.datastax.driver.core.querybuilder.Insert;
2121 import com.datastax.driver.core.querybuilder.Select;
22-import com.google.common.base.Objects;
2322
24-import java.util.ArrayList;
2523 import java.util.Collection;
26-import java.util.List;
2724 import java.util.Set;
2825
2926 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
3027
31-class QueryType {
32-
33- private enum Kind {SAVE, GET, DEL, SLICE, REVERSED_SLICE}
34-
35- private final Kind kind;
36-
37- // For slices
38- private final int startBoundSize;
39- private final boolean startInclusive;
40- private final int endBoundSize;
41- private final boolean endInclusive;
42-
43- public static final QueryType SAVE = new QueryType(Kind.SAVE);
44- public static final QueryType DEL = new QueryType(Kind.DEL);
45- public static final QueryType GET = new QueryType(Kind.GET);
46-
47- private QueryType(Kind kind) {
48- this(kind, 0, false, 0, false);
49- }
50-
51- private QueryType(Kind kind, int startBoundSize, boolean startInclusive, int endBoundSize, boolean endInclusive) {
52- this.kind = kind;
53- this.startBoundSize = startBoundSize;
54- this.startInclusive = startInclusive;
55- this.endBoundSize = endBoundSize;
56- this.endInclusive = endInclusive;
57- }
58-
59- String makePreparedQueryString(TableMetadata table, EntityMapper<?> mapper, MappingManager manager, Set<ColumnMapper<?>> columns, Collection<Mapper.Option> options) {
60- switch (kind) {
61- case SAVE: {
62- Insert insert = table == null
63- ? insertInto(mapper.getKeyspace(), mapper.getTable())
64- : insertInto(table);
65- for (ColumnMapper<?> cm : columns)
66- if (cm.kind != ColumnMapper.Kind.COMPUTED)
67- insert.value(cm.getColumnName(), bindMarker());
68-
69- Insert.Options usings = insert.using();
70- for (Mapper.Option opt : options) {
71- opt.checkValidFor(QueryType.SAVE, manager);
72- if (opt.isIncludedInQuery())
73- opt.appendTo(usings);
74- }
75- return insert.toString();
28+enum QueryType {
29+
30+ SAVE {
31+ @Override
32+ String makePreparedQueryString(TableMetadata table, EntityMapper<?> mapper, MappingManager manager, Set<PropertyMapper> columns, Collection<Mapper.Option> options) {
33+ Insert insert = table == null
34+ ? insertInto(mapper.keyspace, mapper.table)
35+ : insertInto(table);
36+ for (PropertyMapper col : columns)
37+ if (!col.isComputed())
38+ insert.value(col.columnName, bindMarker());
39+
40+ Insert.Options usings = insert.using();
41+ for (Mapper.Option opt : options) {
42+ opt.checkValidFor(QueryType.SAVE, manager);
43+ if (opt.isIncludedInQuery())
44+ opt.appendTo(usings);
7645 }
77- case GET: {
78- Select.Selection selection = select();
79- for (ColumnMapper cm : mapper.allColumns()) {
80- Select.SelectionOrAlias column = (cm.kind == ColumnMapper.Kind.COMPUTED)
81- ? selection.raw(cm.getColumnName())
82- : selection.column(cm.getColumnName());
46+ return insert.toString();
47+ }
8348
84- if (cm.getAlias() == null) {
85- selection = column;
86- } else {
87- selection = column.as(cm.getAlias());
88- }
89- }
90- Select select;
91- if (table == null) {
92- select = selection.from(mapper.getKeyspace(), mapper.getTable());
49+ },
50+
51+ GET {
52+ @Override
53+ String makePreparedQueryString(TableMetadata table, EntityMapper<?> mapper, MappingManager manager, Set<PropertyMapper> columns, Collection<Mapper.Option> options) {
54+ Select.Selection selection = select();
55+ for (PropertyMapper col : mapper.allColumns) {
56+ Select.SelectionOrAlias column = col.isComputed()
57+ ? selection.raw(col.columnName)
58+ : selection.column(col.columnName);
59+
60+ if (col.alias == null) {
61+ selection = column;
9362 } else {
94- select = selection.from(table);
63+ selection = column.as(col.alias);
9564 }
96- Select.Where where = select.where();
97- for (int i = 0; i < mapper.primaryKeySize(); i++)
98- where.and(eq(mapper.getPrimaryKeyColumn(i).getColumnName(), bindMarker()));
99-
100- for (Mapper.Option opt : options)
101- opt.checkValidFor(QueryType.GET, manager);
102- return select.toString();
10365 }
104- case DEL: {
105- Delete delete = table == null
106- ? delete().all().from(mapper.getKeyspace(), mapper.getTable())
107- : delete().all().from(table);
108- Delete.Where where = delete.where();
109- for (int i = 0; i < mapper.primaryKeySize(); i++)
110- where.and(eq(mapper.getPrimaryKeyColumn(i).getColumnName(), bindMarker()));
111- Delete.Options usings = delete.using();
112- for (Mapper.Option opt : options) {
113- opt.checkValidFor(QueryType.DEL, manager);
114- if (opt.isIncludedInQuery())
115- opt.appendTo(usings);
116- }
117- return delete.toString();
66+ Select select;
67+ if (table == null) {
68+ select = selection.from(mapper.keyspace, mapper.table);
69+ } else {
70+ select = selection.from(table);
11871 }
119- case SLICE:
120- case REVERSED_SLICE: {
121- Select select = table == null
122- ? select().all().from(mapper.getKeyspace(), mapper.getTable())
123- : select().all().from(table);
124- Select.Where where = select.where();
125- for (int i = 0; i < mapper.partitionKeys.size(); i++)
126- where.and(eq(mapper.partitionKeys.get(i).getColumnName(), bindMarker()));
127-
128- if (startBoundSize > 0) {
129- if (startBoundSize == 1) {
130- String name = mapper.clusteringColumns.get(0).getColumnName();
131- where.and(startInclusive ? gte(name, bindMarker()) : gt(name, bindMarker()));
132- } else {
133- List<String> names = new ArrayList<String>(startBoundSize);
134- List<Object> values = new ArrayList<Object>(startBoundSize);
135- for (int i = 0; i < startBoundSize; i++) {
136- names.add(mapper.clusteringColumns.get(i).getColumnName());
137- values.add(bindMarker());
138- }
139- where.and(startInclusive ? gte(names, values) : gt(names, values));
140- }
141- }
142-
143- if (endBoundSize > 0) {
144- if (endBoundSize == 1) {
145- String name = mapper.clusteringColumns.get(0).getColumnName();
146- where.and(endInclusive ? gte(name, bindMarker()) : gt(name, bindMarker()));
147- } else {
148- List<String> names = new ArrayList<String>(endBoundSize);
149- List<Object> values = new ArrayList<Object>(endBoundSize);
150- for (int i = 0; i < endBoundSize; i++) {
151- names.add(mapper.clusteringColumns.get(i).getColumnName());
152- values.add(bindMarker());
153- }
154- where.and(endInclusive ? lte(names, values) : lt(names, values));
72+ Select.Where where = select.where();
73+ for (int i = 0; i < mapper.primaryKeySize(); i++)
74+ where.and(eq(mapper.getPrimaryKeyColumn(i).columnName, bindMarker()));
75+
76+ for (Mapper.Option opt : options)
77+ opt.checkValidFor(QueryType.GET, manager);
78+ return select.toString();
79+ }
80+ },
81+
82+ DEL {
83+ @Override
84+ String makePreparedQueryString(TableMetadata table, EntityMapper<?> mapper, MappingManager manager, Set<PropertyMapper> columns, Collection<Mapper.Option> options) {
85+ Delete delete = table == null
86+ ? delete().all().from(mapper.keyspace, mapper.table)
87+ : delete().all().from(table);
88+ Delete.Where where = delete.where();
89+ for (int i = 0; i < mapper.primaryKeySize(); i++)
90+ where.and(eq(mapper.getPrimaryKeyColumn(i).columnName, bindMarker()));
91+ Delete.Options usings = delete.using();
92+ for (Mapper.Option opt : options) {
93+ opt.checkValidFor(QueryType.DEL, manager);
94+ if (opt.isIncludedInQuery())
95+ opt.appendTo(usings);
15596 }
156- }
157-
158- select = select.limit(bindMarker());
159-
160- if (kind == Kind.REVERSED_SLICE)
161- select = select.orderBy(desc(mapper.clusteringColumns.get(0).getColumnName()));
162-
163- return select.toString();
164- }
97+ return delete.toString();
16598 }
166- throw new AssertionError();
167- }
168-
169- @Override
170- public boolean equals(Object obj) {
171- if (this == obj)
172- return true;
173- if (obj == null || this.getClass() != obj.getClass())
174- return false;
175-
176- QueryType that = (QueryType) obj;
177- return kind == that.kind
178- && startBoundSize == that.startBoundSize
179- && startInclusive == that.startInclusive
180- && endBoundSize == that.endBoundSize
181- && endInclusive == that.endInclusive;
182- }
99+ };
183100
184- @Override
185- public int hashCode() {
186- return Objects.hashCode(kind, startBoundSize, startInclusive, endBoundSize, endInclusive);
187- }
101+ abstract String makePreparedQueryString(TableMetadata table, EntityMapper<?> mapper, MappingManager manager, Set<PropertyMapper> columns, Collection<Mapper.Option> options);
188102
189103 }
deleted driver-mapping/src/main/java/com/datastax/driver/mapping/ReflectionMapper.java +0 −109
@@ -1,109 +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.beans.IntrospectionException;
21-import java.beans.PropertyDescriptor;
22-import java.lang.reflect.Field;
23-import java.lang.reflect.Method;
24-import java.util.concurrent.atomic.AtomicInteger;
25-
26-/**
27- * An {@link EntityMapper} implementation that use reflection to read and write fields
28- * of an entity.
29- */
30-class ReflectionMapper<T> extends EntityMapper<T> {
31-
32- private static ReflectionFactory factory = new ReflectionFactory();
33-
34- private ReflectionMapper(Class<T> entityClass, String keyspace, String table, ConsistencyLevel writeConsistency, ConsistencyLevel readConsistency) {
35- super(entityClass, keyspace, table, writeConsistency, readConsistency);
36- }
37-
38- public static Factory factory() {
39- return factory;
40- }
41-
42- @Override
43- public T newEntity() {
44- try {
45- return entityClass.newInstance();
46- } catch (Exception e) {
47- throw new RuntimeException("Can't create an instance of " + entityClass.getName());
48- }
49- }
50-
51- private static class LiteralMapper<T> extends ColumnMapper<T> {
52-
53- private final Method readMethod;
54- private final Method writeMethod;
55-
56- private LiteralMapper(Field field, int position, PropertyDescriptor pd, AtomicInteger columnCounter) {
57- super(field, position, columnCounter);
58- this.readMethod = pd.getReadMethod();
59- this.writeMethod = pd.getWriteMethod();
60- }
61-
62- @Override
63- Object getValue(T entity) {
64- try {
65- return readMethod.invoke(entity);
66- } catch (IllegalArgumentException e) {
67- throw new IllegalArgumentException("Could not get field '" + fieldName + "'");
68- } catch (Exception e) {
69- throw new IllegalStateException("Unable to access getter for '" + fieldName + "' in " + entity.getClass().getName(), e);
70- }
71- }
72-
73- @Override
74- void setValue(Object entity, Object value) {
75- try {
76- writeMethod.invoke(entity, value);
77- } catch (IllegalArgumentException e) {
78- throw new IllegalArgumentException("Could not set field '" + fieldName + "' to value '" + value + "'");
79- } catch (Exception e) {
80- throw new IllegalStateException("Unable to access setter for '" + fieldName + "' in " + entity.getClass().getName(), e);
81- }
82- }
83- }
84-
85- private static class ReflectionFactory implements Factory {
86-
87- @Override
88- public <T> EntityMapper<T> create(Class<T> entityClass, String keyspace, String table, ConsistencyLevel writeConsistency, ConsistencyLevel readConsistency) {
89- return new ReflectionMapper<T>(entityClass, keyspace, table, writeConsistency, readConsistency);
90- }
91-
92- @SuppressWarnings({"unchecked", "rawtypes"})
93- @Override
94- public <T> ColumnMapper<T> createColumnMapper(Class<T> entityClass, Field field, int position, MappingManager mappingManager, AtomicInteger columnCounter) {
95- String fieldName = field.getName();
96- try {
97- PropertyDescriptor pd = new PropertyDescriptor(fieldName, field.getDeclaringClass());
98-
99- for (Class<?> udt : TypeMappings.findUDTs(field.getGenericType()))
100- mappingManager.getUDTCodec(udt);
101-
102- return new LiteralMapper<T>(field, position, pd, columnCounter);
103-
104- } catch (IntrospectionException e) {
105- throw new IllegalArgumentException("Cannot find matching getter and setter for field '" + fieldName + "'");
106- }
107- }
108- }
109-}
modified driver-mapping/src/main/java/com/datastax/driver/mapping/ReflectionUtils.java +168 −15
@@ -15,26 +15,179 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import java.lang.reflect.ParameterizedType;
19-import java.lang.reflect.Type;
18+import com.google.common.base.Throwables;
19+
20+import java.beans.BeanInfo;
21+import java.beans.IntrospectionException;
22+import java.beans.Introspector;
23+import java.beans.PropertyDescriptor;
24+import java.lang.annotation.Annotation;
25+import java.lang.reflect.*;
26+import java.util.HashMap;
27+import java.util.Map;
2028
2129 /**
2230 * Utility methods related to reflection.
2331 */
2432 class ReflectionUtils {
2533
26- /**
27- * Gets a type argument from a parameterized type.
28- *
29- * @param pt the parameterized type.
30- * @param arg the index of the argument to retrieve.
31- * @param name the name of the element (field or method argument).
32- * @return the type argument.
33- */
34- static Class<?> getParam(ParameterizedType pt, int arg, String name) {
35- Type ft = pt.getActualTypeArguments()[arg];
36- if (!(ft instanceof Class))
37- throw new IllegalArgumentException(String.format("Cannot map parameter of class %s for %s", pt, name));
38- return (Class<?>) ft;
34+ static <T> T newInstance(Class<T> clazz) {
35+ Constructor<T> publicConstructor;
36+ try {
37+ publicConstructor = clazz.getConstructor();
38+ } catch (NoSuchMethodException e) {
39+ try {
40+ // try private constructor
41+ Constructor<T> privateConstructor = clazz.getDeclaredConstructor();
42+ privateConstructor.setAccessible(true);
43+ return privateConstructor.newInstance();
44+ } catch (Exception e1) {
45+ throw new IllegalArgumentException("Can't create an instance of " + clazz, e);
46+ }
47+ }
48+ try {
49+ return publicConstructor.newInstance();
50+ } catch (Exception e) {
51+ throw new IllegalArgumentException("Can't create an instance of " + clazz, e);
52+ }
53+ }
54+
55+ // for each key representing a property name,
56+ // value[0] contains a Field object, value[1] contains a PropertyDescriptor object;
57+ // they cannot be both null at the same time
58+ static <T> Map<String, Object[]> scanFieldsAndProperties(Class<T> baseClass) {
59+ Map<String, Object[]> fieldsAndProperties = new HashMap<String, Object[]>();
60+ Map<String, Field> fields = scanFields(baseClass);
61+ for (Map.Entry<String, Field> entry : fields.entrySet()) {
62+ fieldsAndProperties.put(entry.getKey(), new Object[]{entry.getValue(), null});
63+ }
64+ Map<String, PropertyDescriptor> properties = scanProperties(baseClass);
65+ for (Map.Entry<String, PropertyDescriptor> entry : properties.entrySet()) {
66+ Object[] value = fieldsAndProperties.get(entry.getKey());
67+ if (value == null)
68+ fieldsAndProperties.put(entry.getKey(), new Object[]{null, entry.getValue()});
69+ else value[1] = entry.getValue();
70+ }
71+ return fieldsAndProperties;
72+ }
73+
74+ private static <T> Map<String, Field> scanFields(Class<T> baseClass) {
75+ HashMap<String, Field> fields = new HashMap<String, Field>();
76+ for (Class<?> clazz = baseClass; !clazz.equals(Object.class); clazz = clazz.getSuperclass()) {
77+ for (Field field : clazz.getDeclaredFields()) {
78+ if (field.getName().equals("class") || field.isSynthetic() || Modifier.isStatic(field.getModifiers()))
79+ continue;
80+ // never override a more specific field masking another one declared in a superclass
81+ if (!fields.containsKey(field.getName()))
82+ fields.put(field.getName(), field);
83+ }
84+ }
85+ return fields;
86+ }
87+
88+ private static <T> Map<String, PropertyDescriptor> scanProperties(Class<T> baseClass) {
89+ BeanInfo beanInfo;
90+ try {
91+ beanInfo = Introspector.getBeanInfo(baseClass);
92+ } catch (IntrospectionException e) {
93+ throw Throwables.propagate(e);
94+ }
95+ Map<String, PropertyDescriptor> properties = new HashMap<String, PropertyDescriptor>();
96+ for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
97+ if (property.getName().equals("class"))
98+ continue;
99+ properties.put(property.getName(), property);
100+ }
101+ return properties;
102+ }
103+
104+ static Map<Class<? extends Annotation>, Annotation> scanPropertyAnnotations(Field field, PropertyDescriptor property) {
105+ Map<Class<? extends Annotation>, Annotation> annotations = new HashMap<Class<? extends Annotation>, Annotation>();
106+ // annotations on getters should have precedence over annotations on fields
107+ if (field != null)
108+ scanFieldAnnotations(field, annotations);
109+ Method getter = findGetter(property);
110+ if (getter != null)
111+ scanMethodAnnotations(getter, annotations);
112+ return annotations;
113+ }
114+
115+ private static Map<Class<? extends Annotation>, Annotation> scanFieldAnnotations(Field field, Map<Class<? extends Annotation>, Annotation> annotations) {
116+ for (Annotation annotation : field.getAnnotations()) {
117+ annotations.put(annotation.annotationType(), annotation);
118+ }
119+ return annotations;
39120 }
121+
122+ private static Map<Class<? extends Annotation>, Annotation> scanMethodAnnotations(Method method, Map<Class<? extends Annotation>, Annotation> annotations) {
123+ // 1. direct method annotations
124+ for (Annotation annotation : method.getAnnotations()) {
125+ annotations.put(annotation.annotationType(), annotation);
126+ }
127+ // 2. Class hierarchy: check for annotations in overridden methods in superclasses
128+ Class<?> getterClass = method.getDeclaringClass();
129+ for (Class<?> clazz = getterClass.getSuperclass(); !clazz.equals(Object.class); clazz = clazz.getSuperclass()) {
130+ maybeAddOverriddenMethodAnnotations(annotations, method, clazz);
131+ }
132+ // 3. Interfaces: check for annotations in implemented interfaces
133+ for (Class<?> clazz = getterClass; !clazz.equals(Object.class); clazz = clazz.getSuperclass()) {
134+ for (Class<?> itf : clazz.getInterfaces()) {
135+ maybeAddOverriddenMethodAnnotations(annotations, method, itf);
136+ }
137+ }
138+ return annotations;
139+ }
140+
141+ private static void maybeAddOverriddenMethodAnnotations(Map<Class<? extends Annotation>, Annotation> annotations, Method getter, Class<?> clazz) {
142+ try {
143+ Method overriddenGetter = clazz.getDeclaredMethod(getter.getName(), (Class[]) getter.getParameterTypes());
144+ for (Annotation annotation : overriddenGetter.getAnnotations()) {
145+ // do not override a more specific version of the annotation type being scanned
146+ if (!annotations.containsKey(annotation.annotationType()))
147+ annotations.put(annotation.annotationType(), annotation);
148+ }
149+ } catch (NoSuchMethodException e) {
150+ //ok
151+ }
152+ }
153+
154+ static Method findGetter(PropertyDescriptor property) {
155+ if (property == null)
156+ return null;
157+ Method getter = property.getReadMethod();
158+ if (getter == null)
159+ return null;
160+ return getter;
161+ }
162+
163+ static Method findSetter(Class<?> baseClass, PropertyDescriptor property) {
164+ if (property == null)
165+ return null;
166+ Method setter = property.getWriteMethod();
167+ if (setter != null)
168+ return setter;
169+ String propertyName = property.getName();
170+ String setterName = "set" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
171+ // JAVA-984: look for a "relaxed" setter, ie. a setter whose return type may be anything
172+ try {
173+ setter = baseClass.getMethod(setterName, property.getPropertyType());
174+ if (!Modifier.isStatic(setter.getModifiers())) {
175+ return setter;
176+ }
177+ } catch (NoSuchMethodException e) {
178+ // ok
179+ }
180+ return null;
181+ }
182+
183+ static void tryMakeAccessible(AccessibleObject object) {
184+ if (!object.isAccessible()) {
185+ try {
186+ object.setAccessible(true);
187+ } catch (SecurityException e) {
188+ // ok
189+ }
190+ }
191+ }
192+
40193 }
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 }
added driver-mapping/src/test/java/com/datastax/driver/mapping/MapperCaseSensitivityTest.java +192 −0
@@ -0,0 +1,192 @@
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.CCMConfig;
19+import com.datastax.driver.core.CCMTestsSupport;
20+import com.datastax.driver.core.TestUtils;
21+import com.datastax.driver.core.utils.CassandraVersion;
22+import com.datastax.driver.mapping.annotations.*;
23+import com.google.common.base.Objects;
24+import org.testng.annotations.Test;
25+
26+import static com.datastax.driver.core.Metadata.quote;
27+import static org.assertj.core.api.Assertions.assertThat;
28+
29+@CCMConfig(createKeyspace = false)
30+@CassandraVersion(major = 2.1)
31+public class MapperCaseSensitivityTest extends CCMTestsSupport {
32+
33+ static final String KS = "ks_MapperCaseSensitivityTest";
34+ static final String TABLE = "table_MapperCaseSensitivityTest";
35+ static final String TYPE = "udt_MapperCaseSensitivityTest";
36+
37+ UserNoKeyspace user = new UserNoKeyspace("id", new Address("street", "zip"));
38+
39+ @Table(keyspace = KS, name = TABLE, caseSensitiveKeyspace = true, caseSensitiveTable = true)
40+ static class User {
41+
42+ @PartitionKey
43+ @Column(caseSensitive = true)
44+ private String userId;
45+
46+ @Column(name = "Address", caseSensitive = true)
47+ private Address address;
48+
49+ public User() {
50+ }
51+
52+ public User(String userId, Address address) {
53+ this.userId = userId;
54+ this.address = address;
55+ }
56+
57+ public String getUserId() {
58+ return userId;
59+ }
60+
61+ public void setUserId(String userId) {
62+ this.userId = userId;
63+ }
64+
65+ public Address getAddress() {
66+ return address;
67+ }
68+
69+ public void setAddress(Address address) {
70+ this.address = address;
71+ }
72+
73+ @Override
74+ public boolean equals(Object o) {
75+ if (this == o) return true;
76+ if (o == null || !(o instanceof User)) return false;
77+ User user = (User) o;
78+ return Objects.equal(userId, user.userId) &&
79+ Objects.equal(address, user.address);
80+ }
81+
82+ @Override
83+ public int hashCode() {
84+ return Objects.hashCode(userId, address);
85+ }
86+ }
87+
88+ @UDT(keyspace = KS, name = TYPE, caseSensitiveKeyspace = true, caseSensitiveType = true)
89+ static class Address {
90+
91+ @Field(name = "Street", caseSensitive = true)
92+ private String street;
93+
94+ @Field(caseSensitive = true)
95+ private String zipCode;
96+
97+ public Address() {
98+ }
99+
100+ public Address(String street, String zipCode) {
101+ this.street = street;
102+ this.zipCode = zipCode;
103+ }
104+
105+ public String getStreet() {
106+ return street;
107+ }
108+
109+ public void setStreet(String street) {
110+ this.street = street;
111+ }
112+
113+ public String getZipCode() {
114+ return zipCode;
115+ }
116+
117+ public void setZipCode(String zipCode) {
118+ this.zipCode = zipCode;
119+ }
120+
121+ @Override
122+ public boolean equals(Object o) {
123+ if (this == o) return true;
124+ if (o == null || !(o instanceof Address)) return false;
125+ Address address = (Address) o;
126+ return Objects.equal(street, address.street) &&
127+ Objects.equal(zipCode, address.zipCode);
128+ }
129+
130+ @Override
131+ public int hashCode() {
132+ return Objects.hashCode(getStreet(), getZipCode());
133+ }
134+ }
135+
136+ @Table(name = TABLE, caseSensitiveKeyspace = true, caseSensitiveTable = true)
137+ static class UserNoKeyspace extends User {
138+
139+ public UserNoKeyspace() {
140+ }
141+
142+ public UserNoKeyspace(String id, Address address) {
143+ super(id, address);
144+ }
145+
146+ }
147+
148+ @UDT(name = TYPE, caseSensitiveKeyspace = true, caseSensitiveType = true)
149+ static class AddressNoKeyspace extends Address {
150+
151+ }
152+
153+ @Override
154+ public void onTestContextInitialized() {
155+ execute(String.format(TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT, quote(KS), 1));
156+ useKeyspace(quote(KS));
157+ execute(
158+ "CREATE TYPE " + quote(TYPE) + " (\"Street\" text, \"zipCode\" text)",
159+ "CREATE TABLE " + quote(TABLE) + " (\"userId\" text PRIMARY KEY, \"Address\" frozen<" + quote(TYPE) + ">)");
160+ }
161+
162+ /**
163+ * Validates that case sensitive identifiers for fields, types, columns, tables and keyspaces work with the mapper
164+ * when the keyspace name is specified on the mapped class.
165+ *
166+ * @jira_ticket JAVA-564
167+ * @test_category object_mapper
168+ */
169+ @Test(groups = "short")
170+ public void should_handle_case_sensitive_identifiers_when_keyspace_specified() throws Exception {
171+ MappingManager mappingManager = new MappingManager(session());
172+ Mapper<User> mapper = mappingManager.mapper(User.class);
173+ mapper.save(user);
174+ assertThat(mapper.get(user.getUserId())).isEqualTo(user);
175+ }
176+
177+ /**
178+ * Validates that case sensitive identifiers for fields, types, columns, tables and keyspaces work with the mapper
179+ * when the keyspace name is *not* specified on the mapped class.
180+ *
181+ * @jira_ticket JAVA-564
182+ * @test_category object_mapper
183+ */
184+ @Test(groups = "short")
185+ public void should_handle_case_sensitive_identifiers_without_keyspace_specified() throws Exception {
186+ MappingManager mappingManager = new MappingManager(session());
187+ Mapper<UserNoKeyspace> mapper = mappingManager.mapper(UserNoKeyspace.class);
188+ mapper.save(user);
189+ assertThat(mapper.get(user.getUserId())).isEqualTo(user);
190+ }
191+
192+}
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperComputedFieldsTest.java +1 −1
@@ -91,7 +91,7 @@
9191 void should_add_aliases_for_fields_in_select_queries() {
9292 BoundStatement bs = (BoundStatement) userMapper.getQuery("test");
9393 assertThat(bs.preparedStatement().getQueryString())
94- .contains("SELECT", "\"login\" AS col1", "\"name\" AS col2", "writetime(\"name\") AS col3");
94+ .contains("SELECT", "login AS col", "name AS col", "writetime(\"name\") AS col");
9595 }
9696
9797 @Test(groups = "short")
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperDefaultKeyspaceTest.java +2 −2
@@ -92,7 +92,7 @@
9292
9393 @Test(groups = "short",
9494 expectedExceptions = IllegalArgumentException.class,
95- expectedExceptionsMessageRegExp = "Error creating mapper for class Group, the @Table annotation declares no default keyspace, and the session is not currently logged to any keyspace")
95+ expectedExceptionsMessageRegExp = "Error creating mapper for class com.datastax.driver.mapping.MapperDefaultKeyspaceTest\\$Group, the @Table annotation declares no default keyspace, and the session is not currently logged to any keyspace")
9696 public void should_throw_a_meaningful_error_message_when_no_default_table_keyspace_and_session_not_logged() {
9797 Session session2 = cluster().connect();
9898 MappingManager manager = new MappingManager(session2);
@@ -101,7 +101,7 @@
101101
102102 @Test(groups = "short",
103103 expectedExceptions = IllegalArgumentException.class,
104- expectedExceptionsMessageRegExp = "Error creating UDT codec for class GroupName, the @UDT annotation declares no default keyspace, and the session is not currently logged to any keyspace")
104+ expectedExceptionsMessageRegExp = "Error creating UDT codec for class com.datastax.driver.mapping.MapperDefaultKeyspaceTest\\$GroupName, the @UDT annotation declares no default keyspace, and the session is not currently logged to any keyspace")
105105 public void should_throw_a_meaningful_error_message_when_no_default_udt_keyspace_and_session_not_logged() {
106106 Session session2 = cluster().connect();
107107 MappingManager manager = new MappingManager(session2);
added driver-mapping/src/test/java/com/datastax/driver/mapping/MapperInvalidAnnotationsTest.java +287 −0
@@ -0,0 +1,287 @@
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.*;
19+import com.datastax.driver.mapping.annotations.*;
20+import org.testng.annotations.BeforeClass;
21+import org.testng.annotations.Test;
22+
23+import static org.mockito.Mockito.*;
24+
25+@SuppressWarnings({"unused", "WeakerAccess"})
26+public class MapperInvalidAnnotationsTest {
27+
28+ MappingManager mappingManager;
29+
30+ @BeforeClass(groups = "unit")
31+ public void setup() {
32+ mappingManager = mock(MappingManager.class);
33+ Session session = mock(Session.class);
34+ when(mappingManager.getSession()).thenReturn(session);
35+ Cluster cluster = mock(Cluster.class);
36+ when(session.getCluster()).thenReturn(cluster);
37+ Metadata metadata = mock(Metadata.class);
38+ when(cluster.getMetadata()).thenReturn(metadata);
39+ KeyspaceMetadata keyspace = mock(KeyspaceMetadata.class);
40+ when(metadata.getKeyspace(anyString())).thenReturn(keyspace);
41+
42+ UserType userType = mock(UserType.class);
43+ when(keyspace.getUserType(anyString())).thenReturn(userType);
44+ when(userType.contains(anyString())).thenReturn(true);
45+
46+ TableMetadata table = mock(TableMetadata.class);
47+ when(keyspace.getTable(anyString())).thenReturn(table);
48+ ColumnMetadata column = mock(ColumnMetadata.class);
49+ when(table.getColumn(anyString())).thenReturn(column);
50+ }
51+
52+ static class Invalid1 {
53+ }
54+
55+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
56+ expectedExceptionsMessageRegExp =
57+ "@Table annotation was not found on class " +
58+ "com.datastax.driver.mapping.MapperInvalidAnnotationsTest\\$Invalid1")
59+ public void should_throw_IAE_when_Table_annotation_not_found_on_entity_class() throws Exception {
60+ AnnotationParser.parseEntity(Invalid1.class, mappingManager);
61+ }
62+
63+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
64+ expectedExceptionsMessageRegExp =
65+ "@UDT annotation was not found on class " +
66+ "com.datastax.driver.mapping.MapperInvalidAnnotationsTest\\$Invalid1")
67+ public void should_throw_IAE_when_UDT_annotation_not_found_on_udt_class() throws Exception {
68+ AnnotationParser.parseUDT(Invalid1.class, mappingManager);
69+ }
70+
71+ @Table(name = "foo")
72+ @UDT(name = "foo")
73+ static class Invalid2 {
74+ }
75+
76+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
77+ expectedExceptionsMessageRegExp =
78+ "Cannot have both @Table and @UDT on class " +
79+ "com.datastax.driver.mapping.MapperInvalidAnnotationsTest\\$Invalid2")
80+ public void should_throw_IAE_when_UDT_annotation_found_on_entity_class() throws Exception {
81+ AnnotationParser.parseEntity(Invalid2.class, mappingManager);
82+ }
83+
84+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
85+ expectedExceptionsMessageRegExp =
86+ "Cannot have both @UDT and @Table on class " +
87+ "com.datastax.driver.mapping.MapperInvalidAnnotationsTest\\$Invalid2")
88+ public void should_throw_IAE_when_Table_annotation_found_on_udt_class() throws Exception {
89+ AnnotationParser.parseUDT(Invalid2.class, mappingManager);
90+ }
91+
92+ @Table(name = "foo")
93+ @Accessor
94+ static class Invalid3 {
95+ }
96+
97+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
98+ expectedExceptionsMessageRegExp =
99+ "Cannot have both @Table and @Accessor on class " +
100+ "com.datastax.driver.mapping.MapperInvalidAnnotationsTest\\$Invalid3")
101+ public void should_throw_IAE_when_Accessor_annotation_found_on_entity_class() throws Exception {
102+ AnnotationParser.parseEntity(Invalid3.class, mappingManager);
103+ }
104+
105+ @UDT(name = "foo")
106+ @Accessor
107+ static class Invalid4 {
108+ }
109+
110+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
111+ expectedExceptionsMessageRegExp =
112+ "Cannot have both @UDT and @Accessor on class " +
113+ "com.datastax.driver.mapping.MapperInvalidAnnotationsTest\\$Invalid4")
114+ public void should_throw_IAE_when_Accessor_annotation_found_on_udt_class() throws Exception {
115+ AnnotationParser.parseUDT(Invalid4.class, mappingManager);
116+ }
117+
118+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
119+ expectedExceptionsMessageRegExp =
120+ "@Accessor annotation is only allowed on interfaces, got class " +
121+ "com.datastax.driver.mapping.MapperInvalidAnnotationsTest\\$Invalid4")
122+ public void should_throw_IAE_when_Accessor_annotation_found_on_concrete_class() throws Exception {
123+ AnnotationParser.parseAccessor(Invalid4.class, mappingManager);
124+ }
125+
126+ interface Invalid5 {
127+ }
128+
129+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
130+ expectedExceptionsMessageRegExp =
131+ "@Accessor annotation was not found on interface " +
132+ "com.datastax.driver.mapping.MapperInvalidAnnotationsTest\\$Invalid5")
133+ public void should_throw_IAE_when_Accessor_annotation_not_found_on_accessor_class() throws Exception {
134+ AnnotationParser.parseAccessor(Invalid5.class, mappingManager);
135+ }
136+
137+ @Table(name = "foo")
138+ @Accessor
139+ interface Invalid6 {
140+ }
141+
142+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
143+ expectedExceptionsMessageRegExp =
144+ "Cannot have both @Accessor and @Table on interface " +
145+ "com.datastax.driver.mapping.MapperInvalidAnnotationsTest\\$Invalid6")
146+ public void should_throw_IAE_when_Table_annotation_found_on_accessor_class() throws Exception {
147+ AnnotationParser.parseAccessor(Invalid6.class, mappingManager);
148+ }
149+
150+ @UDT(name = "foo")
151+ @Accessor
152+ interface Invalid7 {
153+ }
154+
155+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
156+ expectedExceptionsMessageRegExp =
157+ "Cannot have both @Accessor and @UDT on interface " +
158+ "com.datastax.driver.mapping.MapperInvalidAnnotationsTest\\$Invalid7")
159+ public void should_throw_IAE_when_UDT_annotation_found_on_accessor_class() throws Exception {
160+ AnnotationParser.parseAccessor(Invalid7.class, mappingManager);
161+ }
162+
163+ @Table(name = "foo", keyspace = "ks")
164+ static class Invalid8 {
165+ @Field
166+ int invalid;
167+ }
168+
169+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
170+ expectedExceptionsMessageRegExp =
171+ "Annotation @Field is not allowed on property 'invalid'")
172+ public void should_throw_IAE_when_Field_annotation_found_on_entity_class_field() throws Exception {
173+ AnnotationParser.parseEntity(Invalid8.class, mappingManager);
174+ }
175+
176+ @UDT(name = "foo", keyspace = "ks")
177+ static class Invalid9 {
178+
179+ int invalid;
180+
181+ @Column
182+ public int getInvalid() {
183+ return invalid;
184+ }
185+ }
186+
187+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
188+ expectedExceptionsMessageRegExp =
189+ "Annotation @Column is not allowed on property 'invalid'")
190+ public void should_throw_IAE_when_Column_annotation_found_on_udt_class_field() throws Exception {
191+ AnnotationParser.parseUDT(Invalid9.class, mappingManager);
192+ }
193+
194+ @Table(name = "foo", keyspace = "ks")
195+ static class Invalid10 {
196+
197+ @PartitionKey
198+ @ClusteringColumn
199+ int invalid;
200+
201+ }
202+
203+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
204+ expectedExceptionsMessageRegExp =
205+ "Property 'invalid' cannot be annotated with both @PartitionKey and @ClusteringColumn")
206+ public void should_throw_IAE_when_PartitionKey_and_ClusteringColumn_on_same_property() throws Exception {
207+ AnnotationParser.parseEntity(Invalid10.class, mappingManager);
208+ }
209+
210+ @Table(name = "foo", keyspace = "ks")
211+ static class Invalid11 {
212+
213+ @Computed("foo")
214+ @Column
215+ int invalid;
216+
217+ }
218+
219+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
220+ expectedExceptionsMessageRegExp =
221+ "Property 'invalid' cannot be annotated with both @Column and @Computed")
222+ public void should_throw_IAE_when_Computed_and_Column_on_same_property() throws Exception {
223+ AnnotationParser.parseEntity(Invalid11.class, mappingManager);
224+ }
225+
226+ @Table(name = "foo", keyspace = "ks")
227+ static class Invalid12 {
228+
229+ @Computed("")
230+ int invalid;
231+
232+ }
233+
234+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
235+ expectedExceptionsMessageRegExp =
236+ "Property 'invalid': attribute 'value' of annotation @Computed is mandatory for computed properties")
237+ public void should_throw_IAE_when_Computed_with_empty_value() throws Exception {
238+ AnnotationParser.parseEntity(Invalid12.class, mappingManager);
239+ }
240+
241+ @Table(name = "foo", keyspace = "ks")
242+ static class Invalid13 {
243+
244+ @PartitionKey(-1)
245+ int invalid;
246+
247+ }
248+
249+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
250+ expectedExceptionsMessageRegExp =
251+ "Invalid ordering value -1 for annotation @PartitionKey of property 'invalid', was expecting 0")
252+ public void should_throw_IAE_when_PartitionKey_with_wrong_order() throws Exception {
253+ AnnotationParser.parseEntity(Invalid13.class, mappingManager);
254+ }
255+
256+ @Table(name = "foo", keyspace = "ks")
257+ static class Invalid14 {
258+
259+ public void setNotReadable(int i) {
260+ }
261+
262+ }
263+
264+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
265+ expectedExceptionsMessageRegExp =
266+ "Property 'notReadable' is not readable")
267+ public void should_throw_IAE_when_unreadable_property() throws Exception {
268+ AnnotationParser.parseEntity(Invalid14.class, mappingManager);
269+ }
270+
271+ @Table(name = "foo", keyspace = "ks")
272+ static class Invalid15 {
273+
274+ public int getNotWritable() {
275+ return 0;
276+ }
277+
278+ }
279+
280+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
281+ expectedExceptionsMessageRegExp =
282+ "Property 'notWritable' is not writable")
283+ public void should_throw_IAE_when_unwritable_property() throws Exception {
284+ AnnotationParser.parseEntity(Invalid15.class, mappingManager);
285+ }
286+
287+}
added driver-mapping/src/test/java/com/datastax/driver/mapping/MapperPolymorphismTest.java +521 −0
@@ -0,0 +1,521 @@
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.CCMTestsSupport;
19+import com.datastax.driver.core.utils.CassandraVersion;
20+import com.datastax.driver.mapping.annotations.*;
21+import com.google.common.base.Objects;
22+import com.google.common.collect.Sets;
23+import org.testng.annotations.AfterMethod;
24+import org.testng.annotations.Test;
25+
26+import java.util.Set;
27+import java.util.UUID;
28+
29+import static org.assertj.core.api.Assertions.assertThat;
30+
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"})
37+@CassandraVersion(major = 2.1)
38+public class MapperPolymorphismTest extends CCMTestsSupport {
39+
40+ Circle circle = new Circle(new Point2D(11, 22), 12.34);
41+ Rectangle rectangle = new Rectangle(new Point2D(20, 30), new Point2D(50, 60));
42+ Square square = new Square(new Point2D(20, 30), new Point2D(50, 60));
43+ Sphere sphere = new Sphere(new Point3D(11, 22, 33), 34.56);
44+
45+ @Override
46+ public void onTestContextInitialized() {
47+ execute(
48+ "CREATE TYPE point2d (\"X\" int, \"Y\" int)",
49+ "CREATE TYPE point3d (\"X\" int, \"Y\" int, \"Z\" int)",
50+ "CREATE TABLE circles (circle_id uuid PRIMARY KEY, center2d frozen<point2d>, radius double, tags set<text>)",
51+ "CREATE TABLE rectangles (rect_id uuid PRIMARY KEY, bottom_left frozen<point2d>, top_right frozen<point2d>, tags set<text>)",
52+ "CREATE TABLE squares (square_id uuid PRIMARY KEY, bottom_left frozen<point2d>, top_right frozen<point2d>, tags set<text>)",
53+ "CREATE TABLE spheres (sphere_id uuid PRIMARY KEY, center3d frozen<point3d>, radius double, tags set<text>)");
54+ }
55+
56+ @AfterMethod(groups = "short")
57+ public void clean() {
58+ execute("TRUNCATE circles", "TRUNCATE rectangles", "TRUNCATE squares", "TRUNCATE spheres");
59+ }
60+
61+ @UDT(name = "point2d")
62+ static class Point2D {
63+
64+ // test mix of field and getter - getter should win
65+ @Field(name = "wrong")
66+ private int x;
67+
68+ private int y;
69+
70+ // test private constructor + "immutability"
71+ private Point2D() {
72+ }
73+
74+ public Point2D(int x, int y) {
75+ this.x = x;
76+ this.y = y;
77+ }
78+
79+ @Field(name = "X", caseSensitive = true)
80+ public int getX() {
81+ return x;
82+ }
83+
84+ @Field(name = "Y", caseSensitive = true)
85+ public int getY() {
86+ return y;
87+ }
88+
89+ @Override
90+ public boolean equals(Object o) {
91+ if (this == o) return true;
92+ if (o == null || getClass() != o.getClass()) return false;
93+ Point2D point2D = (Point2D) o;
94+ return getX() == point2D.getX() &&
95+ getY() == point2D.getY();
96+ }
97+
98+ @Override
99+ public int hashCode() {
100+ return Objects.hashCode(getX(), getY());
101+ }
102+ }
103+
104+ @UDT(name = "point3d")
105+ static class Point3D extends Point2D {
106+
107+ private int z;
108+
109+ // test private constructor + "immutability"
110+ private Point3D() {
111+ }
112+
113+ public Point3D(int x, int y, int z) {
114+ super(x, y);
115+ this.z = z;
116+ }
117+
118+ @Field(name = "Z", caseSensitive = true)
119+ public int getZ() {
120+ return z;
121+ }
122+
123+ @Override
124+ public boolean equals(Object o) {
125+ if (this == o) return true;
126+ if (o == null || getClass() != o.getClass()) return false;
127+ if (!super.equals(o)) return false;
128+ Point3D point3D = (Point3D) o;
129+ return getZ() == point3D.getZ();
130+ }
131+
132+ @Override
133+ public int hashCode() {
134+ return Objects.hashCode(super.hashCode(), getZ());
135+ }
136+ }
137+
138+ interface Shape2D {
139+
140+ Set<String> getTags();
141+
142+ // test annotation on interface method, should get inherited everywhere
143+ @Transient
144+ double getArea();
145+
146+ }
147+
148+ interface Shape3D {
149+
150+ double getVolume();
151+
152+ }
153+
154+ static abstract class Shape implements Shape2D {
155+
156+ @PartitionKey // annotated field on superclass; annotation will get inherited in all subclasses
157+ protected UUID id;
158+
159+ protected Set<String> tags;
160+
161+ public Shape() {
162+ this.id = UUID.randomUUID();
163+ this.tags = Sets.newHashSet("cool", "awesome");
164+ }
165+
166+ @Column(name = "wrong") // gets overridden in all subclasses
167+ public abstract UUID getId();
168+
169+ public void setId(UUID id) {
170+ this.id = id;
171+ }
172+
173+ @Override
174+ public Set<String> getTags() {
175+ return tags;
176+ }
177+
178+ @Override
179+ public boolean equals(Object o) {
180+ if (this == o) return true;
181+ if (o == null || getClass() != o.getClass()) return false;
182+ Shape shape = (Shape) o;
183+ return Objects.equal(getId(), shape.getId());
184+ }
185+
186+ @Override
187+ public int hashCode() {
188+ return Objects.hashCode(getId());
189+ }
190+ }
191+
192+ @Table(name = "circles")
193+ static class Circle extends Shape {
194+
195+ @Column(name = "center2d") // overridden by a getter in Sphere
196+ @Frozen
197+ protected Point2D center;
198+
199+ // tests unusual field name (i.e. does not correspond to getter/setter)
200+ // will be considered as a separate "property" with no getter nor setter;
201+ // thus needs to be annotated with @Transient
202+ @Transient
203+ private double _radius;
204+
205+ private long writeTime;
206+
207+ public Circle() {
208+ }
209+
210+ public Circle(Point2D center, double radius) {
211+ this.center = center;
212+ this._radius = radius;
213+ }
214+
215+ @Column(name = "circle_id")
216+ @Override
217+ public UUID getId() {
218+ return id;
219+ }
220+
221+ public Point2D getCenter() {
222+ return center;
223+ }
224+
225+ public void setCenter(Point2D center) {
226+ this.center = center;
227+ }
228+
229+ public double getRadius() {
230+ return _radius;
231+ }
232+
233+ // builder-style setter; because the field isn't named in a standard way,
234+ // if this setter is not detected the test would fail
235+ public Circle setRadius(double radius) {
236+ this._radius = radius;
237+ return this;
238+ }
239+
240+ @Override
241+ // inherits @Transient
242+ public double getArea() {
243+ return Math.PI * (Math.pow(getRadius(), 2));
244+ }
245+
246+ // tests computed columns - no setter
247+ @Computed(value = "writetime(\"radius\")")
248+ public long getWriteTime() {
249+ return writeTime;
250+ }
251+
252+ // mismatched setter - getter is declared in Shape
253+ public void setTags(Set<String> tags) {
254+ this.tags = tags;
255+ }
256+
257+ @Override
258+ public boolean equals(Object o) {
259+ if (this == o) return true;
260+ if (o == null || getClass() != o.getClass()) return false;
261+ if (!super.equals(o)) return false;
262+ Circle circle = (Circle) o;
263+ return Double.compare(circle.getRadius(), getRadius()) == 0 &&
264+ Objects.equal(getCenter(), circle.getCenter());
265+ }
266+
267+ @Override
268+ public int hashCode() {
269+ return Objects.hashCode(super.hashCode(), getCenter(), getRadius());
270+ }
271+ }
272+
273+ @Table(name = "rectangles")
274+ static class Rectangle extends Shape {
275+
276+ private Point2D bottomLeft;
277+
278+ private Point2D topRight;
279+
280+ public Rectangle() {
281+ }
282+
283+ public Rectangle(Point2D bottomLeft, Point2D topRight) {
284+ this.bottomLeft = bottomLeft;
285+ this.topRight = topRight;
286+ }
287+
288+ @Column(name = "rect_id")
289+ @Override
290+ public UUID getId() {
291+ return id;
292+ }
293+
294+ @Column(name = "bottom_left")
295+ @Frozen
296+ public Point2D getBottomLeft() {
297+ return bottomLeft;
298+ }
299+
300+ public void setBottomLeft(Point2D bottomLeft) {
301+ this.bottomLeft = bottomLeft;
302+ }
303+
304+ @Column(name = "top_right")
305+ @Frozen
306+ public Point2D getTopRight() {
307+ return topRight;
308+ }
309+
310+ public void setTopRight(Point2D topRight) {
311+ this.topRight = topRight;
312+ }
313+
314+ // test annotation in class method
315+ @Transient
316+ public double getWidth() {
317+ return Math.abs(topRight.getX() - bottomLeft.getX());
318+ }
319+
320+ @Transient
321+ public double getHeight() {
322+ return Math.abs(topRight.getY() - bottomLeft.getY());
323+ }
324+
325+ @Override
326+ // inherits @Transient
327+ public double getArea() {
328+ return getWidth() * getHeight();
329+ }
330+
331+ @Override
332+ public boolean equals(Object o) {
333+ if (this == o) return true;
334+ if (o == null || getClass() != o.getClass()) return false;
335+ if (!super.equals(o)) return false;
336+ Rectangle rectangle = (Rectangle) o;
337+ return Objects.equal(getBottomLeft(), rectangle.getBottomLeft()) &&
338+ Objects.equal(getTopRight(), rectangle.getTopRight());
339+ }
340+
341+ @Override
342+ public int hashCode() {
343+ return Objects.hashCode(super.hashCode(), getBottomLeft(), getTopRight());
344+ }
345+ }
346+
347+ @Table(name = "squares")
348+ static class Square extends Rectangle {
349+
350+ public Square() {
351+ }
352+
353+ public Square(Point2D bottomLeft, Point2D topRight) {
354+ super(bottomLeft, topRight);
355+ assert getHeight() == getWidth();
356+ }
357+
358+ @Column(name = "square_id")
359+ @Override
360+ public UUID getId() {
361+ return id;
362+ }
363+
364+ @Override
365+ // inherits @Column and @Frozen
366+ public Point2D getBottomLeft() {
367+ return super.getBottomLeft();
368+ }
369+
370+ @Override
371+ // inherits @Transient
372+ public double getHeight() {
373+ return getWidth();
374+ }
375+
376+ @Override
377+ public boolean equals(Object o) {
378+ if (this == o) return true;
379+ if (o == null || getClass() != o.getClass()) return false;
380+ if (!super.equals(o)) return false;
381+ Square square = (Square) o;
382+ return Objects.equal(getBottomLeft(), square.getBottomLeft()) &&
383+ Objects.equal(getTopRight(), square.getTopRight());
384+ }
385+
386+ }
387+
388+ @Table(name = "spheres")
389+ static class Sphere extends Circle implements Shape3D {
390+
391+ private long writeTime;
392+
393+ public Sphere() {
394+ }
395+
396+ public Sphere(Point3D center, double radius) {
397+ this.center = center;
398+ }
399+
400+ @Column(name = "sphere_id")
401+ @Override
402+ public UUID getId() {
403+ return id;
404+ }
405+
406+ // overrides field annotation in Circle,
407+ // note that the property type is narrowed down to Point3D
408+ @Column(name = "center3d")
409+ @Frozen
410+ @Override
411+ public Point3D getCenter() {
412+ return (Point3D) center;
413+ }
414+
415+ @Override
416+ public void setCenter(Point2D center) {
417+ assert center instanceof Point3D;
418+ this.center = center;
419+ }
420+
421+ // overridden builder-style setter
422+ @Override
423+ public Sphere setRadius(double radius) {
424+ super.setRadius(radius);
425+ return this;
426+ }
427+
428+ @Override
429+ public boolean equals(Object o) {
430+ if (this == o) return true;
431+ if (o == null || getClass() != o.getClass()) return false;
432+ if (!super.equals(o)) return false;
433+ Sphere sphere = (Sphere) o;
434+ return Objects.equal(getCenter(), sphere.getCenter());
435+ }
436+
437+ @Override
438+ public int hashCode() {
439+ return Objects.hashCode(super.hashCode(), getCenter());
440+ }
441+
442+ // test annotation on implementation
443+ @Override
444+ @Transient
445+ public double getVolume() {
446+ return 4d / 3d * Math.PI * Math.pow(getRadius(), 3);
447+ }
448+
449+ }
450+
451+ /**
452+ * Validates that fields and methods from a parent class {@link Shape} are inherited for a mapped entity
453+ * class {@link Circle}.
454+ * <p/>
455+ * It also ensures that methods overridden in {@link Circle} are given precedence and that their annotations are
456+ * used. In the case of circle, the {@link Circle#getId()} method overrides the parent and specifies a
457+ * {@link Column} annotation that will be used instead of the parents annotation ('wrong').
458+ * <p/>
459+ * Lastly, it defines another column 'radius' that is defined by having {@link Circle#getRadius} and
460+ * {@link Circle#setRadius} properties, while it has a {@link Transient} field '_radius' that should not be pulled
461+ * in by the mapper.
462+ *
463+ * @test_category object_mapper
464+ * @jira_ticket JAVA-541, JAVA-636
465+ */
466+ @Test(groups = "short")
467+ public void should_save_and_retrieve_circle() throws Exception {
468+ MappingManager mappingManager = new MappingManager(session());
469+ Mapper<Circle> circleMapper = mappingManager.mapper(Circle.class);
470+ circleMapper.save(circle);
471+ assertThat(circleMapper.get(circle.getId())).isEqualTo(circle);
472+ }
473+
474+ /**
475+ * Validates that property methods such as {@link Rectangle#getWidth} and {@link Rectangle#getHeight} are not
476+ * considered as they are marked as {@link Transient}. It also ensures that overridden method
477+ * {@link Rectangle#getArea} inherits its parent's {@link Transient} annotation.
478+ *
479+ * @test_category object_mapper
480+ * @jira_ticket JAVA-541, JAVA-636
481+ */
482+ @Test(groups = "short")
483+ public void should_save_and_retrieve_rectangle() throws Exception {
484+ MappingManager mappingManager = new MappingManager(session());
485+ Mapper<Rectangle> rectangleMapper = mappingManager.mapper(Rectangle.class);
486+ rectangleMapper.save(rectangle);
487+ assertThat(rectangleMapper.get(rectangle.getId())).isEqualTo(rectangle);
488+ }
489+
490+ /**
491+ * Validates that {@link Square} inherits its properties from its parent class {@link Rectangle} and its parent's
492+ * class {@link Shape} and that its methods {@link Square#getBottomLeft} and {@link Square#getHeight} inherit
493+ * annotations from its parent.
494+ *
495+ * @test_category object_mapper
496+ * @jira_ticket JAVA-541, JAVA-636
497+ */
498+ @Test(groups = "short")
499+ public void should_save_and_retrieve_square() throws Exception {
500+ MappingManager mappingManager = new MappingManager(session());
501+ Mapper<Square> squareMapper = mappingManager.mapper(Square.class);
502+ squareMapper.save(square);
503+ assertThat(squareMapper.get(square.getId())).isEqualTo(square);
504+ }
505+
506+ /**
507+ * Validates that {@link Sphere} inherits its properties from its parent class {@link Circle} and most importantly
508+ * can specialize the type of {@link Sphere#center} to a {@link Point3D} instead of a {@link Point2D}.
509+ *
510+ * @test_category object_mapper
511+ * @jira_ticket JAVA-541, JAVA-636
512+ */
513+ @Test(groups = "short")
514+ public void should_save_and_retrieve_sphere() throws Exception {
515+ MappingManager mappingManager = new MappingManager(session());
516+ Mapper<Sphere> sphereMapper = mappingManager.mapper(Sphere.class);
517+ sphereMapper.save(sphere);
518+ assertThat(sphereMapper.get(sphere.getId())).isEqualTo(sphere);
519+ }
520+
521+}
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperSaveNullFieldsTest.java +4 −4
@@ -83,14 +83,14 @@
8383 BoundStatement bs = (BoundStatement) mapper.saveQuery(newUser, options);
8484 String queryString = bs.preparedStatement().getQueryString();
8585 if (nullName && !saveExpected)
86- assertThat(queryString).as(description).doesNotContain("\"name\"");
86+ assertThat(queryString).as(description).doesNotContain("name");
8787 else
88- assertThat(queryString).as(description).contains("\"name\"");
88+ assertThat(queryString).as(description).contains("name");
8989
9090 if (nullPhone && !saveExpected)
91- assertThat(queryString).as(description).doesNotContain("\"phone\"");
91+ assertThat(queryString).as(description).doesNotContain("phone");
9292 else
93- assertThat(queryString).as(description).contains("\"phone\"");
93+ assertThat(queryString).as(description).contains("phone");
9494
9595 // Save entity and check the data
9696 mapper.save(newUser, options);
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 driver-mapping/src/test/java/com/datastax/driver/mapping/MapperUDTTest.java +10 −10
@@ -380,7 +380,7 @@
380380 /**
381381 * Ensures that if a table is altered after a {@link Mapper} is created that it continues to work as long as
382382 * the change is compatible. A new column is added to the table in this case, which is a compatible change.
383- * <p>
383+ * <p/>
384384 * It also ensures that after the change is made that requesting a new {@link Mapper} returns a different instance
385385 * instead of the existing one.
386386 *
@@ -407,7 +407,7 @@
407407 /**
408408 * Ensures that if a UDT is altered after a {@link Mapper} is created that has a UDT that it continues to work as
409409 * long as the change is compatible. A new field is added to the table in this case, which is a compatible change.
410- * <p>
410+ * <p/>
411411 * It also ensures that after the change is made that requesting a new {@link TypeCodec} for that UDT and a new
412412 * {@link Mapper} for a table using that UDT returns different instances instead of the existing ones.
413413 *
@@ -440,7 +440,7 @@
440440 * Ensures that if a table is dropped after a {@link Mapper} is created that the {@link Mapper} can no longer
441441 * successfully make queries and that attempting to create a new {@link Mapper} throws an
442442 * {@link IllegalArgumentException}.
443- * <p>
443+ * <p/>
444444 * It also ensures that requesting a {@link Mapper} fails as the previous {@link Mapper} was evicted and a new
445445 * one cannot be created as the table has been dropped.
446446 *
@@ -471,14 +471,14 @@
471471 manager.mapper(User.class);
472472 fail("Expected IllegalArgumentException");
473473 } catch (IllegalArgumentException e) {
474- assertThat(e.getMessage()).isEqualTo("Table users does not exist in keyspace " + keyspace);
474+ assertThat(e.getMessage()).isEqualTo("Table users does not exist in keyspace \"" + keyspace + "\"");
475475 }
476476 }
477477
478478 /**
479479 * Ensures that if a table is altered after a {@link Mapper} is created that it no longer continues to work if
480480 * the change is not compatible. A column is dropped from the table in this case, which is an incompatible change.
481- * <p>
481+ * <p/>
482482 * It also ensures that requesting a {@link Mapper} fails as the previous {@link Mapper} was evicted and a new
483483 * one cannot be created as a declared column is missing from the schema but is present in the class definition.
484484 *
@@ -509,7 +509,7 @@
509509 manager.mapper(User.class);
510510 fail("Expected IllegalArgumentException");
511511 } catch (IllegalArgumentException e) {
512- assertThat(e.getMessage()).isEqualTo(String.format("Column \"mainaddress\" does not exist in table %s.users", keyspace));
512+ assertThat(e.getMessage()).isEqualTo(String.format("Column mainaddress does not exist in table \"%s\".users", keyspace));
513513 }
514514 }
515515
@@ -517,10 +517,10 @@
517517 * Ensures that if a UDT is altered after a {@link Mapper} is created that it no longer continues to work if
518518 * the change made to the UDT is not compatible. A field is renamed in the UDT in this case, which is not a
519519 * compatible change.
520- * <p>
520+ * <p/>
521521 * It also ensures that requesting a {@link Mapper} fails as the previous {@link Mapper} was evicted and a new
522522 * one cannot be created as a declared field is missing from the schema but is present in the class definition.
523- * <p>
523+ * <p/>
524524 * Also verifies that a {@link TypeCodec} cannot be requested for the UDT as well.
525525 *
526526 * @jira_ticket JAVA-1126
@@ -552,13 +552,13 @@
552552 manager.mapper(User.class);
553553 fail("Expected IllegalArgumentException");
554554 } catch (IllegalArgumentException e) {
555- assertThat(e.getMessage()).isEqualTo(String.format("Field \"ZIP_code\" does not exist in type %s.address", keyspace));
555+ assertThat(e.getMessage()).isEqualTo(String.format("Field \"ZIP_code\" does not exist in type \"%s\".address", keyspace));
556556 }
557557 try {
558558 manager.udtCodec(Address.class);
559559 fail("Expected IllegalArgumentException");
560560 } catch (IllegalArgumentException e) {
561- assertThat(e.getMessage()).isEqualTo(String.format("Field \"ZIP_code\" does not exist in type %s.address", keyspace));
561+ assertThat(e.getMessage()).isEqualTo(String.format("Field \"ZIP_code\" does not exist in type \"%s\".address", keyspace));
562562 }
563563 }
564564
modified manual/object_mapper/creating/README.md +307 −24
@@ -17,7 +17,7 @@
1717 writeConsistency = "QUORUM",
1818 caseSensitiveKeyspace = false,
1919 caseSensitiveTable = false)
20-public static class User {
20+public class User {
2121 @PartitionKey
2222 @Column(name = "user_id")
2323 private UUID userId;
@@ -39,20 +39,155 @@
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. The default constructor
43+is allowed to be non-public, provided that the security manager, if any, grants
44+the mapper access to it via [reflection][set-accessible].
45+
46+#### Mapping table columns
47+
48+The mapping of each table column can be customized through annotations
49+placed on either a field declaration, or on a getter method of a
50+[Java bean property][java-beans]. _Annotations on setters are not
51+supported and will be silently ignored by the mapper_.
52+
53+Users are strongly encouraged to follow the Java bean property
54+conventions when designing mapped classes: if this is the case, the mapper will
55+transparently "bind" together fields and accessor methods (getters and setters)
56+into a single logical abstraction; e.g. a field named `myCol` and a Java
57+bean property named `myCol` offering a public getter named `getMyCol()`
58+will be assumed to represent the very same table column,
59+and annotations for this column are thus allowed to be placed indifferently
60+on the field declaration, or on the getter method declaration.
61+
62+The following mappings are thus equivalent:
63+
64+```java
65+@Table(name = "users")
66+public class User {
67+
68+ // annotation on a field
69+ @PartitionKey
70+ private UUID id;
71+
72+ public UUID getId() {
73+ return id;
74+ }
75+
76+ public void setId(UUID id) {
77+ this.id = id;
78+ }
79+
80+}
81+```
82+
83+```java
84+@Table(name = "users")
85+public class User {
86+
87+ private UUID id;
88+
89+ // annotation on a getter method
90+ @PartitionKey
91+ public UUID getId() {
92+ return id;
93+ }
94+
95+ public void setId(UUID id) {
96+ this.id = id;
97+ }
98+
99+}
100+
101+```
102+
103+It is recommended to adopt one strategy or the other for
104+placing annotations on class members (i.e., either always on fields, or always on getters),
105+but not both at the same time, unless strictly required.
106+Annotating fields is usually less verbose, but with polymorphic
107+data models (see below), annotating getters generally proves to be more flexible.
108+
109+If duplicated annotations for a given column are found on the field declaration
110+and on the getter method declaration, the one declared in the getter method
111+declaration wins. No warnings are generated in such situations.
112+
113+When reading or writing mapped property values, the mapper will first
114+try to invoke the property getter and setter methods, if they are available;
115+and if they are not, the mapper will try a direct access to the property's corresponding field.
116+
117+A mapped field is thus allowed to be non-public if:
118+
119+1. Reads and writes are done through its public getters and setters; or
120+2. The security manager, if any, grants the mapper access to it via [reflection][set-accessible].
121+
122+Note that, according to the [Java Beans specification][java-beans], a setter
123+must have a `void` return type; the driver, however, will consider as a setter any public method
124+having a matching signature (i.e., name and parameter types match those expected),
125+but having a different return type. This allows the usage of "fluent" setters that can
126+be chained together in a builder-pattern style:
127+
128+```java
129+@Table(name = "users")
130+public class User {
131+
132+ // fluent setters
133+
134+ public User setId(UUID id) {
135+ this.id = id;
136+ return this;
137+ }
138+
139+ public User setName(String name) {
140+ this.name = name;
141+ return this;
142+ }
143+
144+}
145+
146+// chained calls
147+User user = new User()
148+ .setId(UUIDs.random())
149+ .setName("John Doe");
150+```
45151
46152 [table]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Table.html
47153 [case-sensitive]:http://docs.datastax.com/en/cql/3.3/cql/cql_reference/ucase-lcase_r.html
48154 [consistency level]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/ConsistencyLevel.html
155+[java-beans]:https://docs.oracle.com/javase/tutorial/javabeans/writing/properties.html
156+[set-accessible]:https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/AccessibleObject.html#setAccessible-boolean-
49157
50158 #### Column names
51159
52-By default, the mapper tries to map each Java property to a
53-case insensitive column of the same name. If you want to use a different
54-name, or [case-sensitive] names, use the [@Column][column] annotation on
55-the field.
160+By default, the mapper tries to map each Java bean property to a
161+column of the same name. _The mapping is case-insensitive by default_,
162+i.e., the property `userId` would map to a column named `userid`.
163+
164+If you want to use a different name, or [case-sensitive] names,
165+use the [@Column][column] annotation.
166+
167+To specify a different column name, use the `name` attribute:
168+
169+```
170+CREATE TABLE users(id uuid PRIMARY KEY, user_name text);
171+```
172+
173+```java
174+// column name does not match field name
175+@Column(name = "user_name")
176+private String userName;
177+```
178+
179+When case-sensitive identifiers are required, use the
180+`caseSensitive` attribute:
181+
182+```
183+CREATE TABLE users(id uuid PRIMARY KEY, "userName" text);
184+```
185+
186+```java
187+// column name is case-sensitive
188+@Column(caseSensitive = true)
189+private String userName;
190+```
56191
57192 [column]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Column.html
58193
@@ -84,8 +219,8 @@
84219
85220 #### Computed fields
86221
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
222+[@Computed][computed] can be used on properties that are the result of a
223+computation on the Cassandra side, typically a function call. Native
89224 functions in Cassandra like `writetime()` or [User Defined Functions] are
90225 supported.
91226
@@ -94,7 +229,7 @@
94229 Integer ttl;
95230 ```
96231
97-The CQL return type of function must match the type of the field,
232+The CQL return type of function must match the type of the property,
98233 otherwise an exception will be thrown.
99234
100235 Computed fields are ignored when saving an entity.
@@ -108,18 +243,21 @@
108243 int f;
109244 ```
110245
111-Finally, computed fields are only supported with [basic read
246+Finally, computed properties are only supported with [basic read
112247 operations](../using/#basic-crud-operations) at this time.
113-Support in [accessors](../using/#accessors) in planned for a future
248+Support in [accessors](../using/#accessors) is planned for a future
114249 version (see
115250 [JAVA-832](https://datastax-oss.atlassian.net/browse/JAVA-832)).
116251
117252 [User Defined Functions]:http://www.planetcassandra.org/blog/user-defined-functions-in-cassandra-3-0/
118253 [computed]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Computed.html
119254
120-#### Transient fields
255+#### Transient properties
121256
122-[@Transient][transient] can be used to prevent a field from being mapped.
257+By default, the mapper will try to map all fields and Java bean properties
258+to table columns. [@Transient][transient] can be used to prevent a field or
259+a Java bean property from being mapped. Like other column-level annotations,
260+it should be placed on either the field declaration or the property getter method.
123261
124262 [transient]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Transient.html
125263
@@ -148,12 +286,14 @@
148286 - `caseSensitiveKeyspace`: whether the keyspace name is case-sensitive.
149287 - `caseSensitiveType`: whether the UDT name is case-sensitive.
150288
151-The class must provide a default constructor, and all fields (except the
152-ones annotated `@Transient`) must have corresponding setters and
153-getters.
289+The class must provide a default constructor. The default constructor
290+is allowed to be non-public, provided that the security manager, if any, grants
291+the mapper access to it via [reflection][set-accessible].
292+
293+As for table entities, properties in UDT classes are mapped to an UDT field of the same
294+name by default.
154295
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,
296+To declare a different name or use case-sensitivity,
157297 use the [@Field][field] annotation:
158298
159299 ```java
@@ -169,7 +309,7 @@
169309 ```
170310
171311 ```java
172-public static class Company {
312+public class Company {
173313 @PartitionKey
174314 @Column(name = "company_id")
175315 private UUID companyId;
@@ -178,8 +318,8 @@
178318 }
179319 ```
180320
181-(this also works with UDTs inside collections or other UDTs, with
182-arbitrary level of nesting)
321+This also works with UDTs inside collections or other UDTs, with any arbitrary
322+nesting level.
183323
184324 [User Defined Types]: ../../udts/
185325 [udt]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/UDT.html
@@ -199,7 +339,7 @@
199339 they match the schema, in anticipation for the schema generation features
200340 that will be added in a future version.
201341 The default annotation is [@Frozen][frozen], [@FrozenKey][frozenkey] and
202-[@FrozenValue][frozenvalue]` are also provided for convenience:
342+[@FrozenValue][frozenvalue] are also provided for convenience:
203343
204344 ```java
205345 // Will be mapped as a 'list<text>'
@@ -222,3 +362,146 @@
222362 [frozen]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Frozen.html
223363 [frozenkey]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/FrozenKey.html
224364 [frozenvalue]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/FrozenValue.html
365+
366+
367+### Polymorphism support
368+
369+When mapping an entity class or a UDT class, the mapper will transparently
370+scan superclasses and superinterfaces for annotations on fields and getter methods,
371+thus enabling the polymorphic mapping of one class hierarchy
372+into different CQL tables or UDTs.
373+
374+Each concrete class must correspond to a table or a UDT,
375+and should be annotated accordingly with `@Table` or `@UDT`.
376+This is analogous to the so-called "table per concrete class"
377+mapping strategy usually found in popular SQL mapping frameworks, such as Hibernate.
378+
379+Here is an example of a polymorphic mapping:
380+
381+```sql
382+CREATE TYPE point2d (x int, y int);
383+CREATE TYPE point3d (x int, y int, z int);
384+CREATE TABLE rectangles (id uuid PRIMARY KEY, bottom_left frozen<point2d>, top_right frozen<point2d>);
385+CREATE TABLE spheres (id uuid PRIMARY KEY, center frozen<point3d>, radius double);
386+```
387+
388+```java
389+@UDT(name = "point2d")
390+public class Point2D {
391+ public int x;
392+ public int y;
393+}
394+
395+@UDT(name = "point3d")
396+public class Point3D extends Point2D {
397+ public int z;
398+}
399+
400+public interface Shape2D {
401+
402+ @Transient
403+ double getArea();
404+
405+}
406+
407+public interface Shape3D {
408+
409+ @Transient
410+ double getVolume();
411+
412+}
413+
414+public abstract class Shape {
415+
416+ private UUID id;
417+
418+ @PartitionKey
419+ public UUID getId() {
420+ return id;
421+ }
422+
423+ public void setId(UUID id) {
424+ this.id = id;
425+ }
426+
427+}
428+
429+@Table(name = "rectangles")
430+public class Rectangle extends Shape implements Shape2D {
431+
432+ private Point2D bottomLeft;
433+ private Point2D topRight;
434+
435+ @Column(name = "bottom_left")
436+ @Frozen
437+ public Point2D getBottomLeft() {
438+ return bottomLeft;
439+ }
440+
441+ public void setBottomLeft(Point2D bottomLeft) {
442+ this.bottomLeft = bottomLeft;
443+ }
444+
445+ @Column(name = "top_right")
446+ @Frozen
447+ public Point2D getTopRight() {
448+ return topRight;
449+ }
450+
451+ public void setTopRight(Point2D topRight) {
452+ this.topRight = topRight;
453+ }
454+
455+ @Transient
456+ public double getWidth() {
457+ return Math.abs(topRight.x - bottomLeft.x);
458+ }
459+
460+ @Transient
461+ public double getHeight() {
462+ return Math.abs(topRight.y - bottomLeft.y);
463+ }
464+
465+ @Override
466+ public double getArea() {
467+ return getWidth() * getHeight();
468+ }
469+
470+}
471+
472+@Table(name = "spheres")
473+public class Sphere extends Shape implements Shape3D {
474+
475+ private Point3D center;
476+ private double radius;
477+
478+ @Frozen
479+ public Point3D getCenter() {
480+ return center;
481+ }
482+
483+ public void setCenter(Point3D center) {
484+ this.center = center;
485+ }
486+
487+ public double getRadius() {
488+ return radius;
489+ }
490+
491+ public void setRadius(double radius) {
492+ this.radius = radius;
493+ }
494+
495+ @Override
496+ public double getVolume() {
497+ return 4d / 3d * Math.PI * Math.pow(getRadius(), 3);
498+ }
499+
500+}
501+```
502+
503+One powerful advantage of annotating getter methods is that
504+annotations are inherited from overridden methods in superclasses and superinterfaces;
505+in other words, if a getter method is overridden in a subclass, annotations in both
506+method declarations will get merged together. If duplicated annotations are found during this merge
507+process, the overriding method's annotations will take precedence over the overridden's.