kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | 62c2dfe00652c1df897e2af4f7f901b5a6e28b710c7aacb4a36e7d0f5104e491 |
|---|---|
| Author | Alexandre Dutra <adutra@users.noreply.github.com> · 2016-07-22 18:52 +02:00 |
| Committer | Olivier Michallat <olim7t@users.noreply.github.com> · 2016-07-22 09:52 -07:00 |
| Parents | 4c920eab788b |
37 files changed
modified changelog/README.md +3 −0
| @@ -10,6 +10,9 @@ | ||
| 10 | 10 | - [new feature] JAVA-1157: Allow asynchronous paging of Mapper Result. |
| 11 | 11 | - [improvement] JAVA-1212: Don't retry non-idempotent statements by default. |
| 12 | 12 | - [improvement] JAVA-1192: Make EventDebouncer settings updatable at runtime. |
| 13 | +- [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. | |
| 13 | 16 | |
| 14 | 17 | Merged from 3.0.x branch: |
| 15 | 18 |
modified clirr-ignores.xml +7 −0
| @@ -13,6 +13,13 @@ | ||
| 13 | 13 | --> |
| 14 | 14 | <differences> |
| 15 | 15 | |
| 16 | + <difference> | |
| 17 | + <differenceType>8001</differenceType> <!-- class removed --> | |
| 18 | + <className>com/datastax/driver/mapping/ColumnMapper$Kind</className> | |
| 19 | + <justification>False positive, the enclosing class is package-private so this was never exposed</justification> | |
| 20 | + </difference> | |
| 21 | + | |
| 22 | + | |
| 16 | 23 | <difference> |
| 17 | 24 | <differenceType>1001</differenceType> <!-- decreased visibility --> |
| 18 | 25 | <className>com/datastax/driver/mapping/ColumnMapper$Kind</className> |
modified driver-core/src/main/java/com/datastax/driver/core/ClusteringOrder.java +1 −1
| @@ -25,4 +25,4 @@ | ||
| 25 | 25 | |
| 26 | 26 | ASC, DESC; |
| 27 | 27 | |
| 28 | -} | |
| 28 | +} | |
| No newline at the end of the file |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/AccessorMapper.java +19 −9
| @@ -19,22 +19,35 @@ | ||
| 19 | 19 | import com.google.common.util.concurrent.Futures; |
| 20 | 20 | import com.google.common.util.concurrent.ListenableFuture; |
| 21 | 21 | |
| 22 | +import java.lang.reflect.Proxy; | |
| 22 | 23 | import java.util.ArrayList; |
| 23 | 24 | import java.util.List; |
| 24 | 25 | |
| 25 | -abstract class AccessorMapper<T> { | |
| 26 | +class AccessorMapper<T> { | |
| 26 | 27 | |
| 27 | - public final Class<T> daoClass; | |
| 28 | - protected final List<MethodMapper> methods; | |
| 28 | + final Class<T> daoClass; | |
| 29 | + final List<MethodMapper> methods; | |
| 30 | + private final Class<T>[] proxyClasses; | |
| 31 | + private final AccessorInvocationHandler<T> handler; | |
| 29 | 32 | |
| 30 | - protected AccessorMapper(Class<T> daoClass, List<MethodMapper> methods) { | |
| 33 | + @SuppressWarnings({"unchecked", "rawtypes"}) | |
| 34 | + AccessorMapper(Class<T> daoClass, List<MethodMapper> methods) { | |
| 31 | 35 | this.daoClass = daoClass; |
| 32 | 36 | this.methods = methods; |
| 37 | + this.proxyClasses = (Class<T>[]) new Class[]{daoClass}; | |
| 38 | + this.handler = new AccessorInvocationHandler<T>(this); | |
| 33 | 39 | } |
| 34 | 40 | |
| 35 | - abstract T createProxy(); | |
| 41 | + @SuppressWarnings("unchecked") | |
| 42 | + T createProxy() { | |
| 43 | + try { | |
| 44 | + return (T) Proxy.newProxyInstance(daoClass.getClassLoader(), proxyClasses, handler); | |
| 45 | + } catch (Exception e) { | |
| 46 | + throw new RuntimeException("Cannot create instance for Accessor interface " + daoClass.getName()); | |
| 47 | + } | |
| 48 | + } | |
| 36 | 49 | |
| 37 | - public void prepare(MappingManager manager) { | |
| 50 | + void prepare(MappingManager manager) { | |
| 38 | 51 | List<ListenableFuture<PreparedStatement>> statements = new ArrayList<ListenableFuture<PreparedStatement>>(methods.size()); |
| 39 | 52 | |
| 40 | 53 | for (MethodMapper method : methods) |
| @@ -49,7 +62,4 @@ | ||
| 49 | 62 | } |
| 50 | 63 | } |
| 51 | 64 | |
| 52 | - interface Factory { | |
| 53 | - public <T> AccessorMapper<T> create(Class<T> daoClass, List<MethodMapper> methods); | |
| 54 | - } | |
| 55 | 65 | } |
deleted driver-mapping/src/main/java/com/datastax/driver/mapping/AccessorReflectionMapper.java +0 −55
| @@ -1,55 +0,0 @@ | ||
| 1 | -/* | |
| 2 | - * Copyright (C) 2012-2015 DataStax Inc. | |
| 3 | - * | |
| 4 | - * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | - * you may not use this file except in compliance with the License. | |
| 6 | - * You may obtain a copy of the License at | |
| 7 | - * | |
| 8 | - * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | - * | |
| 10 | - * Unless required by applicable law or agreed to in writing, software | |
| 11 | - * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | - * See the License for the specific language governing permissions and | |
| 14 | - * limitations under the License. | |
| 15 | - */ | |
| 16 | -package com.datastax.driver.mapping; | |
| 17 | - | |
| 18 | -import java.lang.reflect.Proxy; | |
| 19 | -import java.util.List; | |
| 20 | - | |
| 21 | -class AccessorReflectionMapper<T> extends AccessorMapper<T> { | |
| 22 | - | |
| 23 | - private static AccessorReflectionFactory factory = new AccessorReflectionFactory(); | |
| 24 | - | |
| 25 | - private final Class<T>[] proxyClasses; | |
| 26 | - private final AccessorInvocationHandler<T> handler; | |
| 27 | - | |
| 28 | - @SuppressWarnings({"unchecked", "rawtypes"}) | |
| 29 | - private AccessorReflectionMapper(Class<T> daoClass, List<MethodMapper> methods) { | |
| 30 | - super(daoClass, methods); | |
| 31 | - this.proxyClasses = (Class<T>[]) new Class[]{daoClass}; | |
| 32 | - this.handler = new AccessorInvocationHandler<T>(this); | |
| 33 | - } | |
| 34 | - | |
| 35 | - public static Factory factory() { | |
| 36 | - return factory; | |
| 37 | - } | |
| 38 | - | |
| 39 | - @SuppressWarnings("unchecked") | |
| 40 | - @Override | |
| 41 | - public T createProxy() { | |
| 42 | - try { | |
| 43 | - return (T) Proxy.newProxyInstance(daoClass.getClassLoader(), proxyClasses, handler); | |
| 44 | - } catch (Exception e) { | |
| 45 | - throw new RuntimeException("Cannot create instance for Accessor interface " + daoClass.getName()); | |
| 46 | - } | |
| 47 | - } | |
| 48 | - | |
| 49 | - private static class AccessorReflectionFactory implements Factory { | |
| 50 | - @Override | |
| 51 | - public <T> AccessorMapper<T> create(Class<T> daoClass, List<MethodMapper> methods) { | |
| 52 | - return new AccessorReflectionMapper<T>(daoClass, methods); | |
| 53 | - } | |
| 54 | - } | |
| 55 | -} |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/AnnotationChecks.java +45 −25
| @@ -15,11 +15,15 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.mapping; |
| 17 | 17 | |
| 18 | +import com.datastax.driver.mapping.annotations.Column; | |
| 18 | 19 | import com.datastax.driver.mapping.annotations.Computed; |
| 19 | 20 | import com.datastax.driver.mapping.annotations.Table; |
| 20 | 21 | |
| 21 | 22 | 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; | |
| 23 | 27 | |
| 24 | 28 | /** |
| 25 | 29 | * Various checks on mapping annotations. |
| @@ -36,8 +40,8 @@ | ||
| 36 | 40 | static <T extends Annotation> T getTypeAnnotation(Class<T> annotation, Class<?> annotatedClass) { |
| 37 | 41 | T instance = annotatedClass.getAnnotation(annotation); |
| 38 | 42 | 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)); | |
| 41 | 45 | |
| 42 | 46 | // Check that no other mapping annotations are present |
| 43 | 47 | validateAnnotations(annotatedClass, annotation); |
| @@ -45,50 +49,66 @@ | ||
| 45 | 49 | return instance; |
| 46 | 50 | } |
| 47 | 51 | |
| 52 | + @SuppressWarnings("unchecked") | |
| 48 | 53 | private static void validateAnnotations(Class<?> clazz, Class<? extends Annotation> allowed) { |
| 49 | 54 | @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)); | |
| 51 | 58 | 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", | |
| 53 | 60 | allowed.getSimpleName(), invalid.getSimpleName(), |
| 54 | - clazz.getName())); | |
| 61 | + clazz)); | |
| 55 | 62 | } |
| 56 | 63 | |
| 57 | 64 | /** |
| 58 | 65 | * Checks that a field is only annotated with the given mapping annotations, and that its "frozen" annotations are valid. |
| 59 | 66 | */ |
| 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'", | |
| 64 | 71 | invalid.getSimpleName(), |
| 65 | - field.getName(), classDescription, | |
| 66 | - field.getDeclaringClass().getName())); | |
| 67 | - | |
| 68 | - checkValidComputed(field); | |
| 72 | + property)); | |
| 73 | + } | |
| 74 | + checkValidPrimaryKey(property); | |
| 75 | + checkValidComputed(property); | |
| 69 | 76 | } |
| 70 | 77 | |
| 71 | 78 | // 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) { | |
| 73 | 80 | for (Annotation annotation : annotations) { |
| 74 | 81 | 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)) | |
| 76 | 83 | return actual; |
| 77 | 84 | } |
| 78 | 85 | return null; |
| 79 | 86 | } |
| 80 | 87 | |
| 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 | + } | |
| 86 | 103 | } |
| 87 | 104 | |
| 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)); | |
| 92 | 112 | } |
| 93 | 113 | } |
| 94 | 114 | } |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/AnnotationParser.java +114 −208
| @@ -16,286 +16,193 @@ | ||
| 16 | 16 | package com.datastax.driver.mapping; |
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.ConsistencyLevel; |
| 19 | +import com.datastax.driver.core.Metadata; | |
| 19 | 20 | import com.datastax.driver.core.TableMetadata; |
| 20 | 21 | import com.datastax.driver.core.TypeCodec; |
| 21 | 22 | import com.datastax.driver.core.UserType; |
| 22 | 23 | import com.datastax.driver.mapping.MethodMapper.ParamMapper; |
| 23 | 24 | import com.datastax.driver.mapping.annotations.*; |
| 24 | 25 | import com.google.common.base.Strings; |
| 25 | -import com.google.common.collect.Maps; | |
| 26 | +import com.google.common.collect.ImmutableSet; | |
| 26 | 27 | import com.google.common.reflect.TypeToken; |
| 27 | 28 | |
| 29 | +import java.beans.PropertyDescriptor; | |
| 28 | 30 | 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; | |
| 31 | 34 | import java.util.*; |
| 32 | 35 | import java.util.concurrent.atomic.AtomicInteger; |
| 33 | 36 | |
| 34 | -import static com.datastax.driver.core.Metadata.quote; | |
| 35 | - | |
| 36 | 37 | /** |
| 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. | |
| 38 | 42 | */ |
| 43 | +@SuppressWarnings({"unchecked", "WeakerAccess"}) | |
| 39 | 44 | class AnnotationParser { |
| 40 | 45 | |
| 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>() { | |
| 42 | 70 | @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; | |
| 45 | 73 | } |
| 46 | 74 | }; |
| 47 | 75 | |
| 48 | 76 | private AnnotationParser() { |
| 49 | 77 | } |
| 50 | 78 | |
| 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) { | |
| 52 | 80 | Table table = AnnotationChecks.getTypeAnnotation(Table.class, entityClass); |
| 53 | 81 | |
| 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(); | |
| 56 | 84 | |
| 57 | 85 | ConsistencyLevel writeConsistency = table.writeConsistency().isEmpty() ? null : ConsistencyLevel.valueOf(table.writeConsistency().toUpperCase()); |
| 58 | 86 | ConsistencyLevel readConsistency = table.readConsistency().isEmpty() ? null : ConsistencyLevel.valueOf(table.readConsistency().toUpperCase()); |
| 59 | 87 | |
| 60 | 88 | 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)) | |
| 63 | 91 | 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 | |
| 67 | 94 | )); |
| 95 | + ksName = Metadata.quote(loggedKeyspace); | |
| 68 | 96 | } |
| 69 | 97 | |
| 70 | - EntityMapper<T> mapper = factory.create(entityClass, ksName, tableName, writeConsistency, readConsistency); | |
| 98 | + EntityMapper<T> mapper = new EntityMapper<T>(entityClass, ksName, tableName, writeConsistency, readConsistency); | |
| 71 | 99 | TableMetadata tableMetadata = mappingManager.getSession().getCluster().getMetadata().getKeyspace(ksName).getTable(tableName); |
| 72 | 100 | |
| 73 | 101 | if (tableMetadata == null) |
| 74 | 102 | throw new IllegalArgumentException(String.format("Table %s does not exist in keyspace %s", tableName, ksName)); |
| 75 | 103 | |
| 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>(); | |
| 79 | 107 | |
| 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); | |
| 83 | 121 | |
| 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"); | |
| 86 | 124 | |
| 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); | |
| 90 | 126 | |
| 91 | - if (field.getAnnotation(Transient.class) != null) | |
| 127 | + if (propertyMapper.isTransient()) | |
| 92 | 128 | continue; |
| 93 | 129 | |
| 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); | |
| 106 | 140 | |
| 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 | + } | |
| 108 | 145 | |
| 109 | - Collections.sort(pks, fieldComparator); | |
| 110 | - Collections.sort(ccs, fieldComparator); | |
| 146 | + Collections.sort(pks, POSITION_COMPARATOR); | |
| 147 | + Collections.sort(ccs, POSITION_COMPARATOR); | |
| 111 | 148 | |
| 112 | - validateOrder(pks, "@PartitionKey"); | |
| 113 | - validateOrder(ccs, "@ClusteringColumn"); | |
| 149 | + AnnotationChecks.validateOrder(pks, "@PartitionKey"); | |
| 150 | + AnnotationChecks.validateOrder(ccs, "@ClusteringColumn"); | |
| 114 | 151 | |
| 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); | |
| 119 | 153 | return mapper; |
| 120 | 154 | } |
| 121 | 155 | |
| 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) { | |
| 138 | 157 | UDT udt = AnnotationChecks.getTypeAnnotation(UDT.class, udtClass); |
| 139 | 158 | |
| 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(); | |
| 142 | 161 | |
| 143 | 162 | 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)) | |
| 146 | 165 | 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 | |
| 150 | 168 | )); |
| 169 | + ksName = Metadata.quote(loggedKeyspace); | |
| 151 | 170 | } |
| 152 | 171 | |
| 153 | 172 | UserType userType = mappingManager.getSession().getCluster().getMetadata().getKeyspace(ksName).getUserType(udtName); |
| 154 | 173 | if (userType == null) |
| 155 | 174 | throw new IllegalArgumentException(String.format("User type %s does not exist in keyspace %s", udtName, ksName)); |
| 156 | 175 | |
| 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>(); | |
| 219 | 177 | |
| 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); | |
| 238 | 179 | |
| 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()) { | |
| 248 | 181 | |
| 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]; | |
| 253 | 185 | |
| 254 | - if (computedField != null) { | |
| 255 | - return computedField.value(); | |
| 256 | - } | |
| 186 | + PropertyMapper propertyMapper = new PropertyMapper(udtClass, propertyName, null, field, property); | |
| 257 | 187 | |
| 258 | - return field.getName().toLowerCase(); | |
| 259 | - } | |
| 188 | + AnnotationChecks.validateAnnotations(propertyMapper, VALID_FIELD_ANNOTATIONS); | |
| 260 | 189 | |
| 261 | - public static String newAlias(Field field, int columnNumber) { | |
| 262 | - return "col" + columnNumber; | |
| 190 | + if (propertyMapper.isTransient()) | |
| 191 | + continue; | |
| 263 | 192 | |
| 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())); | |
| 265 | 196 | |
| 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); | |
| 281 | 198 | } |
| 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(); | |
| 292 | 199 | |
| 293 | - return Defaults.NoCodec.class; | |
| 200 | + return new MappedUDTCodec<T>(userType, udtClass, propertyMappers, mappingManager); | |
| 294 | 201 | } |
| 295 | 202 | |
| 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) { | |
| 297 | 204 | 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); | |
| 299 | 206 | |
| 300 | 207 | AnnotationChecks.getTypeAnnotation(Accessor.class, accClass); |
| 301 | 208 | |
| @@ -332,7 +239,7 @@ | ||
| 332 | 239 | else if (allParamsNamed != thisParamNamed) |
| 333 | 240 | throw new IllegalArgumentException(String.format("For method '%s', either all or none of the parameters must be named", m.getName())); |
| 334 | 241 | |
| 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); | |
| 336 | 243 | } |
| 337 | 244 | |
| 338 | 245 | ConsistencyLevel cl = null; |
| @@ -346,7 +253,7 @@ | ||
| 346 | 253 | fetchSize = options.fetchSize(); |
| 347 | 254 | tracing = options.tracing(); |
| 348 | 255 | 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"); | |
| 350 | 257 | } |
| 351 | 258 | idempotent = options.idempotent().length == 0 ? null : options.idempotent()[0]; |
| 352 | 259 | } |
| @@ -354,11 +261,10 @@ | ||
| 354 | 261 | methods.add(new MethodMapper(m, queryString, paramMappers, cl, fetchSize, tracing, idempotent)); |
| 355 | 262 | } |
| 356 | 263 | |
| 357 | - return factory.create(accClass, methods); | |
| 264 | + return new AccessorMapper<T>(accClass, methods); | |
| 358 | 265 | } |
| 359 | 266 | |
| 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) { | |
| 362 | 268 | if (paramType instanceof Class) { |
| 363 | 269 | Class<?> paramClass = (Class<?>) paramType; |
| 364 | 270 | 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 @@ | ||
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.ConsistencyLevel; |
| 19 | 19 | |
| 20 | -import java.lang.reflect.Field; | |
| 21 | 20 | import java.util.ArrayList; |
| 22 | 21 | import java.util.List; |
| 23 | -import java.util.concurrent.atomic.AtomicInteger; | |
| 24 | 22 | |
| 25 | -import static com.datastax.driver.core.querybuilder.QueryBuilder.quote; | |
| 23 | +class EntityMapper<T> { | |
| 26 | 24 | |
| 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; | |
| 32 | 28 | |
| 33 | 29 | final ConsistencyLevel writeConsistency; |
| 34 | 30 | final ConsistencyLevel readConsistency; |
| 35 | 31 | |
| 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>(); | |
| 39 | 34 | |
| 40 | - private final List<ColumnMapper<T>> allColumns = new ArrayList<ColumnMapper<T>>(); | |
| 35 | + final List<PropertyMapper> allColumns = new ArrayList<PropertyMapper>(); | |
| 41 | 36 | |
| 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) { | |
| 43 | 38 | this.entityClass = entityClass; |
| 44 | 39 | this.keyspace = keyspace; |
| 45 | 40 | this.table = table; |
| @@ -47,46 +42,24 @@ | ||
| 47 | 42 | this.readConsistency = readConsistency; |
| 48 | 43 | } |
| 49 | 44 | |
| 50 | - String getKeyspace() { | |
| 51 | - return quote(keyspace); | |
| 52 | - } | |
| 53 | - | |
| 54 | - String getTable() { | |
| 55 | - return quote(table); | |
| 56 | - } | |
| 57 | - | |
| 58 | 45 | int primaryKeySize() { |
| 59 | 46 | return partitionKeys.size() + clusteringColumns.size(); |
| 60 | 47 | } |
| 61 | 48 | |
| 62 | - ColumnMapper<T> getPrimaryKeyColumn(int i) { | |
| 49 | + PropertyMapper getPrimaryKeyColumn(int i) { | |
| 63 | 50 | return i < partitionKeys.size() ? partitionKeys.get(i) : clusteringColumns.get(i - partitionKeys.size()); |
| 64 | 51 | } |
| 65 | 52 | |
| 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) { | |
| 67 | 54 | partitionKeys.addAll(pks); |
| 68 | - allColumns.addAll(pks); | |
| 69 | - | |
| 70 | 55 | clusteringColumns.addAll(ccs); |
| 56 | + allColumns.addAll(pks); | |
| 71 | 57 | allColumns.addAll(ccs); |
| 72 | - | |
| 73 | - addColumns(rgs); | |
| 74 | - } | |
| 75 | - | |
| 76 | - void addColumns(List<ColumnMapper<T>> rgs) { | |
| 77 | - regularColumns.addAll(rgs); | |
| 78 | 58 | allColumns.addAll(rgs); |
| 79 | 59 | } |
| 80 | 60 | |
| 81 | - abstract T newEntity(); | |
| 82 | - | |
| 83 | - List<ColumnMapper<T>> allColumns() { | |
| 84 | - return allColumns; | |
| 61 | + T newEntity() { | |
| 62 | + return ReflectionUtils.newInstance(entityClass); | |
| 85 | 63 | } |
| 86 | 64 | |
| 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 | - } | |
| 92 | 65 | } |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MappedUDTCodec.java +17 −25
| @@ -15,7 +15,10 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.mapping; |
| 17 | 17 | |
| 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; | |
| 19 | 22 | |
| 20 | 23 | import java.nio.ByteBuffer; |
| 21 | 24 | import java.util.Map; |
| @@ -26,10 +29,10 @@ | ||
| 26 | 29 | class MappedUDTCodec<T> extends TypeCodec.AbstractUDTCodec<T> { |
| 27 | 30 | private final UserType cqlUserType; |
| 28 | 31 | private final Class<T> udtClass; |
| 29 | - private final Map<String, ColumnMapper<T>> columnMappers; | |
| 32 | + private final Map<String, PropertyMapper> columnMappers; | |
| 30 | 33 | private final CodecRegistry codecRegistry; |
| 31 | 34 | |
| 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) { | |
| 33 | 36 | super(cqlUserType, udtClass); |
| 34 | 37 | this.cqlUserType = cqlUserType; |
| 35 | 38 | this.udtClass = udtClass; |
| @@ -39,11 +42,7 @@ | ||
| 39 | 42 | |
| 40 | 43 | @Override |
| 41 | 44 | 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); | |
| 47 | 46 | } |
| 48 | 47 | |
| 49 | 48 | Class<T> getUdtClass() { |
| @@ -52,35 +51,28 @@ | ||
| 52 | 51 | |
| 53 | 52 | @Override |
| 54 | 53 | 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); | |
| 58 | 55 | |
| 59 | - ColumnMapper<T> columnMapper = columnMappers.get(fieldName); | |
| 60 | - | |
| 61 | - if (columnMapper == null) | |
| 56 | + if (propertyMapper == null) | |
| 62 | 57 | return null; |
| 63 | 58 | |
| 64 | - Object value = columnMapper.getValue(source); | |
| 59 | + Object value = propertyMapper.getValue(source); | |
| 65 | 60 | |
| 66 | - TypeCodec<Object> codec = columnMapper.getCustomCodec(); | |
| 61 | + TypeCodec<Object> codec = propertyMapper.customCodec; | |
| 67 | 62 | if (codec == null) |
| 68 | - codec = codecRegistry.codecFor(cqlUserType.getFieldType(columnMapper.getColumnName()), columnMapper.getJavaType()); | |
| 63 | + codec = codecRegistry.codecFor(cqlUserType.getFieldType(propertyMapper.columnName), propertyMapper.javaType); | |
| 69 | 64 | |
| 70 | 65 | return codec.serialize(value, protocolVersion); |
| 71 | 66 | } |
| 72 | 67 | |
| 73 | 68 | @Override |
| 74 | 69 | 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; | |
| 81 | 73 | 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)); | |
| 84 | 76 | } |
| 85 | 77 | return target; |
| 86 | 78 | } |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/Mapper.java +27 −29
| @@ -49,11 +49,10 @@ | ||
| 49 | 49 | private static final Logger logger = LoggerFactory.getLogger(Mapper.class); |
| 50 | 50 | private static final Function<Object, Void> TO_NULL = Functions.constant(null); |
| 51 | 51 | |
| 52 | - final MappingManager manager; | |
| 53 | - final ProtocolVersion protocolVersion; | |
| 54 | - final Class<T> klass; | |
| 55 | - final EntityMapper<T> mapper; | |
| 56 | - final TableMetadata tableMetadata; | |
| 52 | + private final MappingManager manager; | |
| 53 | + private final Class<T> klass; | |
| 54 | + private final EntityMapper<T> mapper; | |
| 55 | + private final TableMetadata tableMetadata; | |
| 57 | 56 | |
| 58 | 57 | // Cache prepared statements for each type of query we use. |
| 59 | 58 | private final ConcurrentMap<MapperQueryKey, ListenableFuture<PreparedStatement>> preparedQueries = new ConcurrentHashMap<MapperQueryKey, ListenableFuture<PreparedStatement>>(); |
| @@ -64,7 +63,7 @@ | ||
| 64 | 63 | |
| 65 | 64 | private static final EnumMap<Option.Type, Option> NO_OPTIONS = new EnumMap<Option.Type, Option>(Option.Type.class); |
| 66 | 65 | |
| 67 | - final Function<ResultSet, T> mapOneFunction; | |
| 66 | + private final Function<ResultSet, T> mapOneFunction; | |
| 68 | 67 | final Function<ResultSet, T> mapOneFunctionWithoutAliases; |
| 69 | 68 | final Function<ResultSet, Result<T>> mapAllFunctionWithoutAliases; |
| 70 | 69 | |
| @@ -73,10 +72,9 @@ | ||
| 73 | 72 | this.klass = klass; |
| 74 | 73 | this.mapper = mapper; |
| 75 | 74 | |
| 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); | |
| 78 | 77 | |
| 79 | - this.protocolVersion = manager.getSession().getCluster().getConfiguration().getProtocolOptions().getProtocolVersion(); | |
| 80 | 78 | this.mapOneFunction = new Function<ResultSet, T>() { |
| 81 | 79 | @Override |
| 82 | 80 | public T apply(ResultSet rs) { |
| @@ -105,7 +103,7 @@ | ||
| 105 | 103 | return manager.getSession(); |
| 106 | 104 | } |
| 107 | 105 | |
| 108 | - ListenableFuture<PreparedStatement> getPreparedQueryAsync(QueryType type, Set<ColumnMapper<?>> columns, EnumMap<Option.Type, Option> options) { | |
| 106 | + ListenableFuture<PreparedStatement> getPreparedQueryAsync(QueryType type, Set<PropertyMapper> columns, EnumMap<Option.Type, Option> options) { | |
| 109 | 107 | |
| 110 | 108 | final MapperQueryKey pqk = new MapperQueryKey(type, columns, options); |
| 111 | 109 | ListenableFuture<PreparedStatement> existingFuture = preparedQueries.get(pqk); |
| @@ -139,7 +137,7 @@ | ||
| 139 | 137 | } |
| 140 | 138 | |
| 141 | 139 | ListenableFuture<PreparedStatement> getPreparedQueryAsync(QueryType type, EnumMap<Option.Type, Option> options) { |
| 142 | - return getPreparedQueryAsync(type, Collections.<ColumnMapper<?>>emptySet(), options); | |
| 140 | + return getPreparedQueryAsync(type, Collections.<PropertyMapper>emptySet(), options); | |
| 143 | 141 | } |
| 144 | 142 | |
| 145 | 143 | Class<T> getMappedClass() { |
| @@ -213,13 +211,13 @@ | ||
| 213 | 211 | } |
| 214 | 212 | |
| 215 | 213 | private ListenableFuture<BoundStatement> saveQueryAsync(T entity, final EnumMap<Option.Type, Option> options) { |
| 216 | - final Map<ColumnMapper<?>, Object> values = new HashMap<ColumnMapper<?>, Object>(); | |
| 214 | + final Map<PropertyMapper, Object> values = new HashMap<PropertyMapper, Object>(); | |
| 217 | 215 | boolean saveNullFields = shouldSaveNullFields(options); |
| 218 | 216 | |
| 219 | - for (ColumnMapper<T> cm : mapper.allColumns()) { | |
| 220 | - Object value = cm.getValue(entity); | |
| 221 | - if (cm.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); | |
| 223 | 221 | } |
| 224 | 222 | } |
| 225 | 223 | |
| @@ -228,8 +226,8 @@ | ||
| 228 | 226 | public BoundStatement apply(PreparedStatement input) { |
| 229 | 227 | BoundStatement bs = input.bind(); |
| 230 | 228 | int i = 0; |
| 231 | - for (Map.Entry<ColumnMapper<?>, Object> entry : values.entrySet()) { | |
| 232 | - ColumnMapper<?> mapper = entry.getKey(); | |
| 229 | + for (Map.Entry<PropertyMapper, Object> entry : values.entrySet()) { | |
| 230 | + PropertyMapper mapper = entry.getKey(); | |
| 233 | 231 | Object value = entry.getValue(); |
| 234 | 232 | setObject(bs, i++, value, mapper); |
| 235 | 233 | } |
| @@ -252,12 +250,12 @@ | ||
| 252 | 250 | return option == null || option.saveNullFields; |
| 253 | 251 | } |
| 254 | 252 | |
| 255 | - private static void setObject(BoundStatement bs, int i, Object value, ColumnMapper<?> mapper) { | |
| 256 | - TypeCodec<Object> customCodec = mapper.getCustomCodec(); | |
| 253 | + private static void setObject(BoundStatement bs, int i, Object value, PropertyMapper mapper) { | |
| 254 | + TypeCodec<Object> customCodec = mapper.customCodec; | |
| 257 | 255 | if (customCodec != null) |
| 258 | 256 | bs.set(i, value, customCodec); |
| 259 | 257 | else |
| 260 | - bs.set(i, value, mapper.getJavaType()); | |
| 258 | + bs.set(i, value, mapper.javaType); | |
| 261 | 259 | } |
| 262 | 260 | |
| 263 | 261 | /** |
| @@ -390,9 +388,9 @@ | ||
| 390 | 388 | BoundStatement bs = new MapperBoundStatement(input); |
| 391 | 389 | int i = 0; |
| 392 | 390 | for (Object value : primaryKeys) { |
| 393 | - ColumnMapper<T> column = mapper.getPrimaryKeyColumn(i); | |
| 391 | + PropertyMapper column = mapper.getPrimaryKeyColumn(i); | |
| 394 | 392 | if (value == null) { |
| 395 | - throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i)); | |
| 393 | + throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.columnName, i)); | |
| 396 | 394 | } |
| 397 | 395 | setObject(bs, i++, value, column); |
| 398 | 396 | } |
| @@ -599,9 +597,9 @@ | ||
| 599 | 597 | |
| 600 | 598 | int columnNumber = 0; |
| 601 | 599 | for (Object value : primaryKey) { |
| 602 | - ColumnMapper<T> column = mapper.getPrimaryKeyColumn(columnNumber); | |
| 600 | + PropertyMapper column = mapper.getPrimaryKeyColumn(columnNumber); | |
| 603 | 601 | if (value == null) { |
| 604 | - throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i)); | |
| 602 | + throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.columnName, i)); | |
| 605 | 603 | } |
| 606 | 604 | setObject(bs, i++, value, column); |
| 607 | 605 | columnNumber++; |
| @@ -1130,14 +1128,14 @@ | ||
| 1130 | 1128 | private static class MapperQueryKey { |
| 1131 | 1129 | private final QueryType queryType; |
| 1132 | 1130 | private final EnumSet<Option.Type> optionTypes; |
| 1133 | - private final Set<ColumnMapper<?>> columns; | |
| 1131 | + private final Set<PropertyMapper> columns; | |
| 1134 | 1132 | |
| 1135 | - MapperQueryKey(QueryType queryType, Set<ColumnMapper<?>> columnMappers, EnumMap<Option.Type, Option> options) { | |
| 1133 | + MapperQueryKey(QueryType queryType, Set<PropertyMapper> propertyMappers, EnumMap<Option.Type, Option> options) { | |
| 1136 | 1134 | Preconditions.checkNotNull(queryType); |
| 1137 | 1135 | Preconditions.checkNotNull(options); |
| 1138 | - Preconditions.checkNotNull(columnMappers); | |
| 1136 | + Preconditions.checkNotNull(propertyMappers); | |
| 1139 | 1137 | this.queryType = queryType; |
| 1140 | - this.columns = columnMappers; | |
| 1138 | + this.columns = propertyMappers; | |
| 1141 | 1139 | this.optionTypes = EnumSet.noneOf(Option.Type.class); |
| 1142 | 1140 | for (Option opt : options.values()) { |
| 1143 | 1141 | if (opt.isIncludedInQuery()) |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MappingManager.java +3 −3
| @@ -223,7 +223,7 @@ | ||
| 223 | 223 | synchronized (mappers) { |
| 224 | 224 | mapper = (Mapper<T>) mappers.get(klass); |
| 225 | 225 | if (mapper == null) { |
| 226 | - EntityMapper<T> entityMapper = AnnotationParser.parseEntity(klass, ReflectionMapper.factory(), this); | |
| 226 | + EntityMapper<T> entityMapper = AnnotationParser.parseEntity(klass, this); | |
| 227 | 227 | mapper = new Mapper<T>(this, klass, entityMapper); |
| 228 | 228 | Map<Class<?>, Mapper<?>> newMappers = new HashMap<Class<?>, Mapper<?>>(mappers); |
| 229 | 229 | newMappers.put(klass, mapper); |
| @@ -241,7 +241,7 @@ | ||
| 241 | 241 | synchronized (udtCodecs) { |
| 242 | 242 | codec = (MappedUDTCodec<T>) udtCodecs.get(mappedClass); |
| 243 | 243 | if (codec == null) { |
| 244 | - codec = AnnotationParser.parseUDT(mappedClass, ReflectionMapper.factory(), this); | |
| 244 | + codec = AnnotationParser.parseUDT(mappedClass, this); | |
| 245 | 245 | session.getCluster().getConfiguration().getCodecRegistry().register(codec); |
| 246 | 246 | |
| 247 | 247 | HashMap<Class<?>, MappedUDTCodec<?>> newCodecs = new HashMap<Class<?>, MappedUDTCodec<?>>(udtCodecs); |
| @@ -260,7 +260,7 @@ | ||
| 260 | 260 | synchronized (accessors) { |
| 261 | 261 | accessor = (T) accessors.get(klass); |
| 262 | 262 | if (accessor == null) { |
| 263 | - AccessorMapper<T> mapper = AnnotationParser.parseAccessor(klass, AccessorReflectionMapper.factory(), this); | |
| 263 | + AccessorMapper<T> mapper = AnnotationParser.parseAccessor(klass, this); | |
| 264 | 264 | mapper.prepare(this); |
| 265 | 265 | accessor = mapper.createProxy(); |
| 266 | 266 | Map<Class<?>, Object> newAccessors = new HashMap<Class<?>, Object>(accessors); |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MethodMapper.java +6 −9
| @@ -26,13 +26,11 @@ | ||
| 26 | 26 | import java.lang.reflect.Type; |
| 27 | 27 | import java.util.Set; |
| 28 | 28 | |
| 29 | -// TODO: we probably should make that an abstract class and move some bit in a "ReflexionMethodMapper" | |
| 30 | -// subclass for consistency with the rest, but we can see to that later | |
| 31 | 29 | class MethodMapper { |
| 32 | 30 | |
| 33 | - public final Method method; | |
| 34 | - public final String queryString; | |
| 35 | - public final ParamMapper[] paramMappers; | |
| 31 | + final Method method; | |
| 32 | + final String queryString; | |
| 33 | + private final ParamMapper[] paramMappers; | |
| 36 | 34 | |
| 37 | 35 | private final ConsistencyLevel consistency; |
| 38 | 36 | private final int fetchSize; |
| @@ -132,17 +130,16 @@ | ||
| 132 | 130 | throw new RuntimeException(String.format("Cannot map return of method %s to unsupported type %s", method, type)); |
| 133 | 131 | |
| 134 | 132 | try { |
| 135 | - this.returnMapper = (Mapper<?>) manager.mapper((Class<?>) type); | |
| 133 | + this.returnMapper = manager.mapper((Class<?>) type); | |
| 136 | 134 | } catch (Exception e) { |
| 137 | 135 | throw new RuntimeException("Cannot map return to class " + fullReturnType, e); |
| 138 | 136 | } |
| 139 | 137 | } |
| 140 | 138 | |
| 141 | - public Object invoke(Object[] args) { | |
| 139 | + Object invoke(Object[] args) { | |
| 142 | 140 | |
| 143 | 141 | BoundStatement bs = statement.bind(); |
| 144 | 142 | |
| 145 | - ProtocolVersion protocolVersion = session.getCluster().getConfiguration().getProtocolOptions().getProtocolVersion(); | |
| 146 | 143 | for (int i = 0; i < args.length; i++) { |
| 147 | 144 | paramMappers[i].setValue(bs, args[i]); |
| 148 | 145 | } |
| @@ -185,7 +182,7 @@ | ||
| 185 | 182 | private final TypeCodec<Object> codec; |
| 186 | 183 | |
| 187 | 184 | @SuppressWarnings("unchecked") |
| 188 | - public ParamMapper(String paramName, int paramIdx, TypeToken<?> paramType, Class<? extends TypeCodec<?>> codecClass) { | |
| 185 | + ParamMapper(String paramName, int paramIdx, TypeToken<?> paramType, Class<? extends TypeCodec<?>> codecClass) { | |
| 189 | 186 | this.paramName = paramName; |
| 190 | 187 | this.paramIdx = paramIdx; |
| 191 | 188 | this.paramType = (TypeToken<Object>) paramType; |
added driver-mapping/src/main/java/com/datastax/driver/mapping/PropertyMapper.java +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 @@ | ||
| 19 | 19 | import com.datastax.driver.core.querybuilder.Delete; |
| 20 | 20 | import com.datastax.driver.core.querybuilder.Insert; |
| 21 | 21 | import com.datastax.driver.core.querybuilder.Select; |
| 22 | -import com.google.common.base.Objects; | |
| 23 | 22 | |
| 24 | -import java.util.ArrayList; | |
| 25 | 23 | import java.util.Collection; |
| 26 | -import java.util.List; | |
| 27 | 24 | import java.util.Set; |
| 28 | 25 | |
| 29 | 26 | import static com.datastax.driver.core.querybuilder.QueryBuilder.*; |
| 30 | 27 | |
| 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); | |
| 76 | 45 | } |
| 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 | + } | |
| 83 | 48 | |
| 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; | |
| 93 | 62 | } else { |
| 94 | - select = selection.from(table); | |
| 63 | + selection = column.as(col.alias); | |
| 95 | 64 | } |
| 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(); | |
| 103 | 65 | } |
| 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); | |
| 118 | 71 | } |
| 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); | |
| 155 | 96 | } |
| 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(); | |
| 165 | 98 | } |
| 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 | + }; | |
| 183 | 100 | |
| 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); | |
| 188 | 102 | |
| 189 | 103 | } |
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 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.mapping; |
| 17 | 17 | |
| 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; | |
| 20 | 28 | |
| 21 | 29 | /** |
| 22 | 30 | * Utility methods related to reflection. |
| 23 | 31 | */ |
| 24 | 32 | class ReflectionUtils { |
| 25 | 33 | |
| 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; | |
| 39 | 120 | } |
| 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 | + | |
| 40 | 193 | } |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/Result.java +5 −5
| @@ -43,20 +43,20 @@ | ||
| 43 | 43 | |
| 44 | 44 | private T map(Row row) { |
| 45 | 45 | T entity = mapper.newEntity(); |
| 46 | - for (ColumnMapper<T> cm : mapper.allColumns()) { | |
| 47 | - String name = cm.getAlias() != null && this.useAlias ? cm.getAlias() : cm.getColumnName(); | |
| 46 | + for (PropertyMapper col : mapper.allColumns) { | |
| 47 | + String name = col.alias != null && this.useAlias ? col.alias : col.columnName; | |
| 48 | 48 | if (!row.getColumnDefinitions().contains(name)) |
| 49 | 49 | continue; |
| 50 | 50 | |
| 51 | 51 | Object value; |
| 52 | - TypeCodec<Object> customCodec = cm.getCustomCodec(); | |
| 52 | + TypeCodec<Object> customCodec = col.customCodec; | |
| 53 | 53 | if (customCodec != null) |
| 54 | 54 | value = row.get(name, customCodec); |
| 55 | 55 | else |
| 56 | - value = row.get(name, cm.getJavaType()); | |
| 56 | + value = row.get(name, col.javaType); | |
| 57 | 57 | |
| 58 | 58 | if (shouldSetValue(value)) { |
| 59 | - cm.setValue(entity, value); | |
| 59 | + col.setValue(entity, value); | |
| 60 | 60 | } |
| 61 | 61 | } |
| 62 | 62 | return entity; |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/TypeMappings.java +1 −1
| @@ -30,7 +30,7 @@ | ||
| 30 | 30 | */ |
| 31 | 31 | class TypeMappings { |
| 32 | 32 | |
| 33 | - static boolean mapsToCollection(Class<?> klass) { | |
| 33 | + private static boolean mapsToCollection(Class<?> klass) { | |
| 34 | 34 | return mapsToList(klass) || mapsToSet(klass) || mapsToMap(klass); |
| 35 | 35 | } |
| 36 | 36 |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/ClusteringColumn.java +2 −2
| @@ -21,12 +21,12 @@ | ||
| 21 | 21 | import java.lang.annotation.Target; |
| 22 | 22 | |
| 23 | 23 | /** |
| 24 | - * Annotation for fields that map to a CQL clustering column. | |
| 24 | + * Annotation for properties that map to a CQL clustering column. | |
| 25 | 25 | * <p/> |
| 26 | 26 | * If the mapped table has multiple clustering columns, it is mandatory |
| 27 | 27 | * to specify the ordinal parameter to avoid ordering ambiguity. |
| 28 | 28 | */ |
| 29 | -@Target(ElementType.FIELD) | |
| 29 | +@Target({ElementType.FIELD, ElementType.METHOD}) | |
| 30 | 30 | @Retention(RetentionPolicy.RUNTIME) |
| 31 | 31 | public @interface ClusteringColumn { |
| 32 | 32 | /** |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Column.java +7 −7
| @@ -24,21 +24,21 @@ | ||
| 24 | 24 | |
| 25 | 25 | /** |
| 26 | 26 | * Annotation that allows to specify the name of the CQL column to which the |
| 27 | - * field should be mapped. | |
| 27 | + * property should be mapped. | |
| 28 | 28 | * <p/> |
| 29 | 29 | * Note that this annotation is generally optional in the sense that any field |
| 30 | - * of a class annotated by {@link Table} will be mapped by default to a column | |
| 31 | - * having the same name than this field unless that field has the | |
| 30 | + * or any getter method of a Java bean property of a class annotated by {@link Table} | |
| 31 | + * will be mapped by default to a column | |
| 32 | + * having the same name than this field / property, unless that field or method has the | |
| 32 | 33 | * {@link Transient} annotation. As such, this annotation is mainly useful when |
| 33 | - * the name to map the field to is not the same one that the field itself (but | |
| 34 | - * can be added without it's name parameter for documentation sake). | |
| 34 | + * the CQL column name does not correspond to the field or property name itself. | |
| 35 | 35 | */ |
| 36 | -@Target(ElementType.FIELD) | |
| 36 | +@Target({ElementType.FIELD, ElementType.METHOD}) | |
| 37 | 37 | @Retention(RetentionPolicy.RUNTIME) |
| 38 | 38 | public @interface Column { |
| 39 | 39 | /** |
| 40 | 40 | * Name of the column being mapped in Cassandra. By default, the name of the |
| 41 | - * field will be used. | |
| 41 | + * field or Java bean property will be used. | |
| 42 | 42 | * |
| 43 | 43 | * @return the name of the mapped column in Cassandra, or {@code ""} to use |
| 44 | 44 | * the field name. |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Computed.java +6 −6
| @@ -24,26 +24,26 @@ | ||
| 24 | 24 | import java.lang.annotation.Target; |
| 25 | 25 | |
| 26 | 26 | /** |
| 27 | - * Annotates a "computed" field, which gets filled from a CQL expression in the SELECT query | |
| 27 | + * Annotates a "computed" property, which gets filled from a CQL expression in the SELECT query | |
| 28 | 28 | * used to retrieve an entity. |
| 29 | 29 | * <p/> |
| 30 | - * Note that such fields are only filled by default mapper operations ({@link Mapper#get(Object...)}), | |
| 30 | + * Note that such properties are only filled by default mapper operations ({@link Mapper#get(Object...)}), | |
| 31 | 31 | * they will be ignored in accessor queries and save operations. |
| 32 | 32 | * <p/> |
| 33 | - * As opposed to other mapper annotation, this one doesn't handle case sensitivity. If your expression | |
| 33 | + * As opposed to other mapper annotations, this one doesn't handle case sensitivity. If your expression | |
| 34 | 34 | * contains case-sensitive names, you'll need to quote them explicitly: |
| 35 | 35 | * <pre> |
| 36 | 36 | * {@code @Computed("\"caseSensitiveFunction\"(v)")} |
| 37 | 37 | * </pre> |
| 38 | 38 | */ |
| 39 | -@Target(ElementType.FIELD) | |
| 39 | +@Target({ElementType.FIELD, ElementType.METHOD}) | |
| 40 | 40 | @Retention(RetentionPolicy.RUNTIME) |
| 41 | 41 | public @interface Computed { |
| 42 | 42 | /** |
| 43 | - * The formula used to compute the field. | |
| 43 | + * The formula used to compute the property. | |
| 44 | 44 | * <p/> |
| 45 | 45 | * This is a CQL expression like you would use directly in a query, for instance |
| 46 | - * "writetime(v)". | |
| 46 | + * {@code "writetime(v)"}. | |
| 47 | 47 | * |
| 48 | 48 | * @return the formula. |
| 49 | 49 | */ |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Field.java +7 −7
| @@ -24,21 +24,21 @@ | ||
| 24 | 24 | |
| 25 | 25 | /** |
| 26 | 26 | * Annotation that allows to specify the name of the CQL UDT field to which the |
| 27 | - * Java field should be mapped. | |
| 27 | + * Java field or bean property should be mapped. | |
| 28 | 28 | * <p/> |
| 29 | 29 | * Note that this annotation is generally optional in the sense that any field |
| 30 | - * of a class annotated by {@link UDT} will be mapped by default to a UDT field | |
| 31 | - * having the same name than this Java field unless that Java field has the | |
| 30 | + * or any getter method of a Java bean property of a class annotated by {@link UDT} | |
| 31 | + * will be mapped by default to a UDT field | |
| 32 | + * having the same name than this Java field / bean property unless that Java field or method has the | |
| 32 | 33 | * {@link Transient} annotation. As such, this annotation is mainly useful when |
| 33 | - * the name to map the field to is not the same one that the field itself (but | |
| 34 | - * can be added without it's name parameter for documentation sake). | |
| 34 | + * the UDT field name does not correspond to the Java field or property name itself. | |
| 35 | 35 | */ |
| 36 | -@Target(ElementType.FIELD) | |
| 36 | +@Target({ElementType.FIELD, ElementType.METHOD}) | |
| 37 | 37 | @Retention(RetentionPolicy.RUNTIME) |
| 38 | 38 | public @interface Field { |
| 39 | 39 | /** |
| 40 | 40 | * Name of the column being mapped in Cassandra. By default, the name of the |
| 41 | - * field will be used. | |
| 41 | + * Java field or bean property will be used. | |
| 42 | 42 | * |
| 43 | 43 | * @return the name of the mapped column in Cassandra, or {@code ""} to use |
| 44 | 44 | * the field name. |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Frozen.java +2 −2
| @@ -23,7 +23,7 @@ | ||
| 23 | 23 | import java.lang.annotation.Target; |
| 24 | 24 | |
| 25 | 25 | /** |
| 26 | - * Specifies that the field decorated with this annotation maps to a CQL type that is {@link DataType#isFrozen() frozen}, | |
| 26 | + * Specifies that the property decorated with this annotation maps to a CQL type that is {@link DataType#isFrozen() frozen}, | |
| 27 | 27 | * or contains frozen subtypes. |
| 28 | 28 | * <p/> |
| 29 | 29 | * This annotation is purely informational at this stage, the validity of the declaration is not checked. |
| @@ -33,7 +33,7 @@ | ||
| 33 | 33 | * @see FrozenKey |
| 34 | 34 | * @see FrozenValue |
| 35 | 35 | */ |
| 36 | -@Target(ElementType.FIELD) | |
| 36 | +@Target({ElementType.FIELD, ElementType.METHOD}) | |
| 37 | 37 | @Retention(RetentionPolicy.RUNTIME) |
| 38 | 38 | public @interface Frozen { |
| 39 | 39 |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/FrozenKey.java +2 −2
| @@ -21,13 +21,13 @@ | ||
| 21 | 21 | import java.lang.annotation.Target; |
| 22 | 22 | |
| 23 | 23 | /** |
| 24 | - * Shorthand to specify that the key type of a MAP field is frozen. | |
| 24 | + * Shorthand to specify that the key type of a MAP property is frozen. | |
| 25 | 25 | * <p/> |
| 26 | 26 | * This is equivalent to {@code @Frozen("map<frozen<foo>, bar>")}. |
| 27 | 27 | * |
| 28 | 28 | * @see Frozen |
| 29 | 29 | */ |
| 30 | -@Target(ElementType.FIELD) | |
| 30 | +@Target({ElementType.FIELD, ElementType.METHOD}) | |
| 31 | 31 | @Retention(RetentionPolicy.RUNTIME) |
| 32 | 32 | public @interface FrozenKey { |
| 33 | 33 | } |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/FrozenValue.java +2 −2
| @@ -21,7 +21,7 @@ | ||
| 21 | 21 | import java.lang.annotation.Target; |
| 22 | 22 | |
| 23 | 23 | /** |
| 24 | - * Shorthand to specify that the value type of a collection field is frozen. | |
| 24 | + * Shorthand to specify that the value type of a collection property is frozen. | |
| 25 | 25 | * <p/> |
| 26 | 26 | * This is equivalent to any of the following: |
| 27 | 27 | * <ul> |
| @@ -32,7 +32,7 @@ | ||
| 32 | 32 | * |
| 33 | 33 | * @see Frozen |
| 34 | 34 | */ |
| 35 | -@Target(ElementType.FIELD) | |
| 35 | +@Target({ElementType.FIELD, ElementType.METHOD}) | |
| 36 | 36 | @Retention(RetentionPolicy.RUNTIME) |
| 37 | 37 | public @interface FrozenValue { |
| 38 | 38 | } |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/PartitionKey.java +2 −2
| @@ -21,13 +21,13 @@ | ||
| 21 | 21 | import java.lang.annotation.Target; |
| 22 | 22 | |
| 23 | 23 | /** |
| 24 | - * Annotation for fields that map to a CQL partition key (or one of it's | |
| 24 | + * Annotation for properties that map to a CQL partition key (or one of it's | |
| 25 | 25 | * component if the partition key is composite). |
| 26 | 26 | * <p/> |
| 27 | 27 | * If the partition key of the mapped table is composite, it is mandatory |
| 28 | 28 | * to specify the ordinal parameter to avoid ordering ambiguity. |
| 29 | 29 | */ |
| 30 | -@Target(ElementType.FIELD) | |
| 30 | +@Target({ElementType.FIELD, ElementType.METHOD}) | |
| 31 | 31 | @Retention(RetentionPolicy.RUNTIME) |
| 32 | 32 | public @interface PartitionKey { |
| 33 | 33 | /** |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Transient.java +4 −4
| @@ -21,14 +21,14 @@ | ||
| 21 | 21 | import java.lang.annotation.Target; |
| 22 | 22 | |
| 23 | 23 | /** |
| 24 | - * Whenever this annotation is added on a field, the field will not be mapped | |
| 24 | + * Whenever this annotation is added on a property, the property will not be mapped | |
| 25 | 25 | * to any column (neither during reads nor writes). |
| 26 | 26 | * <p/> |
| 27 | 27 | * Please note that it is thus illegal to have a field that has both the |
| 28 | - * {@code Transcient} annotation and one of the {@link Column}, {@link PartitionKey} | |
| 29 | - * or {@link ClusteringColumn} annotation. | |
| 28 | + * {@code Transient} annotation and one of the following annotations: | |
| 29 | + * {@link Column}, {@link PartitionKey}, {@link ClusteringColumn}. | |
| 30 | 30 | */ |
| 31 | -@Target(ElementType.FIELD) | |
| 31 | +@Target({ElementType.FIELD, ElementType.METHOD}) | |
| 32 | 32 | @Retention(RetentionPolicy.RUNTIME) |
| 33 | 33 | public @interface Transient { |
| 34 | 34 | } |
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 @@ | ||
| 91 | 91 | void should_add_aliases_for_fields_in_select_queries() { |
| 92 | 92 | BoundStatement bs = (BoundStatement) userMapper.getQuery("test"); |
| 93 | 93 | 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"); | |
| 95 | 95 | } |
| 96 | 96 | |
| 97 | 97 | @Test(groups = "short") |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperDefaultKeyspaceTest.java +2 −2
| @@ -92,7 +92,7 @@ | ||
| 92 | 92 | |
| 93 | 93 | @Test(groups = "short", |
| 94 | 94 | 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") | |
| 96 | 96 | public void should_throw_a_meaningful_error_message_when_no_default_table_keyspace_and_session_not_logged() { |
| 97 | 97 | Session session2 = cluster().connect(); |
| 98 | 98 | MappingManager manager = new MappingManager(session2); |
| @@ -101,7 +101,7 @@ | ||
| 101 | 101 | |
| 102 | 102 | @Test(groups = "short", |
| 103 | 103 | 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") | |
| 105 | 105 | public void should_throw_a_meaningful_error_message_when_no_default_udt_keyspace_and_session_not_logged() { |
| 106 | 106 | Session session2 = cluster().connect(); |
| 107 | 107 | 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 @@ | ||
| 83 | 83 | BoundStatement bs = (BoundStatement) mapper.saveQuery(newUser, options); |
| 84 | 84 | String queryString = bs.preparedStatement().getQueryString(); |
| 85 | 85 | if (nullName && !saveExpected) |
| 86 | - assertThat(queryString).as(description).doesNotContain("\"name\""); | |
| 86 | + assertThat(queryString).as(description).doesNotContain("name"); | |
| 87 | 87 | else |
| 88 | - assertThat(queryString).as(description).contains("\"name\""); | |
| 88 | + assertThat(queryString).as(description).contains("name"); | |
| 89 | 89 | |
| 90 | 90 | if (nullPhone && !saveExpected) |
| 91 | - assertThat(queryString).as(description).doesNotContain("\"phone\""); | |
| 91 | + assertThat(queryString).as(description).doesNotContain("phone"); | |
| 92 | 92 | else |
| 93 | - assertThat(queryString).as(description).contains("\"phone\""); | |
| 93 | + assertThat(queryString).as(description).contains("phone"); | |
| 94 | 94 | |
| 95 | 95 | // Save entity and check the data |
| 96 | 96 | mapper.save(newUser, options); |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperTest.java +1 −2
| @@ -36,7 +36,7 @@ | ||
| 36 | 36 | /** |
| 37 | 37 | * Basic tests for the mapping module. |
| 38 | 38 | */ |
| 39 | -@SuppressWarnings("unused") | |
| 39 | +@SuppressWarnings({"unused", "WeakerAccess"}) | |
| 40 | 40 | public class MapperTest extends CCMTestsSupport { |
| 41 | 41 | |
| 42 | 42 | @Override |
| @@ -58,7 +58,6 @@ | ||
| 58 | 58 | * |
| 59 | 59 | * And the next step will be to support UDT (which should be relatively simple). |
| 60 | 60 | */ |
| 61 | - @SuppressWarnings("unused") | |
| 62 | 61 | @Table(name = "users", |
| 63 | 62 | readConsistency = "QUORUM", |
| 64 | 63 | writeConsistency = "QUORUM") |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperUDTTest.java +10 −10
| @@ -380,7 +380,7 @@ | ||
| 380 | 380 | /** |
| 381 | 381 | * Ensures that if a table is altered after a {@link Mapper} is created that it continues to work as long as |
| 382 | 382 | * the change is compatible. A new column is added to the table in this case, which is a compatible change. |
| 383 | - * <p> | |
| 383 | + * <p/> | |
| 384 | 384 | * It also ensures that after the change is made that requesting a new {@link Mapper} returns a different instance |
| 385 | 385 | * instead of the existing one. |
| 386 | 386 | * |
| @@ -407,7 +407,7 @@ | ||
| 407 | 407 | /** |
| 408 | 408 | * Ensures that if a UDT is altered after a {@link Mapper} is created that has a UDT that it continues to work as |
| 409 | 409 | * 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/> | |
| 411 | 411 | * It also ensures that after the change is made that requesting a new {@link TypeCodec} for that UDT and a new |
| 412 | 412 | * {@link Mapper} for a table using that UDT returns different instances instead of the existing ones. |
| 413 | 413 | * |
| @@ -440,7 +440,7 @@ | ||
| 440 | 440 | * Ensures that if a table is dropped after a {@link Mapper} is created that the {@link Mapper} can no longer |
| 441 | 441 | * successfully make queries and that attempting to create a new {@link Mapper} throws an |
| 442 | 442 | * {@link IllegalArgumentException}. |
| 443 | - * <p> | |
| 443 | + * <p/> | |
| 444 | 444 | * It also ensures that requesting a {@link Mapper} fails as the previous {@link Mapper} was evicted and a new |
| 445 | 445 | * one cannot be created as the table has been dropped. |
| 446 | 446 | * |
| @@ -471,14 +471,14 @@ | ||
| 471 | 471 | manager.mapper(User.class); |
| 472 | 472 | fail("Expected IllegalArgumentException"); |
| 473 | 473 | } 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 + "\""); | |
| 475 | 475 | } |
| 476 | 476 | } |
| 477 | 477 | |
| 478 | 478 | /** |
| 479 | 479 | * Ensures that if a table is altered after a {@link Mapper} is created that it no longer continues to work if |
| 480 | 480 | * the change is not compatible. A column is dropped from the table in this case, which is an incompatible change. |
| 481 | - * <p> | |
| 481 | + * <p/> | |
| 482 | 482 | * It also ensures that requesting a {@link Mapper} fails as the previous {@link Mapper} was evicted and a new |
| 483 | 483 | * one cannot be created as a declared column is missing from the schema but is present in the class definition. |
| 484 | 484 | * |
| @@ -509,7 +509,7 @@ | ||
| 509 | 509 | manager.mapper(User.class); |
| 510 | 510 | fail("Expected IllegalArgumentException"); |
| 511 | 511 | } 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)); | |
| 513 | 513 | } |
| 514 | 514 | } |
| 515 | 515 | |
| @@ -517,10 +517,10 @@ | ||
| 517 | 517 | * Ensures that if a UDT is altered after a {@link Mapper} is created that it no longer continues to work if |
| 518 | 518 | * the change made to the UDT is not compatible. A field is renamed in the UDT in this case, which is not a |
| 519 | 519 | * compatible change. |
| 520 | - * <p> | |
| 520 | + * <p/> | |
| 521 | 521 | * It also ensures that requesting a {@link Mapper} fails as the previous {@link Mapper} was evicted and a new |
| 522 | 522 | * one cannot be created as a declared field is missing from the schema but is present in the class definition. |
| 523 | - * <p> | |
| 523 | + * <p/> | |
| 524 | 524 | * Also verifies that a {@link TypeCodec} cannot be requested for the UDT as well. |
| 525 | 525 | * |
| 526 | 526 | * @jira_ticket JAVA-1126 |
| @@ -552,13 +552,13 @@ | ||
| 552 | 552 | manager.mapper(User.class); |
| 553 | 553 | fail("Expected IllegalArgumentException"); |
| 554 | 554 | } 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)); | |
| 556 | 556 | } |
| 557 | 557 | try { |
| 558 | 558 | manager.udtCodec(Address.class); |
| 559 | 559 | fail("Expected IllegalArgumentException"); |
| 560 | 560 | } 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)); | |
| 562 | 562 | } |
| 563 | 563 | } |
| 564 | 564 |
modified manual/object_mapper/creating/README.md +307 −24
| @@ -17,7 +17,7 @@ | ||
| 17 | 17 | writeConsistency = "QUORUM", |
| 18 | 18 | caseSensitiveKeyspace = false, |
| 19 | 19 | caseSensitiveTable = false) |
| 20 | -public static class User { | |
| 20 | +public class User { | |
| 21 | 21 | @PartitionKey |
| 22 | 22 | @Column(name = "user_id") |
| 23 | 23 | private UUID userId; |
| @@ -39,20 +39,155 @@ | ||
| 39 | 39 | save, or delete operation in the mapper. (if unspecified, it defaults |
| 40 | 40 | to the cluster-wide setting) |
| 41 | 41 | |
| 42 | -The class must provide a default constructor, and all fields (except the | |
| 43 | -ones annotated `@Transient`) must have corresponding setters and | |
| 44 | -getters. | |
| 42 | +The class must provide a default constructor. 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 | +``` | |
| 45 | 151 | |
| 46 | 152 | [table]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Table.html |
| 47 | 153 | [case-sensitive]:http://docs.datastax.com/en/cql/3.3/cql/cql_reference/ucase-lcase_r.html |
| 48 | 154 | [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- | |
| 49 | 157 | |
| 50 | 158 | #### Column names |
| 51 | 159 | |
| 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 | +``` | |
| 56 | 191 | |
| 57 | 192 | [column]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Column.html |
| 58 | 193 | |
| @@ -84,8 +219,8 @@ | ||
| 84 | 219 | |
| 85 | 220 | #### Computed fields |
| 86 | 221 | |
| 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 | |
| 89 | 224 | functions in Cassandra like `writetime()` or [User Defined Functions] are |
| 90 | 225 | supported. |
| 91 | 226 | |
| @@ -94,7 +229,7 @@ | ||
| 94 | 229 | Integer ttl; |
| 95 | 230 | ``` |
| 96 | 231 | |
| 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, | |
| 98 | 233 | otherwise an exception will be thrown. |
| 99 | 234 | |
| 100 | 235 | Computed fields are ignored when saving an entity. |
| @@ -108,18 +243,21 @@ | ||
| 108 | 243 | int f; |
| 109 | 244 | ``` |
| 110 | 245 | |
| 111 | -Finally, computed fields are only supported with [basic read | |
| 246 | +Finally, computed properties are only supported with [basic read | |
| 112 | 247 | 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 | |
| 114 | 249 | version (see |
| 115 | 250 | [JAVA-832](https://datastax-oss.atlassian.net/browse/JAVA-832)). |
| 116 | 251 | |
| 117 | 252 | [User Defined Functions]:http://www.planetcassandra.org/blog/user-defined-functions-in-cassandra-3-0/ |
| 118 | 253 | [computed]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Computed.html |
| 119 | 254 | |
| 120 | -#### Transient fields | |
| 255 | +#### Transient properties | |
| 121 | 256 | |
| 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. | |
| 123 | 261 | |
| 124 | 262 | [transient]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Transient.html |
| 125 | 263 | |
| @@ -148,12 +286,14 @@ | ||
| 148 | 286 | - `caseSensitiveKeyspace`: whether the keyspace name is case-sensitive. |
| 149 | 287 | - `caseSensitiveType`: whether the UDT name is case-sensitive. |
| 150 | 288 | |
| 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. | |
| 154 | 295 | |
| 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, | |
| 157 | 297 | use the [@Field][field] annotation: |
| 158 | 298 | |
| 159 | 299 | ```java |
| @@ -169,7 +309,7 @@ | ||
| 169 | 309 | ``` |
| 170 | 310 | |
| 171 | 311 | ```java |
| 172 | -public static class Company { | |
| 312 | +public class Company { | |
| 173 | 313 | @PartitionKey |
| 174 | 314 | @Column(name = "company_id") |
| 175 | 315 | private UUID companyId; |
| @@ -178,8 +318,8 @@ | ||
| 178 | 318 | } |
| 179 | 319 | ``` |
| 180 | 320 | |
| 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. | |
| 183 | 323 | |
| 184 | 324 | [User Defined Types]: ../../udts/ |
| 185 | 325 | [udt]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/UDT.html |
| @@ -199,7 +339,7 @@ | ||
| 199 | 339 | they match the schema, in anticipation for the schema generation features |
| 200 | 340 | that will be added in a future version. |
| 201 | 341 | 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: | |
| 203 | 343 | |
| 204 | 344 | ```java |
| 205 | 345 | // Will be mapped as a 'list<text>' |
| @@ -222,3 +362,146 @@ | ||
| 222 | 362 | [frozen]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Frozen.html |
| 223 | 363 | [frozenkey]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/FrozenKey.html |
| 224 | 364 | [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. |