How to Give dynamic column name to #Query - java

Here is the method in my repository Interface.
#Query("select ?1 ,count(re) from Tabre group by ?1")
Page<RequestEntity> getGroupByColumnName(String columnName, Pageable pageable);
I would like to give column name dynamically to the query as mentioned above. But I see below error
error :
"I see Parameters are only supported in SELECT clauses when used as
part of a INSERT INTO DML statement".
I tried with single quotes, #{#columnName} with no luck.
Can someone help me on how to give the column name dynamically to the #query

Related

How to use CTE expression WITH clause in Spring Data JPA

I want to write a recursive query in SQL Server. So I am using CTE. Query is working properly in SSMS but when I am trying to use the same CTE in JPA as native SQL it gives an error:
Invalid name column Id.
The entity (which I am using in CTE to fetch data recursively) has #Id #Column(name="pk_id") private int Id field.
I also followed this SOQ : cte sql to simple subset query for JPA
But still getting error as invalid name column Id.
I have never used CTE before. How can this be fixed?
You can write the SQL query in JPA Repositories since the #Query annotation takes native query as well. For that, you need to specify the SQL query in the value parameter and nativeQuery is true as follow.
You can write CTE queries as well.
public interface ISomeRepository extends JpaRepository<Entity, Long> {
#Query(value = "SQL QUERY NEED TO BE WRITTEN HERE", nativeQuery = true)
List<Long> getEntityIds();
}

How to make insert custom query in spring data jpa by using #Query annotation

I am using mssql and spring data JPA, I want to insert new records to a table by using custom #Query annotation.
public interface CustomerRepository extends JpaRepository<Customers, String>{
#Modifying
#Query("insert into Customers values (?1 , ?2)")
public void saveCutomer(int custId, Customer cust);
}
Its giving error,
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: expecting OPEN, found 'values' near line 1, column 23 [insert into Customers values (?1 , ?2)]
I tried below also, same error.
#Modifying
#Query("insert into Customers select ?1 , ?2")
public void saveCutomer(int custId, Customer cust);
You don't do that using JPQL. You have batch DELETE and UPDATE but that's it.
Your options are:
1) Mark the query as native if you really make explicit insert (not recommended unless you intend to use some database-specific syntax not supported by JPQL.
2) Use standard save(Entity) method on your repository which is of course preferable.

Can #Query annotation in Spring Data JPA take in a list of enums?

I've been trying to figure out how to take an input of a list of enums for my sql query. This is what it looks like:
#Query(value = "Select * from employees where city in :cities", nativeQuery = true)
List<Employee> findByCities(#Param("cities") List<City> cities);
I understand that for simple queries we can rely on the JPA Criteria API but I want to know if I can actually do it this way instead. Because if so, i can create more complicated queries (such as joins with another table) if I could have this flexibility of specifying the list.
Yes spring-data-jpa's #Query can take a list of enums.
This is my repository method
#Query("Select u from User u where u.userType in :types")
List<User> findByType(#Param("types") List<UserType> types);
This is my repository call
userRepository.findByType(Arrays.asList(AppConstant.UserType.PRINCIPLE)))
And this is the query logs
SELECT user0_.id AS id1_12_,
user0_.date_created AS date_created2_12_,
...
...
FROM users user0_
WHERE user0_.user_type IN ( ? )
Hope this helps.
PS: I tested this in my local machine with positive results.
Update 1
The same doesn't work with nativeQuery=true. I tested it on my local system and it doesn't seem to be working with native queries. However with JPQL it works fine as mentioned in the above answer.
May be this answer will help.

How can I do an UPDATE statement with JOIN in JPQL (Spring JPA Queries)?

This is an extension of this question Update Statement with JOIN in SQL but I am trying to use Spring Data JPQL.
I am trying to use Update along with JOIN in JPQL as follows
#Modifying
#Query("UPDATE TotalValue tv JOIN LineItems li WHERE li.totalValue.totalValueId=:totalValuedId SET tv.totalAmount =sum(li.itemTotalValue) ")
void calculateTotalAmount(#Param("totalValuedId") Long totalValuedId);
However, i get an error as follows
org.hibernate.hql.internal.ast.QuerySyntaxException: expecting "set", found 'JOIN'
Is UPDATE and JOIN not possible in JPQL ? What is the alternative. Thanks
The JPQL syntax seems to indicate that a JOIN is actually not possible in an UPDATE statement.

Spring Data IN clause adds additional brackets

I have a 'Role' table with a 'name' column. I need to get all roles where names are either 'role1' or 'role2'. Role repository method looks like this:
Set<Role> findByNameIsIn(Set<String> roleNames);
My database contains only 'role1'. The request that is generated looks like this:
SELECT ID, NAME FROM ROLE WHERE (NAME IN ((?,?)))
bind => [role1, role2]
Please notice the double brackets around the parameters. Result set is empty. When I try this query manually through the h2 console - no results as well. The following query works:
SELECT ID, NAME FROM ROLE WHERE (NAME IN ('role1', 'role2'))
My set contains two elements exactly. Sets should be supported as a parameter type. See:https://dzone.com/refcardz/core-spring-data
And finally the question: What am I missing?
As Oliver Gierke mentioned - there is a bug opened for this issue in EclipseLink (this is what I'm using as a persistence provider) issue tracker. Since 2011!.. Here is the workaround:
#Query("select r from Role r where r.name in ?1")
Set<Role> findByNameIsIn(Set<String> roleNames);
And here is the valid generated query:
SELECT ID, NAME FROM ROLE WHERE (NAME IN (?,?))
bind => [role1, role2]

Categories

Resources