JPQL QuerySyntaxException: unexpected token -- Jhipster - hql

I have a problem with the code generated by Jhipster.
In my repository, i have this query
#Query("SELECT member FROM Member member left join fetch member.categories where member.id =:id")
Optional<Member> findOneWithEagerRelationships(#Param("id") Long id);
when i run my application i have this error :
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException:
unexpected token: member near line 1, column 8 [SELECT member FROM
com.cf.usercfmanagement.domain.Member member left join fetch
member.categories where member.id =:id]

I couldn't find this on the JPQL documentation, but I'm suppose that member is a reserved word (like order, group, etc), because there is the MEMBER OF clause on JPQL.
So, use another alias for Member entity. Per example:
#Query("SELECT m FROM Member m left join fetch m.categories where m.id = :id")
Optional<Member> findOneWithEagerRelationships(#Param("id") Long id);

Related

QuerySyntaxException occurred for JPA #Query for Distinct and Count

I am using the below as a JpaRepository interface method query
#Query("SELECT DISTINCT order.status, COUNT(*) FROM OrderEntity order WHERE order.customerNumber = ?1 GROUP BY order.status")
During app startup I am getting the following exception -
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: order near line 1, column 17 [SELECT DISTINCT order.status AS status, COUNT(*) AS count FROM debomitra.cmw.orders.entity.OrderEntity order WHERE order.customerNumber = ?1 GROUP BY order.status]
at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:74)
at org.hibernate.hql.internal.ast.ErrorTracker.throwQueryException(ErrorTracker.java:93)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:297)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:189)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:144)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:113)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:73)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:155)
at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:600)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:709)
... 116 more
Is there any other way to write DISTINCT/COUNT query in JPA or am I doing something wrong?
Please provide me with some pointers.
I think the query will work if you modify it like below-
SELECT DISTINCT OrderEntity.status, COUNT(*) FROM OrderEntity WHERE OrderEntity.customerNumber = ?1 GROUP BY OrderEntity.status
The issue is with the order keyword in the JPQL. It is expecting a "by" keyword after the "order".
Whoever is reading this try avoiding "order" keyword in a statement expect at the end where you really need to issue a ORDER BY statement.

Springboot jpa, get rows with specific fields using two joins

I have entities :Student, Class, Room.
student M-M class, student M-M rooms, thus two junction tables. Now I want to get all students assigned to class X and room Y. Thus I've made:
#Query("SELECT s from Student s INNER JOIN s.classes c INNER JOIN s.rooms r WHERE c.id LIKE ?1 AND r.id LIKE ?2")
Page<Student> findAllInClassAndRoom(final Long classId, final Long roomId, final Pageable pageable);
But it gives me wrong results. Is there an error in my query ?
The only error in your query is the LIKE statement. Just change the equal sign "=". As below:
#Query("SELECT s from Student s INNER JOIN s.classes c INNER JOIN s.rooms r WHERE c.id = ?1 AND r.id = ?2")
Page<Student> findAllInClassAndRoom(final Long classId, final Long roomId, final Pageable pageable);
The LIKE statement allows a greater mass of data. Because it would allow any Room or Class that part of the code is the id entered as a parameter.
LIKE statement specification

HQL Select New doesn't return row when a foreign key is null

I have the following named query
#NamedQuery(name = "UserFlight.getUserFlightDetails",
query = "SELECT new com.foobar.UserFlightDetails(uf.flight.divertedAirport, uf.flight.number) " +
"FROM UserFlight uf WHERE uf.user.id=?1 AND uf.flight.id=?2")
The UserFlightDetails constructor is as follows
public UserFlightDetails(Airport airport, String flightNumber) {
this.setDivertedAirport(airport);
this.setFlightNumber(flightNumber);
}
divertedAirport is a foreign key in the flight table, path=(uf.flight.divertedAirport)
My problem is when divertedAirport is null (it's a nullable foreign key), my HQL query returns null as the result (The code doesn't even trigger the constructor above), so I don't get the flightNumber which is never null.
If the divertedAirport isn't null, I get both the airport and the flight number fine (and the above constructor gets executed just fine).
What could be causing this and how could I resolve it? I tried some null functions like nullif and coalesce but nothing helped.
I'm using spring boot 1.2.7, hibernate-core 4.3.11.Final
Probably, the problem is the uf.flight.divertedAirport. This expression do a JOIN between flight and divertedAirport but, as you say, divertedAirport is a fk and can be null.
So, you need to use the LEFT JOIN.
I would rewrite your query like this:
#NamedQuery(name = "UserFlight.getUserFlightDetails",
query =
"SELECT new com.foobar.UserFlightDetails(divertedAirport, flight.number)
FROM UserFlight uf
JOIN uf.flight flight
LEFT JOIN flight.divertedAirport divertedAirport
JOIN uf.user user
WHERE user.id = ?1 AND flight.id = ?2 ")
I remove the references like uf.user.id for a explicit JOIN (JOIN uf.user user plus user.id), because is more legible and this kind of problem that generated your question is more easy to find using this way to write JPQL queries.

how to count elements after making a left join with doctrine

i have 2 tables: "User" and "States". What i pretend to do, is to count how many users are from certain state, ie:
state total users
santa fe 5
buenos aires 20
and so on.
I'm using codeigniter with doctrine, here's my code:
public function countByState(){
$this->qb = $this->em->createQueryBuilder();
$this->qb->select('s.state_id', $this->qb->expr()->count('u.state'))
->from('models\States', 's')
->leftJoin('s.state_id' , 'u')
->leftJoin('models\User', 'u')
->groupBy('s.state_id');
$query = $this->qb->getQuery();
$obj = $query->getResult();
return $obj;
}
and this is the error:
Fatal error: Uncaught exception 'Doctrine\ORM\Query\QueryException' with message '[Semantical Error] line 0, col 76 near 'u LEFT JOIN models\User': Error: Class models\States has no association named state_id' in C:\Desarrollo\new_frame_doctrine\site\application\libraries\data\Doctrine\ORM\Query\QueryException.php on line 47
Please use this sql query
SELECT s.name,count(*) FROM `users` u left join `state` s on u.stateid=s.id
group by s.id;
In the code please change accordingly!!
I tried this by creating two tables named state (with fields id and name)
and users(with fields id, name and state_id), It worked fine for me.
Cheers!!!

linq joint type inference failed to call 'join' error

i have 3 tables User, TeamMember and Assessment all three have the user_id column, User is linked to TeamMember by userid and TeamMember and Assessment are linked with user_id(TeamMember) & rater,rated(Assessment)
Im trying to join in with this
from a in db.Assessments
join u in db.Team_Members on a.rated equals u.user_id
join u2 in db.Team_Members on a.rater equals u2.user_id
It's throwing this error
The type of one of the expressions in the join clause is incorrect.
Type inference failed in the call to 'Join'.
Any idea what going on?
You need to make sure a.rated / u.user_id and a.rater / u2.user_id are the same type

Resources