Can i do two jpa queries in one? - java

Im devloping a crud application in spring-boot and i was wondering if i can do these two queries and methods in one:
package com.celulaweb.crud.repository;
import com.celulaweb.crud.domain.Cidade;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
#Repository
public interface CidadeRepository extends JpaRepository<Cidade, Long> {
#Query("select c from Cidade c where c.estado is null or c.estado = :estado")
Page<Cidade> listarPorEstado(#Param("estado") String estado, Pageable pageable);
#Query("select c from Cidade c where c.nome is null or c.nome like :nome")
Page<Cidade> listarPorNomeTendo(#Param("nome") String nome, Pageable pageable);
}
These are queries from org.springframework.data.jpa.repository.Query
How can i merge these two?

If you have the same Pageable on this methods try this
#Query("""
select c from Cidade c
where (c.estado is null or (c.estado = :estado))
and (c.nome is null or (c.nome like :nome))
"""
)
Page<Cidade> listarEntries(
#Param("estado") estado: String,
#Param("nome") nome: String,
pageable: Pageable
)

Related

Why this Jpa Query is not working when i use count inside query it is not working?

**please help i have placed hidden inside package and import something else is there please mind the change **
package hidden;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import hidden;
public interface SubscriberIdDetailsRepository extends JpaRepository<SubscriberIdDetails, Integer> {
#Query("Select count(distinct s.msisdn) from subscriber_details s where s.subscriber_details_id in (select d.subscriber_details_id from subscriber_id_details d where d.UPPER(REGEXP_REPLACE(id_number,'[^[:alnum:]'' '']', ''))=:idNumber")
Integer countByidNumber( #Param("idNumber") String idNumber);
}
Your query is calling REGEXP_REPLACE, which is a database-specific string function. It won't run as pure JPQL, so you will have to pass nativeQuery=true to the end of #Query to mark it as a native query.
public interface SubscriberIdDetailsRepository extends JpaRepository<SubscriberIdDetails, Integer> {
#Query(value = "SELECT COUNT(DISTINCT s.msisdn) FROM subscriber_details s WHERE s.subscriber_details_id IN (SELECT d.subscriber_details_id FROM subscriber_id_details d WHERE d.UPPER(REGEXP_REPLACE(id_number,'[^[:alnum:]'' '']', '')) = :idNumber",
nativeQuery = true
)
Integer countByidNumber(#Param("idNumber") String idNumber);
}

How do I make PSQL think "keyword" is a variable when it is sent from Java Repository

package com.rev.booktags_sts.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.rev.booktags_sts.model.Booktags;
import java.util.List;
#Repository
public interface BooktagsRepository extends JpaRepository<Booktags, Long>{
//Custom query
#Query(value = "SELECT * FROM booktags s where s.tagname like '%keyword%';", nativeQuery = true)
List<Booktags> findByKeyword(#Param("keyword") String keyword);
}
As you can see the word "keyword" is between the %s the problem is when a SELECT * is done PSQL thinks that I am asking for the word "keyword" so how do I turn the word "keyword" in the java environment into a variable so PSQL thinks it is whatever I put into the keyword variable
The #Query decorator expects different syntax for parameterized queries. Following the example from the documentation for interpolating an SQL LIKE parameter from the method parameters, try:
#Query(value = "SELECT * FROM booktags s WHERE s.tagname LIKE %?1", nativeQuery = true)
List<Booktags> findByKeyword(String keyword);
Or, if you want to use named parameters, the parameter marker is instead ::
#Query(value = "SELECT * FROM booktags s WHERE s.tagname LIKE %:keyword", nativeQuery = true)
List<Booktags> findByKeyword(#Param("keyword") String keyword);

Why does a #Query annotated method require a body?

I'm new to Spring.
I wrote a class:
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller
public class Kontroller
{
#Query( value="select * from teszt"
, nativeQuery = true
)
List<Teszt> osszesSor(); // <-- error
//.....
#RequestMapping("/szam")
public #ResponseBody String szamossag()
{
List<Teszt> sokasag = osszesSor();
return("számosság="+sokasag.size());
}
}
And it says (it = the IDE (STS), and at runtime when I call osszesSor()):
This method requires a body instead of a semicolon.
The Teszt class is:
import java.io.Serializable;
import javax.persistence.*;
#Entity
#IdClass(Teszt.class)
public class Teszt implements Serializable {
#Id
private String kulcs;
#Id
private String ertek;
//getters, setters
}
It's a very simple table (that's why it becomes very complex in spring, because it has not a one-column key):
create table TESZT
(
KULCS VARCHAR2(2000) not null,
ERTEK VARCHAR2(2000) not null,
constraint TESZT_UN
unique (KULCS, ERTEK)
)
Now I know.
I had to create a repo interface:
public interface TesztRepo extends Repository<Teszt, Teszt>
{
#Query( value="select * from teszt"
, nativeQuery = true
)
List<Teszt> sokasag();
//...
}
and autowire it in the controller.
#Autowired
TesztRepo dao;
//...
List<Teszt> sokasag = dao.sokasag();
Not that complex.

QueryDsl ignoring predicate when using another #Query annotation

I have a repository looking like this (with other CRUD methods stripped)
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.StringPath;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
import org.springframework.data.querydsl.binding.QuerydslBinderCustomizer;
import org.springframework.data.querydsl.binding.QuerydslBindings;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.lang.NonNull;
import org.springframework.security.access.prepost.PreAuthorize;
import java.util.Optional;
import java.util.UUID;
#PreAuthorize("hasRole('" + Constants.ROLE_USER + "')")
public interface ProjectRepository extends CrudRepository<Project, UUID>, QuerydslPredicateExecutor<Project>, QuerydslBinderCustomizer<QProject> {
#Override
default void customize(#NonNull QuerydslBindings bindings, #NonNull QProject root) {
bindings.bind(String.class).first(
(StringPath path, String value) -> path.containsIgnoreCase(value));
bindings.including(root.name);
bindings.including(root.description);
}
#Override
#Query("select p from Project p left join p.roles r left join r.account a where ?#{principal.username} = a.username")
#NonNull
Page<Project> findAll(#NonNull Predicate predicate, #NonNull Pageable pageable);
}
As you can see I have a #Query annotation that limits the response of findAll based on who the user is. This causes the Predicate to be ignored entirely. So if I search for anything, it still returns all objects the user has access to. If I remove the #Query annotation then the searching works correctly. But of course I want my security to be applied. Is this a bug in QueryDsl? Or simply a limitation? How could I make this work?

Spring JPA Repository Return Object

I'm new in Spring. I want to create a repository that return Page of object array like this:
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
public interface A extends JpaRepository<Object, Long> {
#Query("SELECT a, b FROM EntityA a FULL OUTER JOIN EntityB b ON "
+ "a.id = b.id")
Page<Object[]> findAll(Pageable pageable);
}
But I get:
nested exception is java.lang.IllegalArgumentException: Not an managed type: class java.lang.Object
Thank you

Categories

Resources