JPA query not fetching results - jpa

i am working on a certain project. I have a JPA query, which i want to give me a result set but the result has to exclude entries matching some data in another table thus am using NOT IN. My query is as below:
String sql = "SELECT DISTINCT(tia.voucherId) As Voucher, "
+ "e.farmId.name As Farm, CONCAT(e.farmId.farmerId.firstName, ' ', e.farmId.farmerId.lastName) AS Farmer,"
+ " tia.seasonId.name Season, e.farmingActivityId.name As FarmingActivity FROM Enrollment e,"
+ " TemporaryInputsAllocated tia where e.farmId = tia.farmId"
+ " AND tia.voucherId NOT IN (SELECT DISTINCT(ia.voucherId) from InputsAllocated ia )";
When i run my code i get the error:
ERROR controllers.ContractApplicationController - java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager:
Exception Description: Syntax error parsing the query [SELECT DISTINCT(tia.voucherId) As Voucher, e.farmId.name As Farm, CONCAT(e.farmId.farmerId.firstName, ' ', e.farmId.farmerId.lastName) AS Farmer, tia.seasonId.name Season, e.farmingActivityId.name As FarmingActivity FROM Enrollment e, TemporaryInputsAllocated tia where e.farmId = tia.farmId AND tia.voucherId NOT IN (SELECT DISTINCT(ia.voucherId) from InputsAllocated ia )], line 1, column 333: unexpected token [(].
Internal Exception: NoViableAltException(83#[1302:1: simpleSelectExpression returns [Object node] : (n= singleValuedPathExpression | n= aggregateExpression | n= variableAccessOrTypeConstant );])

Related

How to make a join with ON in jpa? ( Spring Data Jpa 1.4 )

I have this query, which I have tried in SQL and it goes perfectly
#Query("SELECT new es.abacor.elser.commons.empleado.EmpleadoList("+
"empleado.id,persona.nombre,persona.apellido1,persona.apellido2,persona.dni,persona.email)" +
" FROM rrhh.empleado as empleado" +
" INNER JOIN commons.persona AS persona ON empleado.persona_comun = persona.id" +
" WHERE" +
" empleado.persona_comun is not null" +
" and empleado.borrador = false" +
" and empleado.deleted is null" +
" and empleado.fecha_fin_contrato is null" +
" order by persona.nombre,persona.apellido1,persona.apellido2 asc")
public List<EmpleadoList> allEmpleadosList();
But I get the following error when executing within my project
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ON near line 1, column 217 [SELECT new es.abacor.elser.commons.empleado.EmpleadoList(empleado.id,persona.nombre,persona.apellido1,persona.apellido2,persona.dni,persona.email) FROM rrhh.empleado as empleado INNER JOIN commons.persona AS persona ON empleado.persona_comun = persona.id WHERE empleado.persona_comun is not null and empleado.borrador = false and empleado.deleted is null and empleado.fecha_fin_contrato is null order by persona.nombre,persona.apellido1,persona.apellido2 asc]
Someone knows what I'm doing wrong, I do not know what to do anymore.
JPA doesn't work on tables, it works on objects. If you want to use native queries you have to add nativeQuery=true to the Definition:
#Query(nativeQuery=true, <SQL-Statement>)
otherwise the ON clasue will be generated from the annotations in your entities

Dynamic query with hibernate

I'm trying to select object from dynamic tables but when I run my code I get some erros... There's a way for to do it... I'm using JPA, hibernate and postgres
#Query(nativeQuery = true,
value =
"SELECT u.* " +
"FROM " +
" ?1 AS u ")
Map<String, String> findAny(String tableName);
Here is the error...
org.springframework.dao.InvalidDataAccessResourceUsageException",
"debugMessage": "org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet\r\n\tat org.springframework.orm.jpa.vendor.HibernateJpaDialec
org.postgresql.util.PSQLException: ERROR: syntax error at or near "$1"
With Hibernate, you can't set table name as paramater, this is to ensure against security risks like SQL injection.
you have to mentions the table that you are getting the data from
value ="SELECT * FROM TableName u ?1")

Hibernate Query Language syntax error in query

My Hibernate query is:
SELECT targets from " + TargetSystem.class.getName()
+ " targets join fetch targets.targetSystemType type"
+ " where type.targetSystemTypeName = '"
+ Constants.Constant_TARGET_SYSTEM_TYPE + "'"
And the error I get when I try to execute the query is below
You have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version for the right syntax to use near
'TargetSystem targets join fetch targets.targetSystemType ty' at line 1
note: targetSystemTypeName is the Java name of the column in the entity and targetSystemType is a foreign key.
Query execution code:
Query executeQuery = entityManager.createNativeQuery(query,
TargetSystem.class);
#SuppressWarnings("unchecked")
List<TargetSystem> targetSystems = executeQuery.getResultList();
I can't figure out what is the error

Sql column alias not working in Ebeans rawsql

I am facing strange issue with raw SQLs, and I need some help to figure out the best way to fix it. I could, of course, add the columnMappings, but I want to make sure it's not because I am doing something wrong.
Play Framework APP
Ebeans ORM
Postgresql 9.,4
Executing the following RawSQL against a Postgresql database fails if I don't define columnMappings, although I have an alias defined:
String sql
= " Select date_trunc('day', end_time) as theDate, "
+ " count(*) as value "
+ " From ebay_item "
+ " group by date_trunc('day', end_time) ";
RawSql rawSql =
RawSqlBuilder
.parse(sql)
.create();
Error:
016-03-25 12:05:15,303 ERROR m.c.a.e.s.p.SimpleDBPromiseService - Error executing named query
javax.persistence.PersistenceException: Property [dateTrunc('day'] not found on models.com.abiesolano.ebay.sqlpojos.RangedDateCounter
If I switch to an H2 database:
String sql
= " SELECT trunc(end_time) as theDate, "
+ " count(*) as value "
+ " From ebay_item "
+ " Group by trunc(end_time)";
RawSql rawSql =
RawSqlBuilder
.parse(sql)
.create();
it works no problems.
Any suggestion would be really appreciated.
I don't think mysql likes to group or order by functions, you should use your alias "theDate" instead.
Note that if you're mapping to a bean object, the alias must be a #Transient property of your bean to be mapped by Ebean (otherwise, you'll get an unknown property error).

How to execute raw query in JPA?

I'm trying to execute a raw query like this:
em.createNativeQuery(
"WITH RECURSIVE recursetree(id, parent_id) AS (\n" +
"SELECT id, parent_g_id FROM group WHERE parent_g_id = 2\n" +
"UNION\n" +
" SELECT t.id, t.parent_g_id\n" +
" FROM group t\n" +
" JOIN recursetree rt ON rt.id = t.parent_g_id\n" +
" )\n" +
"SELECT * FROM recursetree;").getResultList();
On the Postgres side (via PGAdmin) it works fine, but from Java it get the following error:
java.lang.IllegalArgumentException: argument type mismatch
What do I do wrong? How to execute a really raw query on Postgres from a Java EE environment?