Elffuss BraidHub

kikocis/java-driver public

Add mapper option to configure whether to save null fields (JAVA-473).
Changeset21d094a922a5e13b1b7fe5f7ac07251a57d858a5663df9aebee1ca2547854cab
AuthorKevin Gallardo <kevin.gallardo@datastax.com> · 2015-05-22 10:37 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2015-07-01 15:18 +02:00
Parents22494c9e09ae

Browse the files at this changeset

7 files changed

modified changelog/README.md +1 −0
@@ -21,6 +21,7 @@
2121 - [improvement] Support CONTAINS / CONTAINS KEY in QueryBuilder (JAVA-677)
2222 - [improvement] Add USING options in mapper for delete and save
2323 operations (JAVA-477/JAVA-540)
24+- [improvement] Add mapper option to configure whether to save null fields (JAVA-473)
2425
2526 Merged from 2.0 branch:
2627
modified driver-mapping/src/main/java/com/datastax/driver/mapping/Mapper.java +93 −15
@@ -32,9 +32,12 @@
3232 import com.datastax.driver.core.querybuilder.Delete;
3333 import com.datastax.driver.core.querybuilder.Insert;
3434 import com.datastax.driver.core.querybuilder.QueryBuilder;
35+import com.datastax.driver.mapping.Mapper.Option.SaveNullFields;
3536 import com.datastax.driver.mapping.annotations.Accessor;
3637 import com.datastax.driver.mapping.annotations.Computed;
3738
39+import static com.datastax.driver.mapping.Mapper.Option.Type.SAVE_NULL_FIELDS;
40+
3841 /**
3942 * An object handling the mapping of a particular class.
4043 * <p>
@@ -100,16 +103,16 @@
100103 return manager.getSession();
101104 }
102105
103- PreparedStatement getPreparedQuery(QueryType type, EnumMap<Option.Type, Option> options) {
106+ PreparedStatement getPreparedQuery(QueryType type, Set<ColumnMapper<?>> columns, EnumMap<Option.Type, Option> options) {
104107
105- MapperQueryKey pqk = new MapperQueryKey(type, options);
108+ MapperQueryKey pqk = new MapperQueryKey(type, columns, options);
106109
107110 PreparedStatement stmt = preparedQueries.get(pqk);
108111 if (stmt == null) {
109112 synchronized (preparedQueries) {
110113 stmt = preparedQueries.get(pqk);
111114 if (stmt == null) {
112- String queryString = type.makePreparedQueryString(tableMetadata, mapper, manager, options.values());
115+ String queryString = type.makePreparedQueryString(tableMetadata, mapper, manager, columns, options.values());
113116 logger.debug("Preparing query {}", queryString);
114117 stmt = session().prepare(queryString);
115118 Map<MapperQueryKey, PreparedStatement> newQueries = new HashMap<MapperQueryKey, PreparedStatement>(preparedQueries);
@@ -121,6 +124,10 @@
121124 return stmt;
122125 }
123126
127+ PreparedStatement getPreparedQuery(QueryType type, EnumMap<Option.Type, Option> options) {
128+ return getPreparedQuery(type, Collections.<ColumnMapper<?>>emptySet(), options);
129+ }
130+
124131 /**
125132 * The {@code TableMetadata} for this mapper.
126133 *
@@ -180,15 +187,24 @@
180187 }
181188
182189 private Statement saveQuery(T entity, EnumMap<Option.Type, Option> options) {
183- BoundStatement bs = getPreparedQuery(QueryType.SAVE, options).bind();
184- int i = 0;
190+ Map<ColumnMapper<?>, Object> values = new HashMap<ColumnMapper<?>, Object>();
191+ boolean saveNullFields = shouldSaveNullFields(options);
192+
185193 for (ColumnMapper<T> cm : mapper.allColumns()) {
186- if (cm.kind != ColumnMapper.Kind.COMPUTED) {
187- Object value = cm.getValue(entity);
188- bs.setBytesUnsafe(i++, value == null ? null : cm.getDataType().serialize(value, protocolVersion));
194+ Object value = cm.getValue(entity);
195+ if (cm.kind != ColumnMapper.Kind.COMPUTED && (saveNullFields || value != null)) {
196+ values.put(cm, value);
189197 }
190198 }
191199
200+ BoundStatement bs = getPreparedQuery(QueryType.SAVE, values.keySet(), options).bind();
201+ int i = 0;
202+ for (Map.Entry<ColumnMapper<?>, Object> entry : values.entrySet()) {
203+ DataType type = entry.getKey().getDataType();
204+ Object value = entry.getValue();
205+ bs.setBytesUnsafe(i++, value == null ? null : type.serialize(value, protocolVersion));
206+ }
207+
192208 if (mapper.writeConsistency != null)
193209 bs.setConsistencyLevel(mapper.writeConsistency);
194210
@@ -200,6 +216,11 @@
200216 return bs;
201217 }
202218
219+ private static boolean shouldSaveNullFields(EnumMap<Option.Type, Option> options) {
220+ SaveNullFields option = (SaveNullFields)options.get(SAVE_NULL_FIELDS);
221+ return option == null || option.saveNullFields;
222+ }
223+
203224 /**
204225 * Save an entity mapped by this mapper.
205226 * <p>
@@ -307,8 +328,7 @@
307328 if (value == null) {
308329 throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i));
309330 }
310- bs.setBytesUnsafe(i, column.getDataType().serialize(value, protocolVersion));
311- i++;
331+ bs.setBytesUnsafe(i++, column.getDataType().serialize(value, protocolVersion));
312332 }
313333
314334 if (mapper.readConsistency != null)
@@ -709,7 +729,7 @@
709729 */
710730 public static abstract class Option {
711731
712- enum Type {TTL, TIMESTAMP, CL, TRACING}
732+ enum Type {TTL, TIMESTAMP, CL, TRACING, SAVE_NULL_FIELDS}
713733
714734 final Type type;
715735
@@ -760,7 +780,8 @@
760780 }
761781
762782 /**
763- * Creates a new Option object to enable query tracing for a mapper operation.
783+ * Creates a new Option object to enable query tracing for a mapper operation. This
784+ * is valid for save, delete and get operations.
764785 *
765786 * @param enabled whether to enable tracing.
766787 * @return the option.
@@ -769,6 +790,23 @@
769790 return new Tracing(enabled);
770791 }
771792
793+ /**
794+ * Creates a new Option object to specify whether null entity fields should be included in
795+ * insert queries. This option is valid only for save operations.
796+ *
797+ * If this option is not specified, it defaults to {@code true} (null fields are saved).
798+ *
799+ * @param enabled whether to include null fields in queries.
800+ * @return the option.
801+ */
802+ public static Option saveNullFields(boolean enabled){
803+ return new SaveNullFields(enabled);
804+ }
805+
806+ public Type getType(){
807+ return this.type;
808+ }
809+
772810 abstract void appendTo(Insert.Options usings);
773811
774812 abstract void appendTo(Delete.Options usings);
@@ -908,16 +946,55 @@
908946 return false;
909947 }
910948 }
949+
950+ static class SaveNullFields extends Option {
951+
952+ private boolean saveNullFields;
953+
954+ SaveNullFields(boolean saveNullFields) {
955+ super(SAVE_NULL_FIELDS);
956+ this.saveNullFields = saveNullFields;
957+ }
958+
959+ @Override
960+ void appendTo(Insert.Options usings) {
961+ throw new UnsupportedOperationException("shouldn't be called");
962+ }
963+
964+ @Override
965+ void appendTo(Delete.Options usings) {
966+ throw new UnsupportedOperationException("shouldn't be called");
967+ }
968+
969+ @Override
970+ void addToPreparedStatement(BoundStatement bs, int i) {
971+ // nothing to do
972+ }
973+
974+ @Override
975+ void checkValidFor(QueryType qt, MappingManager manager) {
976+ checkArgument(qt == QueryType.SAVE, "SaveNullFields option is only allowed in save queries");
977+ }
978+
979+ @Override
980+ boolean isIncludedInQuery() {
981+ return false;
982+ }
983+ }
984+
911985 }
912986
913987 private static class MapperQueryKey {
914988 private final QueryType queryType;
915989 private final EnumSet<Option.Type> optionTypes;
990+ private final Set<ColumnMapper<?>> columns;
916991
917- MapperQueryKey(QueryType queryType, EnumMap<Option.Type, Option> options) {
992+ MapperQueryKey(QueryType queryType, Set<ColumnMapper<?>> columnMappers, EnumMap<Option.Type, Option> options) {
918993 Preconditions.checkNotNull(queryType);
919994 Preconditions.checkNotNull(options);
995+ Preconditions.checkNotNull(columnMappers);
920996 this.queryType = queryType;
997+ this.columns = columnMappers;
921998 this.optionTypes = EnumSet.noneOf(Option.Type.class);
922999 for (Option opt : options.values()) {
9231000 if (opt.isIncludedInQuery())
@@ -932,13 +1009,14 @@
9321009 if (other instanceof MapperQueryKey) {
9331010 MapperQueryKey that = (MapperQueryKey)other;
9341011 return this.queryType.equals(that.queryType)
935- && this.optionTypes.equals(that.optionTypes);
1012+ && this.optionTypes.equals(that.optionTypes)
1013+ && this.columns.equals(that.columns);
9361014 }
9371015 return false;
9381016 }
9391017
9401018 public int hashCode() {
941- return Objects.hashCode(queryType, optionTypes);
1019+ return Objects.hashCode(queryType, optionTypes, columns);
9421020 }
9431021 }
9441022 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/QueryType.java +3 −2
@@ -18,6 +18,7 @@
1818 import java.util.ArrayList;
1919 import java.util.Collection;
2020 import java.util.List;
21+import java.util.Set;
2122
2223 import com.google.common.base.Objects;
2324
@@ -60,13 +61,13 @@
6061 return new QueryType(reversed ? Kind.REVERSED_SLICE : Kind.SLICE, startBoundSize, startInclusive, endBoundSize, endInclusive);
6162 }
6263
63- String makePreparedQueryString(TableMetadata table, EntityMapper<?> mapper, MappingManager manager, Collection<Mapper.Option> options) {
64+ String makePreparedQueryString(TableMetadata table, EntityMapper<?> mapper, MappingManager manager, Set<ColumnMapper<?>> columns, Collection<Mapper.Option> options) {
6465 switch (kind) {
6566 case SAVE: {
6667 Insert insert = table == null
6768 ? insertInto(mapper.getKeyspace(), mapper.getTable())
6869 : insertInto(table);
69- for (ColumnMapper<?> cm : mapper.allColumns())
70+ for (ColumnMapper<?> cm : columns)
7071 if (cm.kind != ColumnMapper.Kind.COMPUTED)
7172 insert.value(cm.getColumnName(), bindMarker());
7273
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperComputedFieldsTest.java +19 −1
@@ -18,9 +18,11 @@
1818 import java.util.Collection;
1919
2020 import com.google.common.collect.Lists;
21+import org.testng.SkipException;
2122 import org.testng.annotations.BeforeMethod;
2223 import org.testng.annotations.Test;
2324
25+import static com.datastax.driver.core.ProtocolVersion.V1;
2426 import static org.assertj.core.api.Assertions.fail;
2527
2628 import com.datastax.driver.core.*;
@@ -35,7 +37,6 @@
3537 * annotation to map computed fields.
3638 */
3739 @SuppressWarnings("unused")
38-@CassandraVersion(major = 2.0)
3940 public class MapperComputedFieldsTest extends CCMBridge.PerClassSingleNodeCluster {
4041
4142 @Override
@@ -45,16 +46,28 @@
4546 "INSERT INTO user (login, name) VALUES ('testlogin', 'test name')");
4647 }
4748
49+ ProtocolVersion protocolVersion;
4850 MappingManager mappingManager;
4951 Mapper<User> userMapper;
5052
5153 @BeforeMethod(groups = "short")
5254 void setup() {
5355 mappingManager = new MappingManager(session);
56+ protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum();
57+ if (protocolVersion.compareTo(V1) > 0)
58+ userMapper = mappingManager.mapper(User.class);
59+ }
60+
61+ @Test(groups = "short", expectedExceptions = { UnsupportedOperationException.class })
62+ void should_get_unsupported_operation_exception_on_v1() {
63+ if (protocolVersion.compareTo(V1) > 0)
64+ throw new SkipException("Skipped when protocol version > V1");
65+
5466 userMapper = mappingManager.mapper(User.class);
5567 }
5668
5769 @Test(groups = "short")
70+ @CassandraVersion(major = 2.0)
5871 void should_save_and_get_entity_with_computed_fields() {
5972 long writeTime = System.currentTimeMillis() * 1000;
6073 User newUser = new User("testlogin2", "blah");
@@ -80,6 +93,7 @@
8093 }
8194
8295 @Test(groups = "short")
96+ @CassandraVersion(major = 2.0)
8397 void should_add_aliases_for_fields_in_select_queries() {
8498 BoundStatement bs = (BoundStatement)userMapper.getQuery("test");
8599 assertThat(bs.preparedStatement().getQueryString())
@@ -87,6 +101,7 @@
87101 }
88102
89103 @Test(groups = "short")
104+ @CassandraVersion(major = 2.0)
90105 public void should_map_aliased_resultset_to_objects() {
91106 Statement getQuery = userMapper.getQuery("testlogin");
92107 getQuery.setConsistencyLevel(ConsistencyLevel.QUORUM);
@@ -99,6 +114,7 @@
99114 }
100115
101116 @Test(groups = "short")
117+ @CassandraVersion(major = 2.0)
102118 void should_map_unaliased_resultset_to_objects() {
103119 UserAccessor userAccessor = mappingManager.createAccessor(UserAccessor.class);
104120 ResultSet rs = userAccessor.all();
@@ -110,11 +126,13 @@
110126 }
111127
112128 @Test(groups = "short", expectedExceptions = IllegalArgumentException.class)
129+ @CassandraVersion(major = 2.0)
113130 void should_fail_if_computed_field_is_not_right_type() {
114131 mappingManager.mapper(User_WrongComputedType.class);
115132 }
116133
117134 @Test(groups = "short")
135+ @CassandraVersion(major = 2.0)
118136 void should_fail_if_computed_field_marked_with_column_annotation() {
119137 Mapper<User_WrongAnnotationForComputed> mapper = mappingManager.mapper(User_WrongAnnotationForComputed.class);
120138 try {
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperOptionTest.java +36 −12
@@ -23,6 +23,7 @@
2323 import org.testng.annotations.BeforeMethod;
2424 import org.testng.annotations.Test;
2525
26+import static com.datastax.driver.core.ConsistencyLevel.*;
2627 import static org.assertj.core.api.Assertions.assertThat;
2728 import static org.assertj.core.api.Assertions.fail;
2829
@@ -33,7 +34,6 @@
3334 import com.datastax.driver.mapping.annotations.PartitionKey;
3435 import com.datastax.driver.mapping.annotations.Table;
3536
36-import static com.datastax.driver.core.ConsistencyLevel.TWO;
3737 import static com.datastax.driver.core.ProtocolVersion.V1;
3838 import static com.datastax.driver.mapping.Mapper.Option;
3939
@@ -55,9 +55,9 @@
5555
5656 @Test(groups = "short")
5757 @CassandraVersion(major = 2.0)
58- void should_use_save_options() {
58+ void should_use_save_options() throws Exception {
5959 Long tsValue = futureTimestamp();
60- mapper.saveAsync(new User(42, "helloworld"), Option.timestamp(tsValue), Option.tracing(true));
60+ mapper.save(new User(42, "helloworld"), Option.timestamp(tsValue), Option.tracing(true));
6161 assertThat(mapper.get(42).getV()).isEqualTo("helloworld");
6262 Long tsReturned = session.execute("SELECT writetime(v) FROM user WHERE key=" + 42).one().getLong(0);
6363 assertThat(tsReturned).isEqualTo(tsValue);
@@ -69,21 +69,24 @@
6969 User todelete = new User(45, "todelete");
7070 mapper.save(todelete);
7171 Option opt = Option.timestamp(35);
72- BoundStatement bs = (BoundStatement)mapper.deleteQuery(45, opt, Option.consistencyLevel(ConsistencyLevel.ALL));
72+ BoundStatement bs = (BoundStatement)mapper.deleteQuery(45, opt, Option.consistencyLevel(QUORUM));
7373 assertThat(bs.preparedStatement().getQueryString()).contains("USING TIMESTAMP");
74+ assertThat(bs.getConsistencyLevel()).isEqualTo(QUORUM);
7475 }
7576
7677 @Test(groups = "short", expectedExceptions = {IllegalArgumentException.class})
7778 @CassandraVersion(major = 2.0)
7879 void should_use_get_options() {
79- User todelete = new User(45, "toget");
80- mapper.save(todelete);
80+ User user = new User(45, "toget");
81+ mapper.save(user);
8182
82- Option opt = Option.tracing(true);
83- BoundStatement bs = (BoundStatement)mapper.getQuery(45, opt);
83+ BoundStatement bs = (BoundStatement)mapper.getQuery(45, Option.tracing(true), Option.consistencyLevel(ALL));
8484 assertThat(bs.isTracing()).isTrue();
85-
86- User us = mapper.mapAliased(session.execute(bs)).one();
85+ assertThat(bs.getConsistencyLevel()).isEqualTo(ALL);
86+
87+ ResultSet rs = session.execute(bs);
88+ assertThat(rs.getExecutionInfo().getQueryTrace()).isNotNull();
89+ User us = mapper.mapAliased(rs).one();
8790 assertThat(us.getV()).isEqualTo("toget");
8891
8992 mapper.getQuery(45, Option.timestamp(1337));
@@ -133,6 +136,27 @@
133136 assertThat(bs.isTracing()).isFalse();
134137 }
135138
139+ @Test(groups = "short")
140+ @CassandraVersion(major = 2.0)
141+ void should_prioritize_option_over_model_consistency() {
142+ // Generate Write Query and ensure User model writeConsistency is used.
143+ User user = new User(1859, "Steve");
144+ Statement saveDefault = mapper.saveQuery(user);
145+ assertThat(saveDefault.getConsistencyLevel()).isEqualTo(ONE);
146+
147+ // Generate Write Query and ensure provided Option for consistencyLevel is used.
148+ Statement saveProvidedCL = mapper.saveQuery(user, Option.consistencyLevel(QUORUM));
149+ assertThat(saveProvidedCL.getConsistencyLevel()).isEqualTo(QUORUM);
150+
151+ // Generate Read Query and ensure User model readConsistency is used.
152+ Statement readDefault = mapper.getQuery(1859);
153+ assertThat(readDefault.getConsistencyLevel()).isEqualTo(LOCAL_ONE);
154+
155+ // Generate Ready Query and ensure provided Option for consistencyLevel is used.
156+ Statement readProvidedCL = mapper.getQuery(1859, Option.consistencyLevel(LOCAL_QUORUM));
157+ assertThat(readProvidedCL.getConsistencyLevel()).isEqualTo(LOCAL_QUORUM);
158+ }
159+
136160 @Test(groups = "short")
137161 @CassandraVersion(major = 2.0)
138162 void should_use_explicit_options_over_default_options() {
@@ -333,14 +357,14 @@
333357 private static void assertFirstNodeUnavailable(ExecutionException e) {
334358 Throwable cause = e.getCause();
335359 assertThat(cause).isInstanceOf(NoHostAvailableException.class);
336- assertFirstNodeUnavailable((NoHostAvailableException)cause);
360+ assertFirstNodeUnavailable((NoHostAvailableException) cause);
337361 }
338362
339363 private static long futureTimestamp() {
340364 return (System.currentTimeMillis() + 1000) * 1000;
341365 }
342366
343- @Table(name = "user", writeConsistency = "ONE")
367+ @Table(name = "user", readConsistency = "LOCAL_ONE", writeConsistency = "ONE")
344368 public static class User {
345369 @PartitionKey
346370 private int key;
added driver-mapping/src/test/java/com/datastax/driver/mapping/MapperSaveNullFieldsTest.java +151 −0
@@ -0,0 +1,151 @@
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.BeforeMethod;
22+import org.testng.annotations.Test;
23+
24+import static org.assertj.core.api.Assertions.assertThat;
25+
26+import com.datastax.driver.core.BoundStatement;
27+import com.datastax.driver.core.CCMBridge;
28+import com.datastax.driver.mapping.Mapper.Option;
29+import com.datastax.driver.mapping.annotations.PartitionKey;
30+import com.datastax.driver.mapping.annotations.Table;
31+
32+public class MapperSaveNullFieldsTest extends CCMBridge.PerClassSingleNodeCluster {
33+
34+ Mapper<User> mapper;
35+
36+ @Override
37+ protected Collection<String> getTableDefinitions() {
38+ return Lists.newArrayList("CREATE TABLE user (login text primary key, name text, phone text)");
39+ }
40+
41+ @BeforeMethod(groups = "short")
42+ public void setup() {
43+ mapper = new MappingManager(session).mapper(User.class);
44+ }
45+
46+ @Test(groups = "short")
47+ void should_save_null_fields_if_requested() {
48+ should_save_null_fields(true, Option.saveNullFields(true));
49+
50+ mapper.setDefaultSaveOptions(Option.saveNullFields(true));
51+ should_save_null_fields(true);
52+ }
53+
54+ @Test(groups = "short")
55+ void should_save_null_fields_by_default() {
56+ should_save_null_fields(true);
57+ }
58+
59+ @Test(groups = "short")
60+ void should_ignore_null_fields_if_requested() {
61+ should_save_null_fields(false, Option.saveNullFields(false));
62+
63+ mapper.setDefaultSaveOptions(Option.saveNullFields(false));
64+ should_save_null_fields(false);
65+ }
66+
67+ private void should_save_null_fields(boolean saveExpected, Option... options) {
68+ // Try different combinations of null fields
69+ should_save_null_fields(true, true, saveExpected, options);
70+ should_save_null_fields(true, false, saveExpected, options);
71+ should_save_null_fields(false, true, saveExpected, options);
72+ should_save_null_fields(false, false, saveExpected, options);
73+ }
74+
75+ private void should_save_null_fields(boolean nullName, boolean nullPhone, boolean saveExpected, Option... options) {
76+ // Start with clean data
77+ session.execute("insert into user(login, name, phone) "
78+ + "values ('test_login', 'previous_name', 'previous_phone')");
79+
80+ String newName = nullName ? null : "new_name";
81+ String newPhone = nullPhone ? null : "new_phone";
82+ String description = String.format("update with name=%s, phone = %s", newName, newPhone);
83+ User newUser = new User("test_login", newName, newPhone);
84+
85+ // Check if null fields are included in generated statement:
86+ BoundStatement bs = (BoundStatement)mapper.saveQuery(newUser, options);
87+ String queryString = bs.preparedStatement().getQueryString();
88+ if (nullName && !saveExpected)
89+ assertThat(queryString).as(description).doesNotContain("\"name\"");
90+ else
91+ assertThat(queryString).as(description).contains("\"name\"");
92+
93+ if (nullPhone && !saveExpected)
94+ assertThat(queryString).as(description).doesNotContain("\"phone\"");
95+ else
96+ assertThat(queryString).as(description).contains("\"phone\"");
97+
98+ // Save entity and check the data
99+ mapper.save(newUser, options);
100+ User savedUser = mapper.get("test_login");
101+ String expectedName = nullName
102+ ? (saveExpected ? null : "previous_name")
103+ : "new_name";
104+ String expectedPhone = nullPhone
105+ ? (saveExpected ? null : "previous_phone")
106+ : "new_phone";
107+ assertThat(savedUser.getName()).as(description).isEqualTo(expectedName);
108+ assertThat(savedUser.getPhone()).as(description).isEqualTo(expectedPhone);
109+ }
110+
111+ @Table(name = "user")
112+ public static class User {
113+ @PartitionKey
114+ private String login;
115+ private String name;
116+ private String phone;
117+
118+ public User() {
119+ }
120+
121+ public User(String login, String name, String phone) {
122+ this.login = login;
123+ this.name = name;
124+ this.phone = phone;
125+ }
126+
127+ public String getLogin() {
128+ return login;
129+ }
130+
131+ public void setLogin(String login) {
132+ this.login = login;
133+ }
134+
135+ public String getName() {
136+ return name;
137+ }
138+
139+ public void setName(String name) {
140+ this.name = name;
141+ }
142+
143+ public String getPhone() {
144+ return phone;
145+ }
146+
147+ public void setPhone(String phone) {
148+ this.phone = phone;
149+ }
150+ }
151+}
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperTest.java +13 −0
@@ -418,4 +418,17 @@
418418 // cleanup
419419 session.execute("delete from posts where user_id = " + u1.getUserId());
420420 }
421+
422+ @Test(groups="short")
423+ public void should_not_initialize_session_when_protocol_version_provided() {
424+ Session newSession = cluster.newSession();
425+
426+ // Ensures that a Session is not initialized when a protocol version is provided.
427+ MappingManager manager = new MappingManager(newSession, ProtocolVersion.V1);
428+ assertThat(newSession.getState().getConnectedHosts()).hasSize(0);
429+
430+ // Session should be initialized on first query.
431+ newSession.execute("USE " + keyspace);
432+ assertThat(newSession.getState().getConnectedHosts()).hasSize(1);
433+ }
421434 }