question

Ryan Quey avatar image
Ryan Quey asked smadhavan edited

How can I append or prepend to a Collection using Java Driver DAO?

For Java Driver 4.6, is it possible to use the DAO interface to append or prepend to a collection column (ie, a SET or a LIST), rather than overwriting it?

I understand that I can just write a custom query using @Query annotation and writing out the whole query, but it would be nice to just keep all the defaults that a @Update method would do, besides for this one list that I want to append to.

My table (podcasts) has a column (found_by_queries) definition that looks like this:

CREATE TABLE podcasts (
  ...
  found_by_queries LIST<frozen<search_query>>
  ...
)

`search_query` is a UDT if it makes a difference:

CREATE TYPE search_query (term TEXT, search_type TEXT, external_api TEXT, updated_at TIMESTAMP);

And the DAO definition is pretty standard:

@Update
void save(Podcast podcast);

Currently calling `save` seems to overwrite my `found_by_queries` list rather than append. Is there a way to append or prepend instead?

Thanks!

driverjavacollections
10 |1000

Up to 8 attachments (including images) can be used with a maximum of 1.0 MiB each and 10.0 MiB total.

smadhavan avatar image
smadhavan answered smadhavan edited

@Ryan Quey, the mapper generates regular assignments for all kinds of columns, including collections. If you need instead to prepend or append to a collection, you will need to generate the query yourself. This is typically done with a "query provider" class. See our manual for details: https://docs.datastax.com/en/developer/java-driver/4.6/manual/mapper/daos/queryprovider/. I have created JAVA-2802 to bring custom assignments feature to Mapper based approach.

Share
10 |1000

Up to 8 attachments (including images) can be used with a maximum of 1.0 MiB each and 10.0 MiB total.

Erick Ramirez avatar image
Erick Ramirez answered Ryan Quey commented

The quick answer is yes, but I suspect there's a bit more nuance in your question.

If you provide the sample code you've already tried, along with your expected outcome and what did/didn't work, I'd be happy to update my answer. Cheers!

1 comment Share
10 |1000

Up to 8 attachments (including images) can be used with a maximum of 1.0 MiB each and 10.0 MiB total.

Ryan Quey avatar image Ryan Quey commented ·

I added more details in the question, let me know if there's something else you need too, thanks!

0 Likes 0 ·
alexandre.dutra avatar image
alexandre.dutra answered

As you guessed already, and as others suggested, you should either use @Query or @QueryProvider.

I'm personally not really in favor of implementing appends and prepends in @Update queries; this would make the contract of @Update more complex, and moreover, appends and prepends on lists are not idempotent, and because of that, should be used carefully.

Share
10 |1000

Up to 8 attachments (including images) can be used with a maximum of 1.0 MiB each and 10.0 MiB total.