Elffuss BraidHub

kikocis/java-driver public

JAVA-605: Codec support for Java enums.

This commit drops the mapper @Enumerated annotation. Users are now encouraged to use the enum codecs instead (EnumNameCodec and EnumOrdinalCodec).
Changeset01c1288c6b3c2085e6274fd1ba2695f9ee607a61db12f5e0501dbeb146cdb832
AuthorAlexandre Dutra <alexandre.dutra@datastax.com> · 2015-11-02 17:01 +01:00
CommitterAlexandre Dutra <alexandre.dutra@datastax.com> · 2015-11-17 14:52 +01:00
Parents70f21c53e06b

Browse the files at this changeset

18 files changed

modified changelog/README.md +1 −0
@@ -18,6 +18,7 @@
1818 - [new feature] JAVA-742: Codec Support for JSON.
1919 - [new feature] JAVA-606: Codec support for Java 8.
2020 - [new feature] JAVA-565: Codec support for Java arrays.
21+- [new feature] JAVA-605: Codec support for Java enums.
2122
2223 Merged from 2.1 branch:
2324
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/enums/EnumCodecsTest.java +55 −22
@@ -31,12 +31,9 @@
3131
3232 import com.datastax.driver.core.*;
3333 import com.datastax.driver.core.utils.CassandraVersion;
34-import com.datastax.driver.mapping.EnumType;
3534 import com.datastax.driver.mapping.Mapper;
3635 import com.datastax.driver.mapping.MappingManager;
37-import com.datastax.driver.mapping.annotations.Enumerated;
38-import com.datastax.driver.mapping.annotations.PartitionKey;
39-import com.datastax.driver.mapping.annotations.Table;
36+import com.datastax.driver.mapping.annotations.*;
4037
4138 import static com.datastax.driver.core.DataType.cint;
4239 import static com.datastax.driver.core.DataType.text;
@@ -72,15 +69,15 @@
7269 + "foo int,"
7370 + "bar text)",
7471 "CREATE TABLE IF NOT EXISTS t1 ("
75- + "pk int PRIMARY KEY, "
72+ + "pk int, "
7673 + "foo int, "
7774 + "foos list<int>, "
7875 + "bar text, "
7976 + "bars set<text>, "
8077 + "foobars map<int,text>, "
8178 + "tup frozen<tuple<int,varchar>>, "
82- + "udt frozen<udt1>"
83- + ")"
79+ + "udt frozen<udt1>,"
80+ + "primary key (pk, foo))"
8481 );
8582 }
8683
@@ -143,18 +140,54 @@
143140 }
144141
145142 @Test(groups = "short")
146- public void should_use_mapper_to_store_and_retrieve_values_with_enum_codecs() {
143+ public void should_use_mapper_to_store_and_retrieve_nulls_with_enum_codecs() {
147144 // given
148145 MappingManager manager = new MappingManager(session);
149146 Mapper<Mapped> mapper = manager.mapper(Mapped.class);
147+ Mapped pojo = new Mapped();
148+ pojo.pk = 42;
149+ pojo.foo = FOO_1;
150150 // when
151+ mapper.save(pojo);
152+ Mapped actual = mapper.get(42, FOO_1);
153+ // then
154+ assertThat(actual).isEqualToComparingFieldByField(pojo);
155+ }
156+
157+ @Test(groups = "short")
158+ public void should_use_mapper_to_store_and_retrieve_values_with_enum_codecs() {
159+ // given
160+ MappingManager manager = new MappingManager(session);
161+ Mapper<Mapped> mapper = manager.mapper(Mapped.class);
151162 Mapped pojo = new Mapped();
163+ pojo.pk = 42;
164+ pojo.foo = FOO_1;
165+ pojo.bar = BAR_1;
166+ pojo.foos = newArrayList(FOO_2, FOO_1);
167+ pojo.bars = newHashSet(BAR_1, BAR_2);
168+ pojo.foobars = ImmutableMap.of(FOO_1, BAR_2);
169+ // when
152170 mapper.save(pojo);
153- Mapped actual = mapper.get(42);
171+ Mapped actual = mapper.get(42, FOO_1);
154172 // then
155173 assertThat(actual).isEqualToComparingFieldByField(pojo);
156174 }
157175
176+ @Test(groups = "short")
177+ public void should_use_accessor_to_store_and_retrieve_values_with_enum_codecs() {
178+ // given
179+ MappedAccessor accessor = new MappingManager(session).createAccessor(MappedAccessor.class);
180+ Mapped expected = new Mapped();
181+ expected.pk = 42;
182+ expected.foo = FOO_1;
183+ expected.bar = BAR_2;
184+ // when
185+ accessor.insert(42, FOO_1, BAR_2);
186+ Mapped result = accessor.getByFoo(42, FOO_1);
187+ // then
188+ assertThat(result).isEqualToComparingFieldByField(expected);
189+ }
190+
158191 private void assertRow(Row row) {
159192
160193 assertThat(row.getInt(0)).isEqualTo(pk);
@@ -215,10 +248,7 @@
215248 @PartitionKey
216249 private int pk;
217250
218- // note that we need to specify @Enumerated here
219- // because the mapper already has a partial support for enums
220- // that kicks in for fields of type Enum
221- @Enumerated(EnumType.ORDINAL)
251+ @ClusteringColumn
222252 private Foo foo;
223253
224254 private List<Foo> foos;
@@ -229,15 +259,6 @@
229259
230260 private Map<Foo, Bar> foobars;
231261
232- public Mapped(){
233- pk = 42;
234- foo = FOO_1;
235- bar = BAR_1;
236- foos = newArrayList(FOO_2, FOO_1);
237- bars = newHashSet(BAR_1, BAR_2);
238- foobars = ImmutableMap.of(FOO_1, BAR_2);
239- }
240-
241262 public int getPk() {
242263 return pk;
243264 }
@@ -287,6 +308,18 @@
287308 }
288309 }
289310
311+ @Accessor
312+ public interface MappedAccessor {
313+
314+ @Query("select * from t1 where pk=? and foo=?")
315+ Mapped getByFoo(int pk, Foo foo);
316+
317+ @Query("insert into t1 (pk, foo, bar) values (?,?,?)")
318+ ResultSet insert(int pk, Foo foo, Bar bar);
319+
320+ }
321+
322+
290323 enum Foo {
291324 FOO_1, FOO_2
292325 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/AnnotationParser.java +2 −22
@@ -30,7 +30,6 @@
3030 import com.datastax.driver.core.ConsistencyLevel;
3131 import com.datastax.driver.core.TypeCodec;
3232 import com.datastax.driver.core.UserType;
33-import com.datastax.driver.mapping.MethodMapper.EnumParamMapper;
3433 import com.datastax.driver.mapping.MethodMapper.ParamMapper;
3534 import com.datastax.driver.mapping.annotations.*;
3635
@@ -80,7 +79,7 @@
8079 throw new UnsupportedOperationException("Computed fields are not supported with native protocol v1");
8180
8281 AnnotationChecks.validateAnnotations(field, "entity",
83- Column.class, ClusteringColumn.class, Enumerated.class, Frozen.class, FrozenKey.class,
82+ Column.class, ClusteringColumn.class, Frozen.class, FrozenKey.class,
8483 FrozenValue.class, PartitionKey.class, Transient.class, Computed.class);
8584
8685 if (field.getAnnotation(Transient.class) != null)
@@ -139,7 +138,7 @@
139138
140139 AnnotationChecks.validateAnnotations(field, "UDT",
141140 com.datastax.driver.mapping.annotations.Field.class, Frozen.class, FrozenKey.class,
142- FrozenValue.class, Enumerated.class, Transient.class);
141+ FrozenValue.class, Transient.class);
143142
144143 if (field.getAnnotation(Transient.class) != null)
145144 continue;
@@ -208,15 +207,6 @@
208207 return ColumnMapper.Kind.REGULAR;
209208 }
210209
211- public static EnumType enumType(Field field) {
212- Class<?> type = field.getType();
213- if (!type.isEnum())
214- return null;
215-
216- Enumerated enumerated = field.getAnnotation(Enumerated.class);
217- return (enumerated == null) ? EnumType.STRING : enumerated.value();
218- }
219-
220210 public static String columnName(Field field) {
221211 Column column = field.getAnnotation(Column.class);
222212 Computed computedField = field.getAnnotation(Computed.class);
@@ -337,16 +327,6 @@
337327 private static ParamMapper newParamMapper(String className, String methodName, int idx, String paramName, Class<? extends TypeCodec<?>> codecClass, Type paramType, Annotation[] paramAnnotations, MappingManager mappingManager) {
338328 if (paramType instanceof Class) {
339329 Class<?> paramClass = (Class<?>) paramType;
340- if (paramClass.isEnum()) {
341- EnumType enumType = EnumType.STRING;
342- for (Annotation annotation : paramAnnotations) {
343- if (annotation instanceof Enumerated) {
344- enumType = ((Enumerated) annotation).value();
345- }
346- }
347- return new EnumParamMapper(paramName, idx, enumType);
348- }
349-
350330 if (TypeMappings.isMappedUDT(paramClass))
351331 mappingManager.getUDTCodec(paramClass);
352332
modified driver-mapping/src/main/java/com/datastax/driver/mapping/ColumnMapper.java +2 −3
@@ -69,10 +69,9 @@
6969 }
7070
7171 /**
72- * The Java type that will get passed to the codec.
73- * This might be different from the field type if the column mapper does a transformation.
72+ * The Java type of this column.
7473 */
75- public TypeToken<Object> getPivotType() {
74+ public TypeToken<Object> getJavaType() {
7675 return fieldType;
7776 }
7877 }
deleted driver-mapping/src/main/java/com/datastax/driver/mapping/EnumType.java +0 −41
@@ -1,41 +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.google.common.reflect.TypeToken;
19-
20-/**
21- * The types of way to persist a JAVA Enum.
22- */
23-public enum EnumType {
24- /**
25- * Persists enumeration values using their ordinal in the Enum declaration.
26- * <p>
27- * Note that this relies on the order of the values in source code, and will change
28- * if values are added/removed before existing ones.
29- */
30- ORDINAL(Integer.class),
31- /** Persists enumeration values using the string they have been declared with. */
32- STRING(String.class);
33-
34- @SuppressWarnings("unchecked")
35- EnumType(Class<?> klass) {
36- this.pivotType = (TypeToken<Object>)TypeToken.of(klass);
37- }
38-
39- /** The type enum constants will be turned into before being saved */
40- final TypeToken<Object> pivotType;
41-}
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MappedUDTCodec.java +2 −2
@@ -52,7 +52,7 @@
5252 Object value = cm.getValue(sourceObject);
5353 TypeCodec<Object> codec = cm.getCustomCodec();
5454 if (codec == null)
55- codec = codecRegistry.codecFor(cqlUserType.getFieldType(cm.getColumnName()), cm.getPivotType());
55+ codec = codecRegistry.codecFor(cqlUserType.getFieldType(cm.getColumnName()), cm.getJavaType());
5656 ByteBuffer serializedField = codec.serialize(value, protocolVersion);
5757 size += 4 + (serializedField == null ? 0 : serializedField.remaining());
5858 serializedFields.add(serializedField);
@@ -83,7 +83,7 @@
8383 ByteBuffer serialized = (size < 0) ? null : CodecUtils.readBytes(input, size);
8484 TypeCodec<Object> codec = cm.getCustomCodec();
8585 if (codec == null)
86- codec = codecRegistry.codecFor(cqlUserType.getFieldType(cm.getColumnName()), cm.getPivotType());
86+ codec = codecRegistry.codecFor(cqlUserType.getFieldType(cm.getColumnName()), cm.getJavaType());
8787 cm.setValue(targetObject, codec.deserialize(serialized, protocolVersion));
8888 }
8989
modified driver-mapping/src/main/java/com/datastax/driver/mapping/Mapper.java +1 −1
@@ -226,7 +226,7 @@
226226 if (customCodec != null)
227227 bs.set(i, value, customCodec);
228228 else
229- bs.set(i, value, mapper.getPivotType());
229+ bs.set(i, value, mapper.getJavaType());
230230 }
231231
232232 /**
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MethodMapper.java +2 −30
@@ -143,7 +143,7 @@
143143
144144 ProtocolVersion protocolVersion = session.getCluster().getConfiguration().getProtocolOptions().getProtocolVersion();
145145 for (int i = 0; i < args.length; i++) {
146- paramMappers[i].setValue(bs, args[i], protocolVersion);
146+ paramMappers[i].setValue(bs, args[i]);
147147 }
148148
149149 if (consistency != null)
@@ -196,7 +196,7 @@
196196 }
197197 }
198198
199- void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) {
199+ void setValue(BoundStatement boundStatement, Object arg) {
200200 if (paramName == null) {
201201 if (codec == null)
202202 boundStatement.set(paramIdx, arg, paramType);
@@ -211,32 +211,4 @@
211211 }
212212 }
213213
214- static class EnumParamMapper extends ParamMapper {
215-
216- private final EnumType enumType;
217-
218- public EnumParamMapper(String paramName, int paramIdx, EnumType enumType) {
219- super(paramName, paramIdx, enumType.pivotType, null);
220- this.enumType = enumType;
221- }
222-
223- @Override
224- void setValue(BoundStatement boundStatement, Object arg, ProtocolVersion protocolVersion) {
225- super.setValue(boundStatement, convert(arg), protocolVersion);
226- }
227-
228- @SuppressWarnings("rawtypes")
229- private Object convert(Object arg) {
230- if(arg == null)
231- return arg;
232-
233- switch (enumType) {
234- case STRING:
235- return arg.toString();
236- case ORDINAL:
237- return ((Enum) arg).ordinal();
238- }
239- throw new AssertionError();
240- }
241- }
242214 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/QueryType.java +0 −4
@@ -58,10 +58,6 @@
5858 this.endInclusive = endInclusive;
5959 }
6060
61- public static QueryType slice(int startBoundSize, boolean startInclusive, int endBoundSize, boolean endInclusive, boolean reversed) {
62- return new QueryType(reversed ? Kind.REVERSED_SLICE : Kind.SLICE, startBoundSize, startInclusive, endBoundSize, endInclusive);
63- }
64-
6561 String makePreparedQueryString(TableMetadata table, EntityMapper<?> mapper, MappingManager manager, Set<ColumnMapper<?>> columns, Collection<Mapper.Option> options) {
6662 QueryBuilder builder = new QueryBuilder(manager.getSession().getCluster());
6763 switch (kind) {
modified driver-mapping/src/main/java/com/datastax/driver/mapping/ReflectionMapper.java +0 −60
@@ -19,12 +19,8 @@
1919 import java.beans.PropertyDescriptor;
2020 import java.lang.reflect.Field;
2121 import java.lang.reflect.Method;
22-import java.util.HashMap;
23-import java.util.Map;
2422 import java.util.concurrent.atomic.AtomicInteger;
2523
26-import com.google.common.reflect.TypeToken;
27-
2824 import com.datastax.driver.core.ConsistencyLevel;
2925
3026 /**
@@ -86,58 +82,6 @@
8682 }
8783 }
8884
89- private static class EnumMapper<T> extends LiteralMapper<T> {
90-
91- private final EnumType enumType;
92- private final Map<String, Object> fromString;
93-
94- private EnumMapper(Field field, int position, PropertyDescriptor pd, EnumType enumType, AtomicInteger columnCounter) {
95- super(field, position, pd, columnCounter);
96- this.enumType = enumType;
97-
98- if (enumType == EnumType.STRING) {
99- fromString = new HashMap<String, Object>(fieldType.getRawType().getEnumConstants().length);
100- for (Object constant : fieldType.getRawType().getEnumConstants())
101- fromString.put(constant.toString().toLowerCase(), constant);
102-
103- } else {
104- fromString = null;
105- }
106- }
107-
108- @SuppressWarnings("rawtypes")
109- @Override
110- public Object getValue(T entity) {
111- Object value = super.getValue(entity);
112- switch (enumType) {
113- case STRING:
114- return (value == null) ? null : value.toString();
115- case ORDINAL:
116- return (value == null) ? null : ((Enum)value).ordinal();
117- }
118- throw new AssertionError();
119- }
120-
121- @Override
122- public void setValue(Object entity, Object value) {
123- Object converted = null;
124- switch (enumType) {
125- case STRING:
126- converted = fromString.get(value.toString().toLowerCase());
127- break;
128- case ORDINAL:
129- converted = fieldType.getRawType().getEnumConstants()[(Integer)value];
130- break;
131- }
132- super.setValue(entity, converted);
133- }
134-
135- @Override
136- public TypeToken<Object> getPivotType() {
137- return enumType.pivotType;
138- }
139- }
140-
14185 private static class ReflectionFactory implements Factory {
14286
14387 public <T> EntityMapper<T> create(Class<T> entityClass, String keyspace, String table, ConsistencyLevel writeConsistency, ConsistencyLevel readConsistency) {
@@ -150,10 +94,6 @@
15094 try {
15195 PropertyDescriptor pd = new PropertyDescriptor(fieldName, field.getDeclaringClass());
15296
153- if (field.getType().isEnum()) {
154- return new EnumMapper<T>(field, position, pd, AnnotationParser.enumType(field), columnCounter);
155- }
156-
15797 for (Class<?> udt : TypeMappings.findUDTs(field.getGenericType()))
15898 mappingManager.getUDTCodec(udt);
15999
modified driver-mapping/src/main/java/com/datastax/driver/mapping/Result.java +1 −1
@@ -52,7 +52,7 @@
5252 if (customCodec != null)
5353 value = row.get(name, customCodec);
5454 else
55- value = row.get(name, cm.getPivotType());
55+ value = row.get(name, cm.getJavaType());
5656
5757 if (shouldSetValue(value)) {
5858 cm.setValue(entity, value);
modified driver-mapping/src/main/java/com/datastax/driver/mapping/TypeMappings.java +0 −8
@@ -24,8 +24,6 @@
2424
2525 import com.google.common.collect.Sets;
2626
27-import com.datastax.driver.core.TupleValue;
28-import com.datastax.driver.core.UDTValue;
2927 import com.datastax.driver.mapping.annotations.UDT;
3028
3129 /**
@@ -53,12 +51,6 @@
5351 return klass.isAnnotationPresent(UDT.class);
5452 }
5553
56- static boolean mapsToUserTypeOrTuple(Class<?> klass) {
57- return isMappedUDT(klass) ||
58- klass.equals(UDTValue.class) ||
59- klass.equals(TupleValue.class);
60- }
61-
6254 /**
6355 * Traverses the type of a Java field or parameter to find classes annotated with @UDT.
6456 * This will recurse into nested collections, e.g. List<Set<TheMappedUDT>>
deleted driver-mapping/src/main/java/com/datastax/driver/mapping/annotations/Enumerated.java +0 −41
@@ -1,41 +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.annotations;
17-
18-import java.lang.annotation.ElementType;
19-import java.lang.annotation.Retention;
20-import java.lang.annotation.RetentionPolicy;
21-import java.lang.annotation.Target;
22-
23-import com.datastax.driver.mapping.EnumType;
24-
25-/**
26- * Defines that the annotated field (that must be a Java Enum) must be
27- * persisted as an enumerated type.
28- * <p>
29- * The optional {@link EnumType} value defined how the enumeration must be
30- * persisted.
31- */
32-@Target(value = {ElementType.FIELD, ElementType.PARAMETER})
33-@Retention(RetentionPolicy.RUNTIME)
34-public @interface Enumerated {
35- /**
36- * How the enumeration must be persisted.
37- *
38- * @return the {@link EnumType} to use for mapping this enumeration.
39- */
40- EnumType value() default EnumType.STRING;
41-}
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperAccessorParamsTest.java +2 −59
@@ -23,7 +23,6 @@
2323 import static org.assertj.core.api.Assertions.assertThat;
2424
2525 import com.datastax.driver.core.CCMBridge;
26-import com.datastax.driver.core.ResultSet;
2726 import com.datastax.driver.core.Row;
2827 import com.datastax.driver.core.utils.CassandraVersion;
2928 import com.datastax.driver.mapping.annotations.*;
@@ -39,36 +38,6 @@
3938 );
4039 }
4140
42- @Test(groups = "short")
43- public void should_allow_enum_as_int_in_accessor_params() {
44- UserAccessor accessor = new MappingManager(session)
45- .createAccessor(UserAccessor.class);
46-
47- accessor.addUser(0, Enum.FEMALE);
48- accessor.addUser(1, Enum.MALE);
49-
50- assertThat(accessor.getUser(Enum.MALE).one().getGender()).isEqualTo(Enum.MALE);
51- assertThat(accessor.getUser(Enum.MALE).one().getKey()).isEqualTo(1);
52-
53- assertThat(accessor.getUser(Enum.FEMALE).one().getGender()).isEqualTo(Enum.FEMALE);
54- assertThat(accessor.getUser(Enum.FEMALE).one().getKey()).isEqualTo(0);
55- }
56-
57- @Test(groups = "short")
58- public void should_allow_enum_as_string_in_accessor_params() {
59- UserAccessor accessor = new MappingManager(session)
60- .createAccessor(UserAccessor.class);
61-
62- accessor.addUserStr(0, Enum.FEMALE);
63- accessor.addUserStr(1, Enum.MALE);
64-
65- assertThat(accessor.getUserStr(Enum.MALE).one().getGender()).isEqualTo(Enum.MALE);
66- assertThat(accessor.getUserStr(Enum.MALE).one().getKey()).isEqualTo(1);
67-
68- assertThat(accessor.getUserStr(Enum.FEMALE).one().getGender()).isEqualTo(Enum.FEMALE);
69- assertThat(accessor.getUserStr(Enum.FEMALE).one().getKey()).isEqualTo(0);
70- }
71-
7241 @Test(groups = "short")
7342 @CassandraVersion(major = 2.0, description = "Uses named parameters")
7443 public void should_allow_less_parameters_than_bind_markers_if_there_are_repeated_names() {
@@ -118,21 +87,6 @@
11887 MALE, FEMALE
11988 }
12089
121- @Accessor
122- public interface UserAccessor {
123- @Query("select * from user where gender=?")
124- Result<User> getUser(@Enumerated(EnumType.ORDINAL) Enum value);
125-
126- @Query("select * from user_str where gender=?")
127- Result<UserStr> getUserStr(@Enumerated(EnumType.STRING) Enum value);
128-
129- @Query("insert into user (key, gender) values (?,?)")
130- ResultSet addUser(int key, @Enumerated(EnumType.ORDINAL) Enum value);
131-
132- @Query("insert into user_str (key, gender) values (?,?)")
133- ResultSet addUserStr(int key, @Enumerated(EnumType.STRING) Enum value);
134- }
135-
13690 /** Tests various ways to match method parameters to query bind markers. */
13791 @Accessor
13892 public interface UserPhoneAccessor {
@@ -176,15 +130,11 @@
176130 @PartitionKey
177131 private int key;
178132
179- @Enumerated(EnumType.ORDINAL)
180- private Enum gender;
181-
182133 public User() {
183134 }
184135
185- public User(int k, Enum val) {
136+ public User(int k) {
186137 this.key = k;
187- this.gender = val;
188138 }
189139
190140 public int getKey() {
@@ -195,13 +145,6 @@
195145 this.key = pk;
196146 }
197147
198- public Enum getGender() {
199- return this.gender;
200- }
201-
202- public void setGender(Enum val) {
203- this.gender = val;
204- }
205148 }
206149
207150 @Table(name = "user")
@@ -235,4 +178,4 @@
235178 this.gender = val;
236179 }
237180 }
238-}
No newline at the end of the file
181+}
deleted driver-mapping/src/test/java/com/datastax/driver/mapping/MapperEnumTest.java +0 −130
@@ -1,130 +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.util.Collection;
19-
20-import com.google.common.collect.Lists;
21-import org.testng.annotations.Test;
22-
23-import static org.testng.Assert.assertNull;
24-
25-import com.datastax.driver.core.CCMBridge;
26-import com.datastax.driver.mapping.annotations.Enumerated;
27-import com.datastax.driver.mapping.annotations.PartitionKey;
28-import com.datastax.driver.mapping.annotations.Table;
29-
30-/**
31- * Covers handling of enum fields by the mapper.
32- */
33-public class MapperEnumTest extends CCMBridge.PerClassSingleNodeCluster {
34-
35- @Override
36- protected Collection<String> getTableDefinitions() {
37- return Lists.newArrayList("CREATE TABLE asOrdinal (k int primary key, v int)",
38- "CREATE TABLE asString (k int primary key, v text)");
39- }
40-
41- public enum Enum {
42- FOO, BAR
43- }
44-
45- @Test(groups = "short")
46- public void should_handle_null_enum_as_ordinal() {
47- Mapper<AsOrdinal> mapper = new MappingManager(session).mapper(AsOrdinal.class);
48-
49- mapper.save(new AsOrdinal(1, null));
50- AsOrdinal o = mapper.get(1);
51-
52- assertNull(o.getV());
53- }
54-
55- @Test(groups = "short")
56- public void should_handle_null_enum_as_string() {
57- Mapper<AsString> mapper = new MappingManager(session).mapper(AsString.class);
58-
59- mapper.save(new AsString(1, null));
60- AsString o = mapper.get(1);
61-
62- assertNull(o.getV());
63- }
64-
65- @Table(name = "asOrdinal")
66- public static class AsOrdinal {
67- @PartitionKey
68- private int k;
69-
70- @Enumerated(EnumType.ORDINAL)
71- private Enum v;
72-
73- public AsOrdinal(Integer k, Enum v) {
74- this.k = k;
75- this.v = v;
76- }
77-
78- public AsOrdinal() {
79- }
80-
81- public int getK() {
82- return k;
83- }
84-
85- public void setK(int k) {
86- this.k = k;
87- }
88-
89- public Enum getV() {
90- return v;
91- }
92-
93- public void setV(Enum v) {
94- this.v = v;
95- }
96- }
97-
98- @Table(name = "asString")
99- public static class AsString {
100- @PartitionKey
101- private int k;
102-
103- @Enumerated(EnumType.STRING)
104- private Enum v;
105-
106- public AsString(Integer k, Enum v) {
107- this.k = k;
108- this.v = v;
109- }
110-
111- public AsString() {
112- }
113-
114- public int getK() {
115- return k;
116- }
117-
118- public void setK(int k) {
119- this.k = k;
120- }
121-
122- public Enum getV() {
123- return v;
124- }
125-
126- public void setV(Enum v) {
127- this.v = v;
128- }
129- }
130-}
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperTest.java +13 −41
@@ -28,7 +28,6 @@
2828 import static org.assertj.core.api.Assertions.assertThat;
2929 import static org.testng.Assert.*;
3030
31-import com.datastax.driver.mapping.MapperTest.User.Gender;
3231 import com.datastax.driver.mapping.annotations.*;
3332 import com.datastax.driver.core.*;
3433 import com.datastax.driver.core.utils.UUIDs;
@@ -38,6 +37,7 @@
3837 */
3938 public class MapperTest extends CCMBridge.PerClassSingleNodeCluster {
4039
40+ @Override
4141 protected Collection<String> getTableDefinitions() {
4242 // We'll allow to generate those create statement from the annotated entities later, but it's currently
4343 // a TODO
@@ -56,6 +56,7 @@
5656 *
5757 * And the next step will be to support UDT (which should be relatively simple).
5858 */
59+ @SuppressWarnings("unused")
5960 @Table(name = "users",
6061 readConsistency="QUORUM",
6162 writeConsistency="QUORUM")
@@ -64,8 +65,6 @@
6465 // Dummy constant to test that static fields are properly ignored
6566 public static final int FOO = 1;
6667
67- public enum Gender { FEMALE, MALE }
68-
6968 @PartitionKey
7069 @Column(name = "user_id")
7170 private UUID userId;
@@ -75,15 +74,12 @@
7574 @Column // not strictly required, but we want to check that the annotation works without a name
7675 private int year;
7776
78- private Gender gender;
79-
8077 public User() {}
8178
82- public User(String name, String email, Gender gender) {
79+ public User(String name, String email) {
8380 this.userId = UUIDs.random();
8481 this.name = name;
8582 this.email = email;
86- this.gender = gender;
8783 }
8884
8985 public UUID getUserId() {
@@ -114,14 +110,6 @@
114110 return year;
115111 }
116112
117- public void setGender(Gender gender) {
118- this.gender = gender;
119- }
120-
121- public Gender getGender() {
122- return gender;
123- }
124-
125113 public void setYear(int year) {
126114 this.year = year;
127115 }
@@ -135,13 +123,12 @@
135123 return Objects.equal(userId, that.userId)
136124 && Objects.equal(name, that.name)
137125 && Objects.equal(email, that.email)
138- && Objects.equal(year, that.year)
139- && Objects.equal(gender, that.gender);
126+ && Objects.equal(year, that.year);
140127 }
141128
142129 @Override
143130 public int hashCode() {
144- return Objects.hashCode(userId, name, email, year, gender);
131+ return Objects.hashCode(userId, name, email, year);
145132 }
146133 }
147134
@@ -151,6 +138,7 @@
151138 * the order must be specified (@ClusteringColumn(0), @ClusteringColumn(1), ...).
152139 * The same stands for the @PartitionKey.
153140 */
141+ @SuppressWarnings("unused")
154142 @Table(name = "posts")
155143 public static class Post {
156144
@@ -268,7 +256,7 @@
268256 // harcoded arg0, arg1, .... A big annoying, and apparently Java 8 will fix that
269257 // somehow, but well, not a huge deal.
270258 @Query("SELECT * FROM posts WHERE user_id=:userId AND post_id=:postId")
271- public Post getOne(@Param("userId") UUID userId,
259+ Post getOne(@Param("userId") UUID userId,
272260 @Param("postId") UUID postId);
273261
274262 // Note that the following method will be asynchronous (it will use executeAsync
@@ -276,23 +264,16 @@
276264 // that we need to map the result to the Post entity thanks to the return type.
277265 @Query("SELECT * FROM posts WHERE user_id=?")
278266 @QueryParameters(consistency="QUORUM")
279- public ListenableFuture<Result<Post>> getAllAsync(UUID userId);
267+ ListenableFuture<Result<Post>> getAllAsync(UUID userId);
280268
281269 // The method above actually query stuff, but if a method is declared to return
282270 // a Statement, it will not execute anything, but just return you the BoundStatement
283271 // ready for execution. That way, you can batch stuff for instance (see usage below).
284272 @Query("UPDATE posts SET content=? WHERE user_id=? AND post_id=?")
285- public Statement updateContentQuery(String newContent, UUID userId, UUID postId);
273+ Statement updateContentQuery(String newContent, UUID userId, UUID postId);
286274
287275 @Query("SELECT * FROM posts")
288- public Result<Post> getAll();
289- }
290-
291- @Accessor
292- public interface UserAccessor {
293- // Demonstrates use of an enum as an accessor parameter
294- @Query("UPDATE users SET name=?, gender=? WHERE user_id=?")
295- ResultSet updateNameAndGender(String name, Gender gender, UUID userId);
276+ Result<Post> getAll();
296277 }
297278
298279 @Test(groups = "short")
@@ -302,7 +283,7 @@
302283 // supported by the Mapper object.
303284 Mapper<User> m = new MappingManager(session).mapper(User.class);
304285
305- User u1 = new User("Paul", "paul@yahoo.com", User.Gender.MALE);
286+ User u1 = new User("Paul", "paul@yahoo.com");
306287 u1.setYear(2014);
307288 m.save(u1);
308289
@@ -320,7 +301,7 @@
320301
321302 Mapper<Post> m = manager.mapper(Post.class);
322303
323- User u1 = new User("Paul", "paul@gmail.com", User.Gender.MALE);
304+ User u1 = new User("Paul", "paul@gmail.com");
324305 Post p1 = new Post(u1, "Something about mapping");
325306 Post p2 = new Post(u1, "Something else");
326307 Post p3 = new Post(u1, "Something more");
@@ -372,15 +353,6 @@
372353
373354 assertTrue(postAccessor.getAllAsync(u1.getUserId()).get().isExhausted());
374355
375- // Pass an enum constant as an accessor parameter
376- UserAccessor userAccessor = manager.createAccessor(UserAccessor.class);
377- userAccessor.updateNameAndGender("Paule", User.Gender.FEMALE, u1.getUserId());
378- Mapper<User> userMapper = manager.mapper(User.class);
379- assertEquals(userMapper.get(u1.getUserId()).getGender(), User.Gender.FEMALE);
380-
381- // Test that an enum value can be unassigned through an accessor (set to null).
382- userAccessor.updateNameAndGender("Paule", null, u1.getUserId());
383- assertEquals(userMapper.get(u1.getUserId()).getGender(), null);
384356 }
385357
386358 @Test(groups="short")
@@ -390,7 +362,7 @@
390362 Mapper<Post> m = manager.mapper(Post.class);
391363
392364 // Insert a few posts
393- User u1 = new User("Paul", "paul@gmail.com", User.Gender.MALE);
365+ User u1 = new User("Paul", "paul@gmail.com");
394366 Post p1 = new Post(u1, "Something about mapping");
395367 Post p2 = new Post(u1, "Something else");
396368 Post p3 = new Post(u1, "Something more");
modified features/object_mapper/creating/README.md +0 −25
@@ -82,31 +82,6 @@
8282 [cc]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/ClusteringColumn.html
8383 [pks]:http://thelastpickle.com/blog/2013/01/11/primary-keys-in-cql.html
8484
85-#### Enumerations
86-
87-[@Enumerated][enum] is used to map Java enumerations. Since Cassandra
88-does not support enumerations, the object mapper defines two ways to
89-persist an enum value :
90-
91-- `EnumType.ORDINAL` : the value is persisted as a Cassandra's `int` and
92- its value is its position in the enum.
93-- `EnumType.STRING` : the value is persisted as a Cassandra's `text` and
94- its value is its name in the enum.
95-
96-According to the chosen type, the matching database column must be the
97-same type.
98-
99-```
100-CREATE TABLE person (id uuid PRIMARY KEY, name text, gender int);
101-```
102-
103-```java
104-@Enumerated(EnumType.ORDINAL)
105-private Gender gender;
106-```
107-
108-[enum]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/mapping/annotations/Enumerated.html
109-
11085 #### Computed fields
11186
11287 [@Computed][computed] can be used on fields that are the result of a
modified upgrade_guide/README.md +22 −0
@@ -208,6 +208,28 @@
208208 20. `TableMetadata.Options` has been made a top-level class and renamed to
209209 `TableOptionsMetadata`. It is now also used by `MaterializedViewMetadata`.
210210
211+21. The mapper annotation `@Enumerated` has been removed, users should now
212+ use the newly-introduced `driver-extras` module to get automatic
213+ enum-to-CQL mappings. Two new codecs provide the same functionality:
214+ `EnumOrdinalCodec` and `EnumNameCodec`:
215+
216+ ```java
217+ enum Foo {...}
218+ enum Bar {...}
219+
220+ // register the appropriate codecs
221+ CodecRegistry.DEFAULT_INSTANCE
222+ .register(new EnumOrdinalCodec<Foo>(Foo.class))
223+ .register(new EnumNameCodec<Bar>(Bar.class))
224+
225+ // the following mappings are handled out-of-the-box
226+ @Table
227+ public class MyPojo {
228+ private Foo foo;
229+ private List<Bar> bars;
230+ ...
231+ }
232+ ```
211233
212234 ### 2.1.8
213235