query at postgres HOW in Spring JPA - java

there is here such a request:
select *
from Organization t
where (t.inn,t.kpp) IN(('000000','00000'),('1111111','111111'));
How make this Query in Spring Data JPA.
I tried like this:
#Query(value =
"SELECT t" +
" FROM Organization t" +
" WHERE (t.inn, t.kpp) IN :innKppList")
List findOrganizationsByInnKpp(#Param("innKppList") Map innKppList);
But it does not work...

If you can split up your map into two lists this will work
#Query("SELECT t FROM Organization t WHERE t.inn IN ?1 AND t.kpp IN ?2")
Set<Organization> findByInnAndKpp(List<String> inn, List<String> kpp);

Related

Cannot compare texts on PostgreSQL (case insensitive not works on Spring Data JPA)

In my Spring Boot app, I use #Query as shown below on PostgreSQL and compare name value case-insensitive:
#Query(value = "SELECT DISTINCT e.id, e.name FROM Employee e " +
"WHERE e.name ILIKE :name) ",
nativeQuery = true)
List<Recipe> getEmployees(#Param("name") String name);
Although it seems to be ok for some time, it cannot return the same result randomly and it continues after rebuilding app and restarting. But it is working when executing the same query on DBeaver.
So, how should I compare equality of name field case insensitively in PostgreSQL?
Your query seems to be wrong. There is twice the parameter :name used. it should be
#Query(value = "SELECT DISTINCT e.id, e.name FROM Employee e " +
"WHERE name ILIKE :name) ",
nativeQuery = true)
List<Recipe> getEmployees(#Param("name") String name);
Another way to implement case insensitive search is to use an interface method:
List<Recipe> findByNameIgnoreCase(String name);

How to paginate a #Query query that is sorted? Java

#Query("select p.id,m.id,c.tipoDocumento,c.codigoFact from Corresponsable c"
" inner join Pais p"
" on p.id = c.pais.id"
" inner join Moneda m"
" on m.id = c.moneda.id"
" order by p.nombre,m.nombre,c.tipoDocumento,c.codigoFact")
List<Corresponsable> getFindPorCodPaisMonedaTipoDoc();
I did it this Query with JPA #Query in my Repository, but i would like to paginate my results with a number of page and numer of offset. What would be the best way to paginate keeping my values ​​ordered?
The Spring Data has native support to paginating, you can simply declare:
List<Corresponsable> getFindPorCodPaisMonedaTipoDoc(Pageable pageable).
You can manage the pagination with:
Pageable pageable = PageRequest.of(page, pageSize, Sort.by(sortBy));
For more info: https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/domain/Pageable.html

How to add schema name to Query annotation in Spring Data JPA

Currently I have such piece of code, which doesn't work, since I have to add schema name before each table in a query(like DEV.DASHBOARDS_METADATA):
public interface DashboardMetadataDao extends CrudRepository<DashboardMetadata, Integer> {
#Query("SELECT D FROM DASHBOARDS_METADATA D " +
"INNER JOIN FAC_DASHBOARDS_LINK DL ON D.ID = DL.DASHBOARD_ID " +
"INNER JOIN FIRMS F ON DL.FAC_ID = F.FAC_UNIT_ID " +
"INNER JOIN USERS U ON U.FIRM_ID = F.FIRM_ID WHERE LOWER(U.USERID) = LOWER(:userid)")
public Set<DashboardMetadata> findByUserId(#Param("userid") String userId);
}
The problem is that schema name differs from database to database (DEV/QA/PROD). Normally I use component's method which prepend schema's name to each table during query generation. How can do this using annotations?
Thanks!
Hibernate has a variable that can be used in native queries to get schema name called: {h-schema}
https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/chapters/query/native/Native.html#sql-global-catalog-schema You can just put {h-schema}table in your query. I think you have to convert it to a native query.
Below Code Snippet worked for me
#Query(
value = "select *\n" +
"from {h-schema}TABLE-A r left join {h-schema}TABLE-B p on r.ID=p.ID\n" +
"left join {h-schema}TABLE-C pe on p.ID=pe.ID\n" +
"left join {h-schema}TABLE-D e on pe.ENT_ID=e.ENT_ID\n" +
"where r.role_type='Provisioning'",
nativeQuery = true)

Hibernate many-to-many retrieve list with condition

Im working with hibernate and java. I have an Group class and a User class. They share a many-to-many relationship as shown in this ERD .
What Im trying to achieve is that I want to retrieve a list of groups with the condition that they contain a User with a certain User_id.
In the GroupDao I have defined a function retrieveForUser in which I tried to retrieve the list using hibernate query language:
public List<Group> retrieveForUser(int userid){
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
String hql = "select distinct g from Group g " +
"join g.allGroupMembers u " +
"where u.id = :id";
Query query = session.createQuery(hql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
query.setParameter("id", userid);
List<Group> list = query.list();
session.getTransaction().commit();
return list;
}
When I try to loop throught the resulting list using:
for(Group g : groupDao.retrieveForUser(user1.getId())){
System.out.println(g.getName());
}
I get the following errormessage:
java.lang.ClassCastException: java.util.HashMap cannot be cast to nl.hu.jelo.domain.group.Group
Question
How can I achieve it so that I end up with an List<Group> with only groups that contain a User with an certain User_id
You do not need to set result transformer. ALIAS_TO_ENTITY_MAP is for other purpose.
Simply do
String hql = "select distinct g from Group g " +
"join g.allGroupMembers u " +
"where u.id = :id";
Query query = session.createQuery(hql);
query.setParameter("id", userid);
is good enough.
Something off topic, are you sure you want to handle transaction manually like that?

HQL convert complicated hql to criteria

HQL
Query query = getSession()
.createQuery(
"select com from News as news " +
"join news.comments as com " +
"where news.id = :id " +
"order by com.addDate desc"
);
query.setParameter("id", id);
HQL above works fine. Want to change in the criteria api. I can not make. Please help
I suppose you can try something like this.
Criteria c = createCriteria(News.class);
c.add(Restrictions.idEq(id));
Criteria cComment = c.createCriteria("comments",c);
cComment.addOrder(Order.desc("addDate"));
ProjectionList projections = Projections.projectionList();
projections.add(Projections.property("c.id"),"id");
projections.add(Projections.property("c.addDate"),"addDate");
//Other Properties...
c.setProjection(projections)
c.setResultTransformer(Transformers.aliasToBean(Comment.class))
List<News> list = c.list();
Please mind that the Hibernate Criteria API is being deprecated in favor of the JPA Criteria API

Categories

Resources