Elffuss BraidHub

kikocis/java-driver public

Merge pull request #600 from datastax/java831

JAVA-831: Mapper can't load an entity where the PK is a UDT.
Changeset3439c5c67fc1ff3b3932de84072bd847fa998ff1467424779fbc66f473becf97
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2016-02-26 19:18 +01:00
CommitterOlivier Michallat <olim7t@users.noreply.github.com> · 2016-02-26 19:18 +01:00
Parents913db6e02171, 24a0a4bea48d

Browse the files at this changeset

6 files changed

modified changelog/README.md +1 −0
@@ -19,6 +19,7 @@
1919 - [improvement] JAVA-1038: Fetch node info by rpc_address if its broadcast_address is not in system.peers.
2020 - [improvement] JAVA-974: Validate accessor parameter types against bound statement.
2121 - [bug] JAVA-1068: Unwrap StatementWrappers when hashing the paging state.
22+- [bug] JAVA-831: Mapper can't load an entity where the PK is a UDT.
2223
2324 Merged from 2.0 branch:
2425
modified driver-mapping/src/main/java/com/datastax/driver/mapping/ColumnMapper.java +12 −0
@@ -69,4 +69,16 @@
6969 return dataType;
7070 }
7171
72+ /**
73+ * Converts the given value to another object that
74+ * can in turn be serialized.
75+ * Some subclasses might return a different object from the given one
76+ * if the original object is not serializable as is
77+ * and requires some transformation, e.g. instances of
78+ * classes annotated with {@link com.datastax.driver.mapping.annotations.UDT}.
79+ */
80+ Object toSerializableValue(Object value) {
81+ return value;
82+ }
83+
7284 }
modified driver-mapping/src/main/java/com/datastax/driver/mapping/Mapper.java +2 −2
@@ -329,7 +329,7 @@
329329 if (value == null) {
330330 throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i));
331331 }
332- bs.setBytesUnsafe(i++, column.getDataType().serialize(value, protocolVersion));
332+ bs.setBytesUnsafe(i++, column.getDataType().serialize(column.toSerializableValue(value), protocolVersion));
333333 }
334334
335335 if (mapper.readConsistency != null)
@@ -511,7 +511,7 @@
511511 if (value == null) {
512512 throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i));
513513 }
514- bs.setBytesUnsafe(i++, column.getDataType().serialize(value, protocolVersion));
514+ bs.setBytesUnsafe(i++, column.getDataType().serialize(column.toSerializableValue(value), protocolVersion));
515515 columnNumber++;
516516 }
517517 return bs;
modified driver-mapping/src/main/java/com/datastax/driver/mapping/ReflectionMapper.java +28 −27
@@ -72,7 +72,7 @@
7272 @Override
7373 public Object getValue(T entity) {
7474 try {
75- return readMethod.invoke(entity);
75+ return toSerializableValue(readMethod.invoke(entity));
7676 } catch (IllegalArgumentException e) {
7777 throw new IllegalArgumentException("Could not get field '" + fieldName + "'");
7878 } catch (Exception e) {
@@ -111,19 +111,6 @@
111111 }
112112 }
113113
114- @SuppressWarnings("rawtypes")
115- @Override
116- public Object getValue(T entity) {
117- Object value = super.getValue(entity);
118- switch (enumType) {
119- case STRING:
120- return (value == null) ? null : value.toString();
121- case ORDINAL:
122- return (value == null) ? null : ((Enum) value).ordinal();
123- }
124- throw new AssertionError();
125- }
126-
127114 @Override
128115 public void setValue(Object entity, Object value) {
129116 Object converted = null;
@@ -137,6 +124,18 @@
137124 }
138125 super.setValue(entity, converted);
139126 }
127+
128+ @Override
129+ Object toSerializableValue(Object value) {
130+ switch (enumType) {
131+ case STRING:
132+ return (value == null) ? null : value.toString();
133+ case ORDINAL:
134+ return (value == null) ? null : ((Enum) value).ordinal();
135+ }
136+ throw new AssertionError();
137+ }
138+
140139 }
141140
142141 private static class UDTColumnMapper<T, U> extends LiteralMapper<T> {
@@ -147,13 +146,6 @@
147146 this.udtMapper = udtMapper;
148147 }
149148
150- @Override
151- public Object getValue(T entity) {
152- @SuppressWarnings("unchecked")
153- U udtEntity = (U) super.getValue(entity);
154- return udtEntity == null ? null : udtMapper.toUDT(udtEntity);
155- }
156-
157149 @Override
158150 public void setValue(Object entity, Object value) {
159151 assert value instanceof UDTValue;
@@ -162,6 +154,17 @@
162154
163155 super.setValue(entity, udtMapper.toEntity((udtValue)));
164156 }
157+
158+ @Override
159+ Object toSerializableValue(Object value) {
160+ if (value == null) {
161+ return null;
162+ } else {
163+ @SuppressWarnings("unchecked")
164+ U mappedUdt = (U) value;
165+ return udtMapper.toUDT(mappedUdt);
166+ }
167+ }
165168 }
166169
167170 private static class NestedUDTMapper<T> extends LiteralMapper<T> {
@@ -173,15 +176,13 @@
173176 }
174177
175178 @Override
176- @SuppressWarnings("unchecked")
177- public Object getValue(T entity) {
178- Object valueWithEntities = super.getValue(entity);
179- return (T) UDTMapper.convertEntitiesToUDTs(valueWithEntities, inferredCQLType);
179+ public void setValue(Object entity, Object valueWithUDTValues) {
180+ super.setValue(entity, UDTMapper.convertUDTsToEntities(valueWithUDTValues, inferredCQLType));
180181 }
181182
182183 @Override
183- public void setValue(Object entity, Object valueWithUDTValues) {
184- super.setValue(entity, UDTMapper.convertUDTsToEntities(valueWithUDTValues, inferredCQLType));
184+ Object toSerializableValue(Object value) {
185+ return UDTMapper.convertEntitiesToUDTs(value, inferredCQLType);
185186 }
186187 }
187188
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperEnumTest.java +57 −1
@@ -21,6 +21,7 @@
2121 import com.datastax.driver.mapping.annotations.Table;
2222 import org.testng.annotations.Test;
2323
24+import static org.assertj.core.api.Assertions.assertThat;
2425 import static org.junit.Assert.assertNull;
2526
2627 /**
@@ -32,7 +33,8 @@
3233 @Override
3334 public void onTestContextInitialized() {
3435 execute("CREATE TABLE asOrdinal (k int primary key, v int)",
35- "CREATE TABLE asString (k int primary key, v text)");
36+ "CREATE TABLE asString (k int primary key, v text)",
37+ "CREATE TABLE asPk (k int primary key, v int)");
3638 }
3739
3840 public enum Enum {
@@ -59,6 +61,25 @@
5961 assertNull(o.getV());
6062 }
6163
64+ /**
65+ * Ensures that an entity that has an Enum as part of its primary key
66+ * can be successfully stored and retrieved.
67+ *
68+ * @jira_ticket JAVA-831
69+ */
70+ @Test(groups = "short")
71+ public void should_handle_enum_as_primary_key() {
72+ Mapper<AsPk> mapper = new MappingManager(session()).mapper(AsPk.class);
73+
74+ mapper.save(new AsPk(Enum.FOO, 42));
75+ AsPk o = mapper.get(Enum.FOO);
76+
77+ assertThat(o.getV()).isEqualTo(42);
78+ mapper.delete(Enum.FOO);
79+
80+ assertThat(mapper.get(Enum.FOO)).isNull();
81+ }
82+
6283 @Table(name = "asOrdinal")
6384 public static class AsOrdinal {
6485 @PartitionKey
@@ -124,4 +145,39 @@
124145 this.v = v;
125146 }
126147 }
148+
149+ @Table(name = "asPk")
150+ public static class AsPk {
151+
152+ @PartitionKey
153+ @Enumerated(EnumType.ORDINAL)
154+ private Enum k;
155+
156+ private int v;
157+
158+ public AsPk(Enum k, int v) {
159+ this.k = k;
160+ this.v = v;
161+ }
162+
163+ public AsPk() {
164+ }
165+
166+ public Enum getK() {
167+ return k;
168+ }
169+
170+ public void setK(Enum k) {
171+ this.k = k;
172+ }
173+
174+ public int getV() {
175+ return v;
176+ }
177+
178+ public void setV(int v) {
179+ this.v = v;
180+ }
181+ }
182+
127183 }
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperUDTTest.java +72 −9
@@ -17,7 +17,6 @@
1717
1818 import com.datastax.driver.core.CCMTestsSupport;
1919 import com.datastax.driver.core.ResultSet;
20-import com.datastax.driver.core.utils.UUIDs;
2120 import com.datastax.driver.mapping.annotations.*;
2221 import com.google.common.base.Objects;
2322 import com.google.common.collect.Maps;
@@ -35,7 +34,8 @@
3534 @Override
3635 public void onTestContextInitialized() {
3736 execute("CREATE TYPE address (street text, city text, zip_code int, phones set<text>)",
38- "CREATE TABLE users (user_id uuid PRIMARY KEY, name text, mainaddress frozen<address>, other_addresses map<text,frozen<address>>)");
37+ "CREATE TYPE user_id (id uuid, login text)",
38+ "CREATE TABLE users (user_id frozen<user_id> PRIMARY KEY, name text, mainaddress frozen<address>, other_addresses map<text,frozen<address>>)");
3939 }
4040
4141 @BeforeMethod(groups = "short")
@@ -47,9 +47,11 @@
4747 readConsistency = "QUORUM",
4848 writeConsistency = "QUORUM")
4949 public static class User {
50+
5051 @PartitionKey
5152 @Column(name = "user_id")
52- private UUID userId;
53+ @Frozen
54+ private UserId userId;
5355
5456 private String name;
5557
@@ -64,17 +66,17 @@
6466 }
6567
6668 public User(String name, Address address) {
67- this.userId = UUIDs.random();
69+ this.userId = new UserId(UUID.randomUUID(), name);
6870 this.name = name;
6971 this.mainAddress = address;
7072 this.otherAddresses = new HashMap<String, Address>();
7173 }
7274
73- public UUID getUserId() {
75+ public UserId getUserId() {
7476 return userId;
7577 }
7678
77- public void setUserId(UUID userId) {
79+ public void setUserId(UserId userId) {
7880 this.userId = userId;
7981 }
8082
@@ -191,16 +193,59 @@
191193 }
192194 }
193195
196+ @UDT(name = "user_id")
197+ public static class UserId {
198+
199+ private UUID id;
200+
201+ private String login;
202+
203+ public UserId() {
204+ }
205+
206+ public UserId(UUID id, String login) {
207+ this.id = id;
208+ this.login = login;
209+ }
210+
211+ public UUID getId() {
212+ return id;
213+ }
214+
215+ public void setId(UUID id) {
216+ this.id = id;
217+ }
218+
219+ public String getLogin() {
220+ return login;
221+ }
222+
223+ public void setLogin(String login) {
224+ this.login = login;
225+ }
226+
227+ @Override
228+ public boolean equals(Object other) {
229+ if (other instanceof UserId) {
230+ UserId that = (UserId) other;
231+ return Objects.equal(this.id, that.id) &&
232+ Objects.equal(this.login, that.login);
233+ }
234+ return false;
235+ }
236+
237+ }
238+
194239 @Accessor
195240 public interface UserAccessor {
196241 @Query("SELECT * FROM users WHERE user_id=:userId")
197- User getOne(@Param("userId") UUID userId);
242+ User getOne(@Param("userId") UserId id);
198243
199244 @Query("UPDATE users SET other_addresses[:name]=:address WHERE user_id=:id")
200- ResultSet addAddress(@Param("id") UUID id, @Param("name") String addressName, @Param("address") Address address);
245+ ResultSet addAddress(@Param("id") UserId id, @Param("name") String addressName, @Param("address") Address address);
201246
202247 @Query("UPDATE users SET other_addresses=:addresses where user_id=:id")
203- ResultSet setOtherAddresses(@Param("id") UUID id, @Param("addresses") Map<String, Address> addresses);
248+ ResultSet setOtherAddresses(@Param("id") UserId id, @Param("addresses") Map<String, Address> addresses);
204249
205250 @Query("SELECT * FROM users")
206251 Result<User> getAll();
@@ -267,4 +312,22 @@
267312 assertEquals(u.one(), u5);
268313 assertTrue(u.isExhausted());
269314 }
315+
316+ /**
317+ * Ensures that an entity that has an UDT as part of its primary key
318+ * can be successfully stored and retrieved.
319+ *
320+ * @jira_ticket JAVA-831
321+ */
322+ @Test(groups = "short")
323+ public void should_handle_UDT_in_partition_key() throws Exception {
324+ Mapper<User> m = new MappingManager(session()).mapper(User.class);
325+ User u1 = new User("Paul", null);
326+ m.save(u1);
327+ User u2 = m.get(u1.getUserId());
328+ assertThat(u1).isEqualTo(u2);
329+ m.delete(u1.getUserId());
330+ assertThat(m.get(u1.getUserId())).isNull();
331+ }
332+
270333 }