Query By example and boolean field - spring-data

In class Users, I have a field id, firstname, lastname, username, password, enabled.
Enabled field is boolean
When i use do this query by example with spring
Users users = new Users();
users.setId(12);
Example<Users> example = Example.of(users);
Page<Users> pageUsers = userRepository.findAll(example, page);
In the generated query, i see in the where condition, it search on id field and enabled
why it's search on enabled?

You are using "boolean" primitive type, so your "Example" object has implicitly the "false" value.. you can use "Boolean" type to fix it

Related

Firestore "updateData" removes all the fields in document

In my prpject I have a "employees" collection where every employee document containes fileds like: firstName, lastName, zipCode, refreshToken etc.
When trying to update just a value of refreshToken i use 'updateData' like shown in documentation docs
my code:
static func updateToken(token:String){
Firestore.firestore().collection("companies").document(self.user.companyId).collection("employees")
.document(self.user.employeeId).updateData(["refreshToken" : token])
}
but that removees all other values of employee document (firstName, lastName, zipCode etc) and just new value of refreshToken exist in the node after operation. Am I doing something worng or I missunderstod idea of "updateData"?
If you want to update the value of a field and if the document does exist, its contents will be overwritten with the newly provided data, unless you specify that the data should be merged into the existing document, as follows:
Firestore.firestore().collection("companies").document(self.user.companyId)
.collection("employees").document(self.user.employeeId)
.setData(["refreshToken" : token], merge: true)
}
See, I have used setData() function instead of updateData().

spring-data-mongo, how to return _id back for saved objects from mongo?

I am newbie to the Spring Data mongo. I have documents which has same FirstName say John, but MiddleName and LastName are different.
Also from UI, some students populating data (feeding data via forms) which has also FirstName say John and again MiddleName and LastName would be different.
Now, when I am saving User Object (which has FirstName, MiddleName, LastName, Age, Sex etc..etc..) into mongo using MongoTemplate. I need to return back "_id" (which mongo create by default if we don't provide it explicitly) of those each saved User object.
Could you please provide any example / guidance? Please help.
If you are saving with mongo template your object Id will be set after insertion (as Oliver Gierke has writen) of the object so you can do it like this.
//User object annotated with #Document
User user = new User(String name);
user.setWhatever(something);
mongoTemplate.save(user);
//now the user object should be populated with generated id;
return user.getId();
but you can use normal CrudRepository and use it with
<mongo:repositories base-package="your.package" />
Spring Data MongoDB will automatically populate the identifier property of your domain object with the generated identifier value.
#Document
class User {
ObjectId id; // by convention, use #Id if you want to use a different name
String firstname, lastname;
…
}
If an object of this class is persisted with the id property set to null, the object will have the property set after it has been persisted via MongoTempalte.
All of this is also described in the reference documentation.

Grails MongoDB Update object with Association

I can't seem to understand where I am going wrong currently when I attempt to update my User domain model that has a hasOne association to a Profile object.
My domain models are as follows:
class User {
static hasOne = [profile: Profile]
static fetchMode = [profile: 'eager']
ObjectId id
String username
}
class Profile {
static belongsTo = [user: User]
ObjectId id
String familyName
String givenName
}
I am able to persist a User with a profile originally but when attempting to update the User object I get validation errors.
Validation error occurred during call to save():
- Field error in object 'co.suitable.User' on field 'profile.familyName': rejected value [null]
- Field error in object 'co.suitable.User' on field 'profile.givenName': rejected value [null]
I am able to print out the user.profile ID and also the user.profile.familyName before saving the object. Like the following:
println(user.profile.familyName)
println(user.profile.id.toString())
user.save(flush: true, failOnError: true)
But I still get the validation errors before saving, i'd imagine that the println(user.profile.familyName) call is fetching the profile object if it already hasn't been loaded which I thought setting the fetchMode would have handled.
The object is able to successfully persist and save when I do:
user.profile = Profile.findById(user.profile.id)
println(user.profile.id.toString())
user.save(flush: true, failOnError: true)
I could wrap that in a service but I was hoping for a solution that would be handled by Grails if possible. Any advice or thoughts is much appreciated.
You should not apply the logic for the SQL DB to Mongo 1 to 1. Mongo and other document-oriented DBs are not originally intended to store the joins between collections. There are some workarounds, like db-refs, but they are to be used with caution.
For your case - with hasOne - I would suggest using mongo's subdocuments (mirrored as GORM's embedded objects) instead of referencing:
class User {
ObjectId id
String username
Profile profile
static embedded = [ 'profile' ]
}
class Profile {
String familyName
String givenName
}
thus you use the mongo in accordance to it's original puprose. Also querying is simpler and faster.

jpa select string found in where in caluse

I have a list of strings and i need to search them in my table then construct new class contain key as on of my search strings and value as my pojo if exist or null if not exist.
something like that :
Class MyMapper {
private String identificationKey;
private User user;
// Getter and Setter
}
My Expected Query:
SELECT NEW MyMapper(identificationKey, u) From User u where u.identification IN :identificationKeys
i need to select every identificationKey in identificationKeys even not exist

Is there a way to update a database field based on a list?

Using JPA, I have a list of entries from my database :
User(id, firstname, lastname, email)
That I get by doing:
List<User> users = User.find("lastname = ?", "smith");
And I'd like to update all in one request, by doing something like this :
"UPDATE USER SET email = null IN :list"
and then set the parameter "list" to users
Is it possible? if so, how?
Thanks for your help :)
Well, you could embed the query that you used to obtain list in the where clause of the update.
UPDATE User a SET a.email = null
WHERE user IN (SELECT b FROM User b WHERE lastName = :?)
By doing this you'd be doing the query to search the list and the update in single update query.
How do you like that? Do you think this could work?
-EDIT-
Since you want to use the original list of items instead of a list just retrieved from the database, you can still ensure you build the original list like this
UPDATE User a SET a.email = null
WHERE user IN (SELECT b FROM User b WHERE lastName IN(:originalList))
Then when you invoke it, you can do something like this:
Collection<String> originalList = Arrays.asList("Kenobi", "Skywalker", "Windu");
query.setParameter("originalList", originalList);
By this, you can still ensure the query will only contain items in your original list and not any possible new item from the database, provided that that last name is a candidate key in the database, otherwise I would recommend that you use the ID for the subquery instend of the last name.
if you have jpa+hibernate you can use entityManager.createQuery() for creating hql query
like that:
String hql = "UPDATE Supplier SET name = :newName WHERE name IN :name";
entityManager.createQuery(hql);