I want to get the findAndModify return value of MongoTemplate as a modified value - spring-boot

I am currently using mongoTemplate in Spring boot like this:
public MyEntity update(MyDto dto) {
...
MyEntity result = mongoTemplate.findAndModify(
query, update, MyEntity.class);
return result;
}
query puts in the Criteria that finds the MyEntity to be modified, and update puts the contents to change. However, the returned value is the data before the update. How can I get the modified value right away?

When using findAndModify on the mongoTemplate, you have to explicitly configure it if the updated record shall be returned instead of the original one.
This may be done the following way:
FindAndModifyOptions findAndModifyOptions = FindAndModifyOptions.options().returnNew(true);
MyEntity result = mongoTemplate.findAndModify(query, update, findAndModifyOptions, MyEntity.class);
return result;
https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/

Related

Spring Mongo Aggregation that doesn't return duplicates values

I'm working on Spring while using Mongo as database. I have some collections and elements inside it. I'm trying to create a function that will return a random element from collection on every call but not return same element twice.
I have this in my repository class:
#Aggregation(pipeline = {"{'$match':{'typeOfAdventureHolidays':'summerCamps'}}", "
{$sample:{size:1}}"})
AggregationResults<AdventureHolidays> randomSummerCamps();
This return me a random value but also show me same value twice, while I want to avoid that.
I tried to search for some answers but I just founded a couple of ways to prevent it but to not show duplicate elements, no to not return same element twice.
So my code is like this.
Repository
#Aggregation(pipeline = {"{'$match':{'typeOfAdventureHolidays':'summerCamps'}}", "
{$sample:{size:1}}"})
AggregationResults<AdventureHolidays> randomSummerCamps();
ServiceImpl
#Override
public List<AdventureHolidays> getRandomSummerCamps() {
return Collections.singletonList(adventureHolidaysRepository.randomSummerCamps().
getMappedResults().stream().findFirst().orElse(null));
}
Controller
#GetMapping("/getRandomSummerCamps")
public String getRandomSummerCamps(Model model) {
model.addAttribute("randomSummerCamps",
adventureHolidaysService.getRandomSummerCamps());
return "randomSummerCamps";
}
If I need to provide something else I'm here, I tried to find something that will be useful but no success

Why can JPQLs modifying queries only return void or int?

When i want to modify the database via JPQL i have to mark the query as Transactional and Modiyfing. If i do so, the return type of the method representing the query has to be either void or int(representing the number of edited rows i think). Why are only the two return types allowed? If i do a HTTP-PUT request and update the object with an own JPQL query, i would like to return the updated object again. Whats the best way to do it if the return type of the query has to be void or int? Do i have to do a seperate query/request again which selects the object after it was updated?
EDIT:
Thats how i call the query:
if (inactivityListDTO.getProjectIds().size() > 0) {
projectRepository.updateProjectsIsArchivedByProjectIds(inactivityListDTO.getProjectIds(), inactivityListDTO.getIsArchived());
}
Thats the query:
#Transactional
#Modifying
#Query("UPDATE Project project SET project.isArchived = :isArchived,
project.archivedDate = current_date " +
"WHERE project.id IN :ids")
void updateProjectsIsArchivedByProjectIds(#Param("ids") List<Long> ids, #Param("isArchived") boolean isArchived);
Because it finally boils down to execute a standard UPDATE SQL in the DB , and the UPDATE in standard SQL only returns the number of records being updated and does not return a result set.
And yes , if you need get a record 's value after update , you have to query it again. Alternatively , you should consider using a JPA way to update a record , which first query the object , then update it by changing its state . Something like below (Assume you are using spring #Transactional to manage the transactional boundary):
#Transactional
public void changeEmployeeSalary(Integer employeeId , Integer salary){
Employee employee = entityManager.find(Employee.class , employeeId);
employee.setSalary(salary);
}
In this way , you do not need to query the record again after it is updated and you also do not need to manually write a UPDATE SQL.

Sorting a custom JPA query with pageable

So, I've already done this using the standard Spring Data JPA interface which extends PagingAndSortingRepository in order to achieve pagination and sorting for a REST API. The thing is, now I want to achieve the very same thing but now using just vanilla JPA and so far so good I managed to get my API to paginate but the sorting doesn't work at all. Every time I try to set the parameter (from a pageable object using pageable.getSort()) it ends with a query error (either if I just send a string as parameter like "name" or just send the sort object, it shows errors).
Here's some code:
My repo implementation:
#Override
public List<Project> findByAll(Pageable pageable) {
Query query = em.createQuery("SELECT project FROM Project project ORDER BY :sort");
query.setParameter("sort", pageable.getSort());
query.setMaxResults(pageable.getPageSize());
query.setFirstResult(pageable.getPageSize() * pageable.getPageNumber());
return query.getResultList();
}
My service:
#Override
public Page<Project> findAll(Pageable pageable) {
objects = Lists.newArrayList(repository.findByAll(pageable));
PageImpl<Project> pages= new PageImpl<Project>(objects, pageable, repository.count());
return pages;
}
To be clear, I'm filling the Pageable object via URI and from the console I can say it's actually getting the data, so I assume the problem is with the repo.
Edit: This is the error I get when I replace the setParameter("sort", ...) for a hardcoded string aka query.setParameter("sort", "name"):
java.lang.NumberFormatException: For input string: "name"
And I think this method should stand for strings as well. If I use query.setParameter("sort", pageable.getSort()), the error is the same.
The order by cannot be set as a query parameter. Also, the Pageable.getSort().toString() likely won't return a string suitable for use in an order by clause as it will result in a String that represents the Order as property: ORDER, note the colon.
Here are some modifications that will work, assuming Java 8...
String order = StringUtils.collectionToCommaDelimitedString(
StreamSupport.stream(sort.spliterator(), false)
.map(o -> o.getProperty() + " " + o.getDirection())
.collect(Collectors.toList()));
Query query = em.createQuery(
String.format("SELECT project FROM Project project ORDER BY %s", order));

Spring Mongodb findandModify fails to update entire document

I am new to mongodb and struggling to understand how document update works.
I have a document called 'menu':
{
"someId":"id123",
"someProperty":"property123",
"list" : [{
"innerProperty":"property423"
}]
}
which maps to my entity:
#Document(collection = "menu")
public class Menu {
#Id
private String id;
private String someid;
private String someProperty;
private List<SomeClass> list;
// accessors
}
when I try to find and update this document like this it does not update the document. It sure does find the menu as as it returns the original entity with Id:
#Override
public Menu update(Menu menu) {
Query query = new Query(
Criteria.where("someId").is(menu.getSomeId()));
Update update = Update.update("menu", menu);
return mongoOperations.findAndModify(query, update,
FindAndModifyOptions.options().returnNew(true), Menu.class);
}
But if I change it to this, it works:
#Override
public Menu update(Menu menu) {
Query query = new Query(
Criteria.where("someId").is(menu.getSomeId()));
Update update = new Update().set("someProperty", menu.getSomeProperty())
.set("list", menu.getList());
return mongoOperations.findAndModify(query, update,
FindAndModifyOptions.options().returnNew(true), Menu.class);
}
I don't really like this second method where each element of the document is individually set, as you might imagine I have a rather large document and is prone to errors.
Why does the first method not work? And what could be a better approach to update the document?
Check out the docs for findAndModify - it returns the version of the document before the fields were modified. If you do a new find() straight after, you will see that your changes were actually saved to MongoDB.

How do I update Object with Spring Data and MongoDB?

How do I update Object with Spring Data and MongoDB?
do I just do a template.save()?
public Person update( String id, String Name )
{
logger.debug("Retrieving an existing person");
// Find an entry where pid matches the id
Query query = new Query(where("pid").is(id));
// Execute the query and find one matching entry
Person person = mongoTemplate.findOne("mycollection", query, Person.class);
person.setName(name);
/**
* How do I update the database
*/
return person;
}
If you read the javadoc for MongoOperations/MongoTemplate you will see that
save()
performs an:
upsert()
So yes you can just update your object and call save.
You could probably do both 'find' and 'update' operations in one line.
mongoTemplate.updateFirst(query,Update.update("Name", name),Person.class)
You can find some excellent tutorials at
Spring Data MongoDB Helloworld
You can just use template.save() or repository.save(entity) methods for this. But mongo has also Update object for this operations.
For example:
Update update=new Update();
update.set("fieldName",value);
mongoTemplate.update**(query,update,entityClass);
Below code is the equivalent implementation using MongoTemplate for update operation.
public Person update(Person person){
Query query = new Query();
query.addCriteria(Criteria.where("id").is(person.getId()));
Update update = new Update();
update.set("name", person.getName());
update.set("description", person.getDescription());
return mongoTemplate.findAndModify(query, update, Person.class);
}

Resources