Reputation: 602
I'm using a non AppEngine Google Cloud Datastore Java API. I store entities from outside the Google Cloud environment.
My Gradle dependency is:
compile('com.google.cloud:google-cloud-datastore:0.8.0-beta')
I have a List in an entity that I'd like to set in the Entity but there is no method to set a collection. Currently I'm setting values as follows:
/**
* It returns a Google Datastore Entity from a DTO Entity
* @param usersKey The Key to use to build the entity
* @param user The Users entity containing the data to persist
* @return A Google Datastore Entity from a DTO Entity
*/
public static Entity fromDtoToGoogleEntity(Key usersKey, User user) {
Entity.Builder builder = Entity.newBuilder(usersKey);
builder.set(User.FIRST_NAME, user.getFirstName());
builder.set(User.LAST_NAME, user.getLastName());
builder.set(User.PASSWORD, user.getPassword());
builder.set(User.EMAIL, user.getEmail());
builder.set(User.STRIPE_USER_ID, user.getStripeUserId());
builder.set(User.COUNTRY, user.getCountry());
builder.set(User.DESCRIPTION, user.getDescription());
builder.set(User.USERNAME, user.getUsername());
builder.set(User.ENABLED, user.isEnabled());
return builder.build();
}
There is no method such as:
builder.set(User.USER_ROLES, user.getUserRoles());//userRoles is a List<String>
Can anybody suggest a way? The only way so far is to have a comma separated String representation and convert from Collection to comma separated String and vice versa.
Thanks in advance.
M.
Upvotes: 0
Views: 350
Reputation: 2207
You can use either of the below methods (http://googlecloudplatform.github.io/google-cloud-java/0.8.0/apidocs/com/google/cloud/datastore/BaseEntity.Builder.html) -
set(String name, List<? extends Value<?>> values)
set(String name, String first, String second, String... others)
See also the ListValue
and ListValue.Builder
.
The first one - you just create a list of Value
objects (e.g. StringValue
) and assign the list to a property on the entity. In essence, convert your List<String>
to List<StringValue>
.
The second one is a simpler variation with String
var args, where you can pass your two or more Strings.
You may also consider using an ORM framework like Catatumbo (http://catatumbo.io) which takes care of the mapping of your model objects.
Disclosure: I'm the author of Catatumbo.
Upvotes: 1