Sql column alias not working in Ebeans rawsql - postgresql

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).

Related

Springboot JPA Cast numeric substring to string

I have a JPA/Springboot application backed by a Postgres database. I need to get a records that is equal to a substring passed back to the server.
For example:
Select * from dp1_attachments where TRIM(RIGHT(dp1_submit_date_dp1_number::text, 5)) ='00007'
This query works in PgAdmin, but not in the JPA #Query statement.
#Query("SELECT a.attachmentsFolder as attachmentsFolder, a.attachmentNumber as attachmentNumber, a.attachmentName as attachmentName, a.dp1SubmitDateDp1Number as dp1SubmitDateDp1Number,a.attachmentType as attachmentType, a.attachmentDate as attachmentDate, a.attachmentBy as attachmentBy "
+ "FROM DP1Attachments a WHERE TRIM(SUBSTRING(a.dp1SubmitDateDp1Number::text, 5 )) = :dp1Number")
I've also tried CASTing the parameter like this:
#Query("SELECT a.attachmentsFolder as attachmentsFolder, a.attachmentNumber as attachmentNumber, a.attachmentName as attachmentName, a.dp1SubmitDateDp1Number as dp1SubmitDateDp1Number,a.attachmentType as attachmentType, a.attachmentDate as attachmentDate, a.attachmentBy as attachmentBy "
+ "FROM DP1Attachments a WHERE TRIM(SUBSTRING(CAST(a.dp1SubmitDateDp1Number as string, 5 ))) = :dp1Number")
but the application won't even run, and returns an error that the query isn't valid.
If I make no attempt to cast it, I get an error that function pg_catalog.substring(numeric, integer) does not exist
UPDATE
I've also tried creating a native query instead but that also doesn't seem to work.
List<DP1AttachmentsProjection> results = em.createNativeQuery("Select * FROM dp1_attachments WHERE TRIM(RIGHT(CAST(dp1_submit_date_dp1_number as varchar),5)) =" + dp1Number).getResultList();
In place of varchar I have also tried string and text.
Errors come back similar to ERROR: operator does not exist: text = integer. Its like the CAST is being ignored and I'm not sure why.
I also tried the following as a native query:
em.createNativeQuery("Select * FROM dp1_attachments WHERE TRIM(RIGHT(dp1_submit_date_dp1_number::varchar),5)) =" + dp1Number).getResultList();
and get ERROR: syntax error at or near ":"
FINAL SOLUTION
Thanks to #Nenad J I altered the query to get the final working solution:
#Query(value = "SELECT a.attachments_Folder as attachmentsFolder, a.attachment_Number as attachmentNumber, a.attachment_Name as attachmentName, a.dp1_Submit_Date_Dp1_Number as dp1SubmitDateDp1Number,a.attachment_Type as attachmentType, a.attachment_Date as attachmentDate, a.attachment_By as attachmentBy FROM DP1_Attachments a WHERE TRIM(RIGHT(CAST(a.dp1_Submit_Date_Dp1_Number as varchar ), 5 )) = :dp1Number", nativeQuery = true)"
Default substring returns a string, so substring(integer data,5) returns a string. Thus no need for the cast.
#Query("SELECT * FROM DP1Attachments a WHERE TRIM(SUBSTRING(a.dp1SubmitDateDp1Number, 5)) = :dp1Number")
But I recommend in this case use native query like this:
Put this code in your attachment repository.
#Query(value="SELECT * FROM DP1Attachments AS a WHERE TRIM(SUBSTRING(a.dp1SubmitDateDp1Number, 5 )) = :dp1Number", nativeQuery=true)
Be careful with the column's name.

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")

PostgreSQL {call Update Set ...} getting "syntax error at or near SET"

I'm changing queries from an Oracle Database to PostgreSQL, and in this query I am getting this error:
ERROR: syntax error at or near "SET"
the query is:
{call UPDATE alarm_instance SET last_update_time=default, wait_expire_time=null, core_number=nextval(SEQ_ALRM_NUMBR)
where wait_time <= current_date RETURNING alarm_instance_id bulk collect INTO ?}
I am using JDBC to connect to the database and here is the call code
try (CallableStatement cs = super.prepareCall_(query)) {
cs.registerOutParameter(1, Types.ARRAY);
cs.execute();
...
I have taken a long look at Postgres documentation and cannot find what is wrong and didn't find any answer to this specific situation
An UPDATE statement can't be executed with a CallableStatement. A CallableStatement is essentially only intended to call stored procedures. In case of Oracle that includes anonymous PL/SQL blocks.
And bulk collect is invalid in Postgres to begin with.
It seems you want something like this:
String sql =
"UPDATE alarm_instance " +
" SET last_update_time=default, " +
" wait_expire_time=null, "
" core_number=nextval('SEQ_ALRM_NUMBR') " +
" where wait_time <= current_date RETURNING alarm_instance_id";
Statement stmt = connection.createStatement();
stmt.execute(sql);
int rowsUpdated = stmt.getUpdateCount();
ResultSet rs = stmt.getResultSet();
while (rs.next() {
// do something with the returned IDs
}

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

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?