How to convert Month-Year to date in HQL/Grails? - oracle

This query is working in database
select to_date(a.year || a.month, 'YYYYMM') as dates from table a
but not working in Grails as HQL. Giving an error as "unexpected token".
How do I use this query in HQL/Grails?
As example I have month & year column. I need to show this as date in new column.
Above to_date(a.year || a.month, 'YYYYMM') as dates works fine in oracle database but it doesn't work in HQL in grails where I'm using as
executeQuery("select to_date(a.year || a.month, 'YYYYMM') as dates from table a") but this one is not working

HQL is only good if you have modeled your database table. If you really want to use this exact query, go for native SQL instead of HQL:
MyController {
Sql groovySql // package: groovy.sql
def myAction() {
def results = groovySql.rows("SELECT 'thisIsNativeSqlQuery'");
// do something with your results;
}
}
If you have modeled this table already (has Domain class) you can just fetch them all with YourDomain.list() and make a getter method that forms your date from the format you have:
Date toDate() {
​ return Date.parse("yyyyMM", "201808")​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
}
or have transient field that does this for you, it all depends on your use case

Related

Passing Date to NamedParameterJdbcTemplate in Select query to oracle

I have a query as below which is returning expected records when run from the SQL Developer
SELECT *
FROM MY_TABLE WHERE ( CRT_TS > TO_DATE('25-Aug-2016 15:08:18', 'DD-MON-YYYY HH24:MI:SS')
or UPD_TS > TO_DATE('25-Aug-2016 15:08:18', 'DD-MON-YYYY HH24:MI:SS'));
I think that we will not need to apply TO_DATE when we are passing java.util.Date object as date parameters but the below code snippet is silently returning me 0 records.
My SQL query in Java class is as below:
SELECT *
FROM MY_TABLE WHERE ( CRT_TS > :lastSuccessfulReplicationTimeStamp1
or UPD_TS > :lastSuccessfulReplicationTimeStamp2);
The code which executes the above query is as below but the below code snippet is silently returning me 0 records:
parameters.put("lastSuccessfulReplicationTimeStamp1", new java.sql.Date(outputFileMetaData.getLastSuccessfulReplicationTimeStamp().getTime()));
parameters.put("lastSuccessfulReplicationTimeStamp2", new java.sql.Date(outputFileMetaData.getLastSuccessfulReplicationTimeStamp().getTime()));
list = namedParameterJdbcTemplateOracle.query(sql, parameters, myTabRowMapper);
Please advise.
I guess you already found the answer but if anybody else needs it, here's what I've found:
java.sql.Date doesn't have time, just the date fields. Either use java.sql.Timestamp or java.util.Date. Both seems to be working for me with NamedParameterJdbcTemplate.
A little variation to above solution can be when your input(lastSuccessfulReplicationTimeStamp1/lastSuccessfulReplicationTimeStamp2) is a String instead of Date/TimeStamp (which is what i was looking for and found at this link -> may be it can help someone):
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("lastSuccessfulReplicationTimeStamp1", lastSuccessfulReplicationTimeStamp1, Types.TIMESTAMP);
parameters.addValue("lastSuccessfulReplicationTimeStamp2", lastSuccessfulReplicationTimeStamp2, Types.TIMESTAMP);
list = namedParameterJdbcTemplateOracle.query(sql, parameters, myTabRowMapper);

JPA Native query on Oracle database

I'm trying to do a native query on an Oracle database involve dates but I'm just not getting something.
I have a table with a number of rows in it and I know that the record with the oid=1234 has the latest updatetimeutc field, where updatetimeutc is a Date field. So I do the following:
Query query1 = entityManager.createNativeQuery("select updatetimeutc from TABLE where oid=1234");
List<Object[]> resultList = query1.getResultList();
Object[] os = resultList.get(0);
Date date = os[0];
Query query2 = entityManager.createNativeQuery("select oid, updatetimeutc from TABLE where updatetimeutc > :d");
query.setParameter("d", date);
resultList = query.getResultList();
At this point, I'm expecting the resultList.size() == 0, but that's not what's happening. I'm getting the same row returned to me as in query1.
Can someone explain why this is happening or what I'm doing wrong?
Thanks
The solution is to make sure you are using a version of Oracle's JDBC drivers that produce a java.sql.Timestamp for native queries that return DATE field.

hive query using regular expression

hi i was looking for a way to query a hive table ( user_acc_detl )
where a column (ACC_DETAILS) data looks like below,
COUNTRY[0]_united staes~DATE[0]_6/10/2014~AMOUNT[0]_200~ID[0]_20140509065052159324~COUNTRY[1]_united kingdom~DATE[1]_6/17/2014~AMOUNT[1]_125~ID[1]_20140516075156389761~COUNTRY[2]_Canada~DATE[2]_6/26/2014~AMOUNT[2]_200~ID[2]_20140515094013444121~COUNTRY[3]_Mexico~DATE[3]_7/3/2014~AMOUNT[3]_1200~ID[3]_20140601000937914898
i can query the hive table by
select ACC_DETAILS["COUNTRY[0]"] as COUNTRY, ACC_DETAILS["DATE[0]"] as DATE, ACC_DETAILS["AMOUNT[0]"] as BILLAMOUNT, ACC_DETAILS["ID[0]"] as PAYMENTID
from user_acc_detl
the above query gives the data for country[0], date[0], amount[0], id[0] which is fine.
Question - all i need to query it using just country, date, amount....without specifying as country[0]...
Question - is there a regular expression way to modify the query accordingly. please help me.
A simple way to achieve this is to wrap your query in a view:
CREATE VIEW user_acc_detl_simple AS
SELECT ACC_DETAILS["COUNTRY[0]"] as COUNTRY
, ACC_DETAILS["DATE[0]"] as DATE
, ACC_DETAILS["AMOUNT[0]"] as BILLAMOUNT
, ACC_DETAILS["ID[0]"] as PAYMENTID
FROM user_acc_detl;
SELECT country, date, billamount, paymentid FROM user_acc_detl_simple;

getting Hibernate error when using DBMS_RANDOM.value

I would like to achieve same result as the below query using Hibernate SQL, i.e., I would like to get two random records from the table whose ID is not equal to 300. I am using Hibernate 4.1 and Oracle 11g. I ran the below query on Toad and it gives 2 random records. But, when I try to run the HQL, there is error to do with the usage of "DBMS_RANDOM.value".
SELECT * FROM
( SELECT *
FROM table
where ID != '300'
AND q_ID=125
ORDER BY DBMS_RANDOM.value
)WHERE rownum < 3
;
I tried creating criteria and query, but both give Hibernate errors:
Hibernate Message: Invalid path: 'DBMS_RANDOM.RANDOM' [from com.model.table tab where tab.ID != '33092' ORDER BY DBMS_RANDOM.RANDOM]
and my actual hibernate query is:
Query query = session.createQuery("from table tab where tab.ID != '" +agrmId+"' ORDER BY DBMS_RANDOM.RANDOM").setMaxResults(2);
I also tried ORDER BY rand() and that gives an Oracle error.
Thank you for any help.
I solved the problem by adding a property tag in the hibernate mapping file:
<property name="constVal" formula="DBMS_RANDOM.RANDOM" type="long"/>
and then, in the POJO class, I added a variable with getter and setter methods:
private long constVal;
then, in the DAO class, I added the following query:
Criteria crit1 = session.createCriteria(table.class);
crit1.add(Restrictions.ne("id",300));
crit1.add(Restrictions.eq("quesId",125));
crit1.addOrder(Order.asc("constVal"));
crit1.setMaxResults(2);
and that solved it.

Error in creating query in openbravo through hql

This question might have answer ... But not for openbravo with postgresql database.
I have openbravo 3.0 framework. In my window i have two date fields namely fromdate and todate. The requirement is i have to write a hql where clause to filter the records on the basis of current date.The date field is of timestamp without timezone.
Means fromdate < currentdate
and todate > currentdate .
I went through this link and wrote the hql where clause as
e.id in(select s.id from Tablename as s where s.fromdate < current_Date and s.todate>current_date)
when i open this window i get this error as
Exception when creating query select e from Tablename as e
where ( e.id in(select s.Tablename_ID from Tablename as s where s.fromdate < (current_date) and s.todate < (current_date)
however if i remove the current date conditions as
e.id in(select s.id from Tablename as s).. It is working fine.
Is it because of current_Date function ? .I tried even with now function .. but i get the same error.
!!! Got The Error.
There is a problem in the query i wrote , in the where clause i am selecting the id's which is not correct,hence when i gave the below query it was running correctly.
(Tablename.fromdate < currrent_date and TableName.todate>current_date) There was no problem with the current_date function.
I thought may be it would help some one!!!
Tip: If you want to write hql query correctly in openbravo , pls install the Hql query tool module that is available freely for community edition of openbravo.
Happy Coding

Resources