JPA sorting by condition - spring-boot

I'm using spring boot 2.1.9
Ihave some repositories extended QuerydslPredicateExecutor and I need to sort enteties by specific value, plain sql works fine
select * from attachment_points order by kpp =1 desc;
I have about 50 entitis to add sorting, is there a way to add sorting to existing method
Page<T> findAll(Predicate predicate, Pageable pageable);
I've tried to add sort to pagable
JpaSort.unsafe(Sort.Direction.DESC, "kpp=1")
but I've dot error
threw exception [Request processing failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property kpp=77 found for type AttachmentPoint!] with root cause

Related

Error in spring mongodb for indexing a hashmap

I created in a pojo a index as it follows for the properties "attributes" that is a Map class
#CompoundIndex(name = "attributes", def = "{'attributes.key' : 1,attributes.value:1}")
i wish index the keys and the values of that map . I read in a another stackoverflow that is possibile to create a index in a nested properties but i have this error
" Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is org.bson.json.JsonParseException: Invalid JSON input. Position: 25. Character: '.'."

Spring Boot JPA native query for call PostgreSQL function

I am not familiar with the SQL function with spring boot. can anyone check my spring boot query whether it is correct?
I have created a PostgreSQL function and implemented it with spring boot.
but it is getting an error when I call the JPA query. below I have attached the SQL function and JPA query
PostgreSQL function - it is working fine
select pulse.fn_get_ticket_details_json(''::text,null::date,null::date,''::text)
Spring boot query
#Query(value = "select pulse.fn_get_ticket_details_json(''::text,null::date,null::date,''::text)", nativeQuery = true)
JsonObject SearchData();
Error message
ERROR: syntax error at or near ":"
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause
org.postgresql.util.PSQLException: ERROR: syntax error at or near ":"
Position: 44
screenshot
This should work
#Query(value = "select pulse.fn_get_ticket_details_json(''\\:\\:text,null\\:\\:date,null\\:\\:date,''\\:\\:text)", nativeQuery = true)
Remove extra spaces and check your simple quotes.

Getting Postgres Table Not Found Error with #ReadOnly Annotation in Spring Boot

I am getting the error PSQLException: ERROR: relation "schema.tableName" does not exist.
I have a GET API in spring which fetches data from a table. This API internally uses a custom method to access data using JpaReporitory. This custom method is annotated with #ReadOnly and #Transactional annotations since this API only fetches data from table. This gives me the table not found error.
But when I remove the #ReadOnly annotation, the API works just fine.
Below are the signatures of the said API and the custom method that it uses:
API:
#GetMapping("/houses/{houseId}/furnitures")
public List<Furnitures> getFurnitureslist(#PathVariable("houseId") long houseId) throws InterruptedException, ExecutionException {
return this.houseService.getFurnituresList(houseId);
}
Custom method:
#Transactional
#ReadOnly
public List<Asset> getTripPicklist(long tripId){
//Bunch of read operations using jpa repository.
}
This gives me an error trace as below:
org.springframework.orm.jpa.JpaSystemException: org.hibernate.exception.SQLGrammarException: could not extract ResultSet; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
Caused by: org.postgresql.util.PSQLException: ERROR: relation "schema.tableName" does not exist
But when I remove the #ReadOnly annotation from my custom method, the API works fine and I am able fetch the expected results from the database. What am I doing wrong?

Running a native insert query in spring boot

I am trying to run a simple insert query in spring boot but I am unable to do so.
Query:
#Modifying
#Query(value = "insert into Local(userId,name,address,pin) VALUES (:userId,:name,:address,:pin)", nativeQuery = true)
List < Local > insertattributes(#Param("userId")String userId,#Param("address") String address ,#Param("name")String name,#Param("pin") String pin);
Controller:
#RequestMapping("insertattributes/{userId}/{name}/{address}/{pin}")
#ResponseBody
public List < Local > insertAttributes(#PathVariable String userId, #PathVariable String name, #PathVariable String address, #PathVariable String pin) {
return localService.insertattributes(userId,name,address,pin);
}
Error:
o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: S1009
o.h.engine.jdbc.spi.SqlExceptionHelper : Can not issue data manipulation statements with executeQuery().
[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: could not extract ResultSet; nested exception is org.hibernate.exception.GenericJDBCException: could not extract ResultSet] with root cause
java.sql.SQLException: Can not issue data manipulation statements with executeQuery().
An insert statement doesn't return the inserted record. Since you're expecting a list to be returned executeQuery() is executed by Spring. What you want is the executiong of executeUpdate() which is only executed for void methods.
See also Cannot issue data manipulation statements with executeQuery()

Spring | SPEL multiple property accessors

I'm trying to use SPeL with multiple property accessors.
StandardEvaluationContext simpleContext = new StandardEvaluationContext(myPojo);
simpleContext.setVariable("ctx", ruleExecutionContext);
simpleContext.setPropertyAccessors(Arrays.asList(new MapAccessor(), new ReflectivePropertyAccessor()));
ExpressionParser parser = new SpelExpressionParser();
return (Boolean) parser.parseExpression(spelExpression).getValue(simpleContext, RulebaseConfiguration.LIB_MAP);
RulebaseConfiguration.LIB_MAP contains {"instanceName": instance}
I want to pass expressions that could operate on a POJO as well as call methods on the instance. But it only takes map into the effect.
I get this error:
SEVERE: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'payload' cannot be found on object of type 'java.util.HashMap' - maybe not public?] with root cause
org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'payload' cannot be found on object of type 'java.util.HashMap' - maybe not public?
at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:226)
Creating a context and parsing the expression for each request is wasteful, unless it's different for each request; in which case, consider caching expressions/contexts.
As I said, since you are passing a rootObject to getValue(), your myPojo is "hidden" - the evaluation is always performed on LIB_MAP.
You need to call getValue() without a root object to use the context's root object. You can add LIB_MAP as a variable (e.g. with name nationalityLookup) and use
payload['channel'] == #nationalityLookup.resolveChannel('CBR1000')

Resources