convert a sql query into jpql (JPA) - java

I have a JPA annotated model classes called LeadGeneration and Lead. I need to get a resultset from the above two classes with JPQL. I have done an SQL equivivalent of the result set I want. Please tell me how to convert this SQL to JPQL. Have to give generated_employee_id and status as parameters.
SELECT *
FROM lead_generation lg, lead l
WHERE lg.lg_code = l.lead_generation AND lg.generated_employee_id = '111' AND l.status ='CONVERTED_LEAD'
AND (first_appointment_date between DATE_FORMAT(NOW() ,'%Y-%m-01') AND NOW() );

in other ways,you can using nativeQuery,like this:
#Query(value="SELECT * FROM lead_generation lg, lead l WHERE lg.lg_code = l.lead_generation AND lg.generated_employee_id = ?1 AND l.status ='CONVERTED_LEAD' AND (first_appointment_date between DATE_FORMAT(NOW() ,'%Y-%m-01') AND NOW() )",nativeQuery=true)
List<User> findLeadGeneration(Integer id);

Make sure lead_generation has collections of lead. Each object "." variable must be setter and getter of object.
SELECT * FROM lead_generation lg INNER_JOIN lg.leads l WHERE lg.generated_employee_id = :id AND l.status= :status AND (lead_generation.first_appointment_date BETWEEN :min ANd :max)
Query query = em.createQuery("SELECT * FROM lead_generation lg INNER_JOIN lg.leads l WHERE lg.generated_employee_id = :id AND l.status= :status AND (lead_generation.first_appointment_date BETWEEN :min ANd :max)");
query.setParameter("id", "111");
query.setParameter("status", "CONVERTED_LEAD");
query.setParameter("min", DATE_FORMAT(NOW() ,'%Y-%m-01'));
query.setParameter("max", NOW());
List<lead_generation> lead_generations = (List<lead_generation>) query.getResultList();

Related

How to use `from` sub query in JPA QUERY DSL?

I have a query sql:
select distinct a.* from (select * from product_sku) a, (select #rowno:= 0) t;
Now, I want to perfrom my sql in query dsl:
jpaQuery.selectDistinct(qProductSku).from(query, jpaQuery.select(Expressions.numberTemplate(Integer.class, "#rowno:=0")));
I have already named a with query. Its type is JPAQuery<ProductSkuEntity>. The type of jpaQuery is JPAQueryFactory.
But it is incorrect, because from method only accpt type EntityPath.
How could I transfrom it to query dsl correctly?
(Don't ask me why this SQL is so strange, it just a part of complete expression)
SQLQuery sqlQuery = new SQLQuery(connection, PostgresTemplates.builder().quote().newLineToSingleSpace()
.printSchema().build());
ListSubQuery<Tuple> listSubQuery = new SQLSubQuery().from(QUsersPasswords.usersPasswords).orderBy(QUsersPasswords.usersPasswords.usuNummat.desc()).list(QUsersPasswords.usersPasswords.all());
QUsersPasswords qSubquery = new QUsersPasswords("subquery");
sqlQuery.from(listSubQuery.as("subquery")).limit(10);
sqlQuery.list(qSubquery.all());

CRudRepository native query could not return Result Set

I have a simple test query inside a CrudRepository interface that should return a List of entities.
public interface TestRepository extends CrudRepository<Test, TestId> {
#Query(value = "SELECT p FROM test p ", nativeQuery = true)
public List<Test> getTests();
}
When I test this I get the exception:
org.springframework.dao.InvalidDataAccessResourceUsageException: could
not extract ResultSet
If I don't use native query it works, but I want to use native query because I want to extend the select.
In order to make your query work :-
#Query(value = "SELECT * FROM TEST ", nativeQuery = true)
public List<Test> getTests();
The reason is simply because you are writing native query."SELECT p FROM test p" is not a native query
2 problems
in native SQL use native SQL :)
#Query(value = "SELECT p.* FROM test p ", nativeQuery = true)
your native Query returns an Object[] or a List of Object[].
You can change that, if you provide additional mapping information to the EntityManager.
By doing this you can tell the EntityManager to map the result into managed entities, scalar values of specific types or POJOs.
The simplest way to map the result of a native query into a managed entity is to select all properties of the entity and provide its as a parameter to the createNativeQuery method.
(sorry for using other examples)
Query q = em.createNativeQuery("SELECT a.id, a.version, a.firstname, a.lastname FROM Author a", Author.class);
List<Author> authors = q.getResultList();
All other mappings, like the following one which maps the query result into a POJO, need to be defined as SQLResultSetMappings.
#SqlResultSetMapping(
name = "AuthorValueMapping",
classes = #ConstructorResult(
targetClass = AuthorValue.class,
columns = {
#ColumnResult(name = "id", type = Long.class),
#ColumnResult(name = "firstname"),
#ColumnResult(name = "lastname"),
#ColumnResult(name = "numBooks", type = Long.class)}))
To use this mapping, you need to provide the name of the mapping as a parameter to the createNativeQuery method.
Query q = em.createNativeQuery("SELECT a.id, a.firstname, a.lastname, count(b.id) as numBooks FROM Author a JOIN BookAuthor ba on a.id = ba.authorid JOIN Book b ON b.id = ba.bookid GROUP BY a.id", "AuthorValueMapping");
List<AuthorValue> authors = q.getResultList();
#Query(value = "SELECT * FROM test p ", nativeQuery = true)

Criteria Builder select from select

Can anybody help me to create JPA Criteria Builder query in order to achieve this ?:
select id from (
select distinct r.id
r.date
r.name
from report r
inner join unit u
on u.report_id = r.id
order by
r.date desc,
r.name asc)
where rownum <= 10
I just can create inner query:
CriteriaQuery<Object[]> innerQuery = cb.createQuery(Object[].class);
Root<ReportEntity> root = innerQuery.from(ReportEntity.class);
List<Ojbect[]> resultLsit = em.createQuery(
innerQuery.multiselect(root.get(ReportEntity_.id),
root.get(ReportEntity_.date),
root.get(ReportEntity_.name)
.distinct(true)
.orderBy(cb.desc(root.get(ReportEntity_.date)),
cb.asc(root.get(ReportEntity.name))
).setMaxResults(10).getResultList();
Thx in advance :)
I've decided to get List of Object[] and then retrieve id from array
List idList = resultList.stream().map(array -> (Long)array[0]).collect(Collectors.toList());
This is code smell, but unfortunatelly I haven't found better solution.
Note I use this approach to cope Hibernate issue :
"Warning “firstResult/maxResults specified with collection fetch; applying in memory!”? - this warning pops up due to using fetch and setMaxResults in hql or criteria query.
That's why first of all I get all id, and then I find all entities according this id. (select * from ReportEntity r where r.id in :idList) - smth like this.

Hibernate HQL issue expecting IDENT found "*"

I need get all data from relative table so I'm using something like this (i would use it in sql)
private static final String SELECT_OOPR_TO_SEND = "SELECT R.* " +
"FROM offerOrderProjectRel R, offerOrder O, project P " +
"WHERE P.id = R.project_id and O.id = R.offer_order_id " +
"and O.type = 'ORDER' and (P.status = 'PENDING' or P.status ='PROTECTED')" ;
;
#SuppressWarnings("unchecked")
public List<OfferOrderProjectRel> findAllOfferOrderToSendToSalesmans() {
Query q = getSession().createQuery(SELECT_OOPR_TO_SEND);
List<OfferOrderProjectRel> list = q.list();
return list;
}
After lauching this code i'm getting that error :
org.hibernate.hql.internal.ast.QuerySyntaxException: expecting IDENT,
found '**' near line 1, column 10 [SELECT R.* FROM offerOrderProjectRel
R, offerOrder O, project P WHERE P.id = R.project_id and O.id =
R.offer_order_id and O.type = 'ORDER' and (P.status = 'PENDING' or
P.status ='PROTECTED')]
So how can I obtain all data from column R with hibernate?
The method createQuery expects an HQL query string.
HQL is an object-oriented querying language.
HQL interprets SELECT R.* as select the member field * of the object R.
But * is not a member field of R. Is it?..
To select all the member fields of R use:
SELECT R
FROM offerOrderProjectRel R, offerOrder O, project P
WHERE P.id = R.project_id and O.id = R.offer_order_id
and O.type = 'ORDER' and (P.status = 'PENDING' or P.status ='PROTECTED')
you use SQL query, not hql query, so it should be
Query q = getSession().createSQLQuery(SELECT_OOPR_TO_SEND);
For people that received the "expecting IDENT found “*”" error when using org.springframework.data.jpa.repository.Query and found this question I'll add that you can change the nativeQuery flag to true:
#Query(value = "SELECT * FROM table1", nativeQuery = true)
List<Object> myFindAll();

Can I convert this Mysql query to JPA?

I'm fairly familiar with SQL but very new to the Java Persistence API. I'm using JPA through the Play Framework.
I have the following MySql query that I'd like to convert to pure JPA code if I can:
SELECT a.id, b.id
FROM Rankable a
INNER JOIN Rankable b on a.id < b.id
WHERE
a.category_id = ? AND b.category_id = ?
AND NOT EXISTS (
SELECT *
FROM Comparison c
WHERE c.lower in (a.id, b.id))
AND NOT EXISTS (
SELECT *
FROM Comparison c
WHERE c.higher IN (a.id, b.id))
ORDER BY a.id * rand()
LIMIT 1;
The purpose of this query is to select two rows from the Rankable table, but ensure that this specific pair is not present in the Comparison table.
What would be the best way to call a somewhat complicated query like this from Play/JPA?
It is possible to do a self join in JPA.
Take a look at this example
from the example
#NamedQuery(name="siblings", query="select distinct sibling1 "
+ "from Deity sibling1, Deity sibling2 where "
+ "sibling1.father = sibling2.father "
+ "and sibling1.mother = sibling2.mother "
+ "and sibling2 = ?1 and sibling1 <> ?1"),

Categories