Issue
Im trying to return an integer using mongo repository, the value i want to get is the id, below is the mongo query being used to extract the id field from the database as an integer
package com.example.messagestomongodb.repository;
import com.example.messagestomongodb.domain.CovidCases;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.stereotype.Repository;
@Repository
public interface CasesRepository extends MongoRepository<CovidCases, Integer> {
@Query(value = "{ '_id' : ?0 }", fields = "{ '_id' : 1}")
Integer returnIntegerFromDB(Integer id);
}
i am trying to check for duplicate records which contain the id when it already exists in the database, the reason for this is so i can DLQ the message as i am working with RabbitMQ
public boolean checkForDuplicateRecords(Integer id, CovidCases cases){
Integer existingId = casesRepository.returnIntegerFromDB(id);
if (cases.getId().equals(existingId)){
log.info("existingid is {} and casesid is {}",existingId,cases.getId());
return true;
}
return false;
}
I am getting the following error when i run the application:
Caused by: org.springframework.data.mapping.MappingException: Expected to read Document Document{{_id=1}} into type class java.lang.Integer but didn't find a PersistentEntity for the latter!
There seems to be an error getting the data from mongo but i am returning an integer and _id is set to an integer data type in mongo aswell
Solution
When you query with just value
and fields
in a JPA @Query
, it would still return instances of your entity.
Therefore, the return type of your method should be CovidCases
. You can later, count number of documents to get the required result.
@Query(value = "{ '_id' : ?0 }", fields = "{ '_id' : 1}")
CovidCases returnIntegerFromDB(Integer id);
To get count directly using @Query
, add the flag count
to it:
@Query(value = "{ '_id' : ?0 }", fields = "{ '_id' : 1}", count = true)
Long returnIntegerFromDB(Integer id);
Answered By - Prashant Vishwakarma
Answer Checked By - Terry (JavaFixing Volunteer)