reference to query is ambiguous (jdbcTemplate) - spring

I cloned project from git and code is working on another machines.
just for me have errors, look at code and error:
And similar to this error is repeated in other places and other classes. I really have no idea.
I used different JDKs, different version of Gradle settings and tomcat settings correctly. The code runs on other computers, but not on my system.
#Override
public Long findLastPolicy(long policyId) {
Long firstPolicy = findFirstPolicy(policyId);
if (firstPolicy == null) {
return null;
}
final List<Long> lastPolicyId = new ArrayList<>();
jdbcTemplate.query("select id from ( " +
" select qsn3.fk_plc id from cmn.tbi_questionnaire_tree qsn3 where qsn3.fk_plc_anct = ? and qsn3.fk_plc is not null" +
" order by qsn3.endorsement_sequence desc " +
" ) where rowNum < 2", resultSet -> {
lastPolicyId.add(resultSet.getLong("id"));
}, firstPolicy);
return lastPolicyId.get(0);
}
error: reference to query is ambiguous
jdbcTemplate.query("select id from ( " +
^
both method query(String,ResultSetExtractor,Object...) in JdbcTemplate and method query(String,RowCallbackHandler,Object...) in JdbcTemplate match
where T is a type-variable:
T extends Object declared in method query(String,ResultSetExtractor,Object...)
And at the same point:
error: incompatible types: cannot infer type-variable(s) T
jdbcTemplate.query("select id from ( " +
^
(argument mismatch; bad return type in lambda expression
missing return value)
where T is a type-variable:
T extends Object declared in method query(String,ResultSetExtractor,Object...)

problem sloved. i deleted all jdk's and gradle and ide and all file and folders about ide and reinstalled all of them again :)

Related

InvalidPathException while sorting with org.springframework.data.domain.Pageable

I am trying to sort my table's content on the backend side, so I am sending org.springframework.data.domain.Pageable object to controller. It arrives correctly, but at the repository I am getting org.hibernate.hql.internal.ast.InvalidPathException. Somehow the field name I would use for sorting gets an org. package name infront of the filed name.
The Pageable object logged in the controller:
Page request [number: 0, size 10, sort: referenzNumber: DESC]
Exception in repository:
Invalid path: 'org.referenzNumber'","logger_name":"org.hibernate.hql.internal.ast.ErrorTracker","thread_name":"http-nio-8080-exec-2","level":"ERROR","level_value":40000,"stack_trace":"org.hibernate.hql.internal.ast.InvalidPathException: Invalid path: 'org.referenzNumber'\n\tat org.hibernate.hql.internal.ast.util.LiteralProcessor.lookupConstant(LiteralProcessor.java:111)
My controller endpoint:
#GetMapping(value = "/get-orders", params = { "page", "size" }, produces = { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<PagedModel<KryptoOrder>> getOrders(
#ApiParam(name = "searchrequest", required = true) #Validated final OrderSearchRequest orderSearchRequest,
#PageableDefault(size = 500) final Pageable pageable, final BindingResult bindingResult,
final PagedResourcesAssembler<OrderVo> pagedResourcesAssembler) {
if (bindingResult.hasErrors()) {
return ResponseEntity.badRequest().build();
}
PagedModel<Order> orderPage = PagedModel.empty();
try {
var orderVoPage = orderPort.processOrderSearch(resourceMapper.toOrderSearchRequestVo(orderSearchRequest), pageable);
orderPage = pagedResourcesAssembler.toModel(orderVoPage, orderAssembler);
} catch (MissingRequiredField m) {
log.warn(RESPONSE_MISSING_REQUIRED_FIELD, m);
return ResponseEntity.badRequest().build();
}
return ResponseEntity.ok(orderPage);
}
the repository:
#Repository
public interface OrderRepository extends JpaRepository<Order, UUID> {
static final String SEARCH_ORDER = "SELECT o" //
+ " FROM Order o " //
+ " WHERE (cast(:partnerernumber as org.hibernate.type.IntegerType) is null or o.tradeBasis.account.retailpartner.partnerbank.partnerernumber = :partnerernumber)"
+ " and (cast(:accountnumber as org.hibernate.type.BigDecimalType) is null or o.tradeBasis.account.accountnumber = :accountnumber)"
+ " and (cast(:orderReference as org.hibernate.type.LongType) is null or o.tradeBasis.referenceNumber = :orderReference)"
+ " and (cast(:orderReferenceExtern as org.hibernate.type.StringType) is null or o.tradeBasis.kundenreferenceExternesFrontend = :orderReferenceExtern)"
+ " and (cast(:dateFrom as org.hibernate.type.DateType) is null or o.tradeBasis.timestamp > :dateFrom) "
+ " and (cast(:dateTo as org.hibernate.type.DateType) is null or o.tradeBasis.timestamp < :dateTo) ";
#Query(SEARCH_ORDER)
Page<Order> searchOrder(#Param("partnerernumber") Integer partnerernumber,
#Param("accountnumber") BigDecimal accountnumber, #Param("orderReference") Long orderReference,
#Param("orderReferenceExtern") String orderReferenceExtern, #Param("dateFrom") LocalDateTime dateFrom,
#Param("dateTo") LocalDateTime dateTo, Pageable pageable);
}
Update:
I removed the parameters from the sql query, and put them back one by one to see where it goes sideways. It seems as soon as the dates are involved the wierd "org." appears too.
Update 2:
If I change cast(:dateTo as org.hibernate.type.DateType) to cast(:dateFrom as date) then it appends the filed name with date. instead of org..
Thanks in advance for the help
My guess is, Spring Data is confused by the query you are using and can't properly append the order by clause to it. I would recommend you to use a Specification instead for your various filters. That will not only improve the performance of your queries because the database can better optimize queries, but will also make use of the JPA Criteria API behind the scenes, which requires no work from Spring Data to apply an order by specification.
Since your entity Order is named as the order by clause of HQL/SQL, my guess is that Spring Data tries to do something stupid with the string to determine the alias of the root entity.

ERROR - new Global exception handled! Message = java.util.LinkedHashMap cannot be cast to java.math.BigInteger

DataType of patientId is BigInteger in entity Object
private BigInteger patientId;
Code:
#Override
public List<ChatRoomHistory> getLastChatDetails(List<String> patientIds) {
String queryStr = "FROM ChatRoomHistory where type = 'NO' and patientId in :patientIds ORDER BY chatCloseTime DESC";
TypedQuery<ChatRoomHistory> query = sessionFactory.getObject().getCurrentSession().createQuery(queryStr, ChatRoomHistory.class);
query.setParameter("patientIds", patientIds);
return query.getResultList();
}
Error
2020-08-16 19:52:27,939 [http-nio-8080-exec-5:] c.t.c.u.e.GlobalExceptionHandler.handleException:243
ERROR - new Global exception handled! Message = java.util.LinkedHashMap cannot be cast to java.math.BigInteger
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to java.math.BigInteger
at org.hibernate.type.descriptor.java.BigIntegerTypeDescriptor.unwrap(BigIntegerTypeDescriptor.java:19)
at org.hibernate.type.descriptor.sql.DecimalTypeDescriptor$1.doBind(DecimalTypeDescriptor.java:47)
at org.hibernate.type.descriptor.sql.BasicBinder.bind(BasicBinder.java:74)
at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:280)
Like said in the comment, you can't pass a list of String as a parameter intended for a numeric field.
You should declare your parameter as
public List<ChatRoomHistory> getLastChatDetails(List<BigInteger> patientIds)
You can correct your method in this way:
#Override
public List<ChatRoomHistory> getLastChatDetails(List<BigInteger> patientIds)
{
String hql = "select c from ChatRoomHistory c where c.type = 'NO' and c.patientId in :patientIds ORDER BY c.chatCloseTime DESC";
TypedQuery<ChatRoomHistory> query = sessionFactory.getCurrentSession().createQuery(hql, ChatRoomHistory.class);
query.setParameter("patientIds", patientIds);
return query.getResultList();
}
Comments:
Even though HQL does not require the presence of a select_clause, it is generally good practice to include one.
The list of values must not be empty; it must contain at least one value. (See this).

spring data jpa custom query fails to recognize class type

Not able to use custom POJO classes for my spring data jpa queries. Repeatedly fails with the following exception
"org.hibernate.MappingException: Unknown entity:
com.app.mycompany.AgileCenterServices.entities.ComponentDetailedInfo"*
Tried replacing the custom ComponentDetailedInfo.class and not mentioning anything during the call to entityManager.createNativeQuery(componentQuery.toString()), but then Object List returned fails to be converted to the specific POJO class after the query.
#Override
public ComponentListResponsePaginated findComponentByProjectId(String projectId, Pageable pageable) {
logger.info(" Inside findComponentByProjectId() API in IssueComponentServiceImpl");
String componentQuery = "select c.*, u.fullname "
+ "from issue_component c "
+ "left join user u on c.component_lead = u.username "
+ "where "
+ "upper(c.project_id) = upper(" + projectId + ")";
List<ComponentDetailedInfo> compList = new ArrayList<ComponentDetailedInfo>();
try {
logger.info(" ************* Printing query ******************************* ");
logger.info(componentQuery.toString());
compList = entityManager.createNativeQuery(componentQuery.toString(), ComponentDetailedInfo.class) .setFirstResult(pageable.getOffset())
.setMaxResults(pageable.getPageSize())
.getResultList();
}
}
Also tried the following
List<? extends Object> objList = null;
objList = entityManager.createNativeQuery(componentQuery.toString()) .setFirstResult(pageable.getOffset())
.setMaxResults(pageable.getPageSize())
.getResultList();
if(objList != null && objList.size() > 0) {
for(Object rec: objList) {
logger.info(" Printing Object ::: " + rec.toString());
compList.add((ComponentDetailedInfo)rec);
}
}
However the compList fails with the
java.lang.ClassCastException
The custom query returned should get typecast to the specific class type passed to the entityManager.createNativeQuery. However, I am facing the exception as mentioned above when I pass the class to createNativeQuery().
Even tried by totally removed the class in the createNativeQuery...
You have to define a constructor result mapping if you want to use a POJO as a result of a native query.
Here is an example query:
Query q = em.createNativeQuery(
"SELECT c.id, c.name, COUNT(o) as orderCount, AVG(o.price) AS avgOrder " +
"FROM Customer c " +
"JOIN Orders o ON o.cid = c.id " +
"GROUP BY c.id, c.name",
"CustomerDetailsResult");
And that's the mapping you have to add to your Entity:
#SqlResultSetMapping(name="CustomerDetailsResult",
classes={
#ConstructorResult(targetClass=com.acme.CustomerDetails.class,
columns={
#ColumnResult(name="id"),
#ColumnResult(name="name"),
#ColumnResult(name="orderCount"),
#ColumnResult(name="avgOrder", type=Double.class)})
})
If you don't like that approach you could use QLRM. Learn more about it here: https://github.com/simasch/qlrm

JPA - How to select from a database function?

I have the following SQL query in T-SQL:
SELECT a.ReportDate,
a.Value,
a.Quantity,
a.ID,
a.Code
FROM AQF.fCalc(#data) a
#data is a varbinary. I'm trying to replicate this query using JPA. (I'm actually using Spring Data JPA 1.10.2.) I have the following defined in MyRepository:
#Query("SELECT a "
+ "FROM function('AQF.fCalc', :data) a "
)
List<MyClass> getCalcData(#Param("data") byte[] data);
MyClass is as follows:
#Entity
#Data // using lombok to create setters, getters, etc.
public class MyClass {
#Id
private Long id;
private Date reportDate;
private BigDecimal value;
private BigDecimal quantity;
private String code;
}
When I call getCalcData, I receive the following error:
antlr.NoViableAltException: unexpected token: function
at org.hibernate.hql.internal.antlr.HqlBaseParser.fromRange(HqlBaseParser.java:1501) [hibernate-core-5.0.9.Final.jar:5.0.9.Final]...
How can I call the function AQF.fCalc (and pass in the byte array) using JPA?
Update 1
I've now tried using a native query too, but now I get an error stating:
java.sql.SQLException: An error occurred while getting new row from user defined Table Valued Function :
System.Xml.XmlException: Unexpected end of file has occurred. The following elements are not closed: Data, Report. Line 24, position 804.
Here's the test code for the native query in MyRepository:
#Query(value = "SELECT a.code "
+ "FROM AQF.fCalc(?1) a",
nativeQuery = true)
List<String> getCalcData(byte[] data);
Update 2
I was able to resolve the error noted in "Update 1" above. The byte array of data in the getCalcData was corrupted. Once I resolved that issue, the error no longer appeared. So, now I can run as a native query. However, I would still like to know how to use JPQL to make this function call.
You can use StoredProcedureQuery. From the javadoc
Interface used to control stored procedure query execution.
Refer this sample code.
Assume your SQL function name is sales_tax in this example.
EntityManager em = factory.createEntityManager();
// Create call stored procedure
em.getTransaction().begin();
StoredProcedureQuery storedProcedure = em.createStoredProcedureQuery("sales_tax");
// set parameters
storedProcedure.registerStoredProcedureParameter("subtotal", Double.class, ParameterMode.IN);
storedProcedure.registerStoredProcedureParameter("tax", Double.class, ParameterMode.OUT);
storedProcedure.setParameter("subtotal", 1f);
// execute SP
storedProcedure.execute();
// get result
Double tax = (Double)storedProcedure.getOutputParameterValue("tax");
System.out.println("Tax is: " + tax);
em.getTransaction().commit();
em.close();

SubSonic 3.0.0.3 | SimpleRepository - SortBy [SubSonicIgnore]

I got a class with [SubSonicIgnore]:
[SubSonicIgnore]
public string Name
{
get
{
return (FirstName ?? string.Empty) + ((MiddleName ?? string.Empty).Length > 0 ? " " + MiddleName + " " : " ") + (SurName ?? string.Empty);
}
}
whenver I run my test:
[Test]
public void Can_Sort()
{
IUserRepository _repo = new SqlUserRepository();
var users = _repo.GetUsers().OrderBy("Name");
It always yield an error:
TestQueryableSorter.Can_Sort : FailedSystem.NotSupportedException: The member 'Name' is not supported
I notice that it only breaks on those properties which has [SubSonicIgnore]. Is this a bug or by design?
I used the class from C:\Program Files\Microsoft Visual Studio 9.0\Samples\1033\CSharpSamples\LinqSamples\DynamicQuery.
You are trying to get SubSonic to order by a column that you are also explicitly telling it to ignore. This is by design, since SubSonic has no concept of the Name member (you are telling it to ignore this property using SubSonicIgnore) you cannot order by, select by or use that property in your SubSonic queries.
Looking at your code you could probably do the following instead:
[Test]
public void Can_Sort()
{
IUserRepository _repo = new SqlUserRepository();
var users = _repo.GetUsers().OrderBy("FirstNAme");

Resources