Hibernate get all transaction of current year - java

Suppose I have a class TransactionDetails. This table holds transaction of last 10 year. Now How can i get all TransactionDetails of current year
I am using criteria as following
Criteria criteria = session.getCurrentSession().createCriteria(TransactionDetails.class);
criteria.add(Restrictions.eq("entryDate", thisYear));
return (List<TransactionDetails>) criteria.list();
I know I can achieve this by detecting beginning of year and end of year and the do a query with between operator. But I am looking for a way do this in one line. e.g. like in sql we use CURDATE()
How can this be done??

Try Restrictions.between("entryDate", loDate, highDate)
Edit:
You could also probably use a (vendor specific) sql restriction.
eg: Restrictions.sqlRestriction("to_char(entry_date, 'YYYY') = ?", "2015", StringType.INSTANCE)
Note: This will likely perform worse than between

You need to use between restriction together with date range:
Calendar lowCal = Calendar.getInstance();
lowCal.set(Calendar.DAY_OF_YEAR, lowCal.getActualMinimum(Calendar.DAY_OF_YEAR);
Date lowDate = lowCal.getTime();
Calendar highCal = Calendar.getInstance();
lowCal.set(Calendar.DAY_OF_YEAR, lowCal.getActualMaximum(Calendar.DAY_OF_YEAR);
Date highDate = highCal.getTime();
Criteria criteria = session.getCurrentSession().createCriteria(TransactionDetails.class);
criteria.add(Restrictions.between("entryDate", lowDate, highDate));
return (List<TransactionDetails>) criteria.list();
Dates are obtained by basic Java Calendar API. If is of course possible to obtain dates in different ways, for example using Joda Time.

Restrictions.between("entryDate",fromYear, thisYear)
can give you what you need. Reference to API here
or compute the year/date 10 years before now and use
Restrictions.ge("entryDate",fromYearMinus10);//uses years less than 10

Related

java.sql.SQLException: ORA-01843: not a valid month (Working in SQL DEVELOPER and doesn't work in JAVA)

I have a table in database that contains the 'Date_transaction' column his type is varchar.
In my Code JAVA, I create a SQL query via several conditions.
When I debug in Eclipse the query generated is like this:
SELECT *
FROM Transaction where 1=1
AND (to_date(Date_transaction,'YYYY/MM/DD HH:MI:SS') between '16/01/01' and '16/02/29')
AND projet = 'Project name'
AND nomtranche = 'tranche name' AND voletctrl = 'volet name'
AND (numeroimmeuble BETWEEN 1 AND 100)
AND validation = 1
AND statutDocNormal = 'statut'
AND numeroAppartement = 14
order by DateTrasaction DESC;
I execute this query in SQL DEVELOPER, the query is executed successfully without any error.
But in my code Java I get this Error : java.sql.SQLException: ORA-01843: not a valid month.
When I want to generate the query, I use this method to convert my date, this I spend in parameter (In the query it's : 16/01/01 and 16/02/29):
public static String parseDate2(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("yy/MM/dd");
String dt = sdf.format(date);
return dt;
}
I try this answer but it's not working.
You are relying on the session's NLS_DATE_FORMAT, which is set differently in the client and probably indirectly via your Java locale. Use explicit conversion with a specific format mask:
... between to_date('16/01/01', 'RR/MM/DD') and to_date('16/02/29', 'RR/MM/DD') ...
But it would be better to use four-digit years and YYYY (remember Y2K?), or date literals - those those don't work with variable values.
This also looks wrong:
to_date(Date_transaction,'YYYY/MM/DD HH:MI:SS')
If `date_transaction is already a date then you are implicitly converting it to a string and then back to a date, which is pointless and dangerous. And then possibly back to a string to compare with your fixed values. If it is a string then it shouldn't be. Either way you need HH24 rather than just HH so you can distinguish between AM and PM.
If it is a date you need:
...
date_transaction between to_date('2016/01/01', 'YYYY/MM/DD')
and to_date('2016/02/29', 'YYYY/MM/DD')
...

Query using setDate does not find results - cannot see final-query with parameters

I have an SQL which looks into a dimension table (which stores every dates until year 2020) and then shall retrieve the todays row.
I watched into the table, todays date is in there.
The problem is, that SQL does not return any result.
I am thinking of a problem related to the use of java.sql.PreparedStatement.setDate method.
In past i think this was working fine, now I did some kine of regression test and it failed. The differences to the past are having Oracle 12 DB now instead of 11 in past and running it on CentOS 6.5 instead of AIX.
On search I found this topic here:
Using setDate in PreparedStatement
As far as I can see, I am doing as suggested.
Heres the java code and the query:
public static String SELECT_DATUM = "SELECT TIME_ID, DATE, DAY_NAME, WEEK_NAME, MONTH_NAME, YEAR_NAME, SORTING, RELATIONDATE, VALID_TO, VALID_FROM FROM DIM_TIME WHERE DATE = :date";
java.util.Calendar now = Calendar.getInstance();
now.clear(Calendar.HOUR);
now.clear(Calendar.MINUTE);
now.clear(Calendar.SECOND);
now.clear(Calendar.MILLISECOND);
Date tmpDate = now.getTime();
Date tmpDate2 = new Date(((java.util.Date)tmpDate ).getTime());
statement.setDate(1, tmpDate2 );
I notice that getTime() is called twice. But I dont think its that bad.
I also noticed some displaying formats:
in Database the date-colums shows me the date like this: '08.11.2015'
in java while debugging tmpDate2 shows me a date like this: '2015-11-08'
in java while debugging tmpDate shows me a date like this 'Sun Nov 08 12:00:00 CET 2015'
But again, these are just display formattings while it is a dateobject in background and a date-type in database. I would expect that je JDBC driver would map this itself without formattings, that why we are using setDate method and not setString.
What am I doing wrong? What could I do for further debugging to get it?
I would like see the resulting SQL query which is finally executed with the parameter.
I tried this sql on db isntance:
SELECT * FROM v$sql s WHERE s.sql_text LIKE '%select time%' ;
but only getting this then: "... where date = trunc(:1 )"
On this row at least I can see that it was using the right schema I expected it to use and where I checked whether todays date is available.
Edit:
something I found out:
I saw another code using the same function but giving an GregorianCalendar instead Calendar. When using
new GregorienCalandar();
instead of
Calendar.getInstance();
Theres no difference.
But when I assign a date and dont let the system take the current time, then it works:
Using
new GregorianCalendar(2015, Calendar.NOVEMBER, 8);
Would retrieve the row I want from SQL.
Zsigmond Lőrinczy posted this answer as comment:
Try this: SELECT TIME_ID, DATE, DAY_NAME, WEEK_NAME, MONTH_NAME,
YEAR_NAME, SORTING, RELATIONDATE, VALID_TO, VALID_FROM FROM DIM_TIME
WHERE DATE = TRUNC (:date) – 3 hours ago
This works for my problem.
I am writing this as reponse to check it later as answer on this question if hes not going to write his own response (to get the reputation-points).
But I am wondering how I could get the same by preparing on java.
The code uses the clear-methods, which where released into an own method named 'trunc'. I think the programmer intendet to do this instead of TRUNC in SQL. I am wondering if it werent possible to do so in java and if yes, how?
Edit:
And I am wondering why a TRUNC is needed at all. Because the column in Database is of type Date an not Timestampt. So wouldnt there be an automatically trunc? I would expect this. Why do I need a trunc on SQL?

Hibernate java Mysql date are not sync

I have a java code using Hibernate and Mysql.
I cant understand what happens to Dates between Mysql and Java? for example can any body explain why is the output of this code is true????
Date d = something!
Query q= HSF.get().getCurrentSession().createQuery("from BaseNotification where creationDate <= :maxd and creationDate >= :mind order by creationDate");
q.setDate("maxd",new Date(d.getTime()+23*3600*1000+1155*1000));
q.setDate("mind",new Date(d.getTime()+23*3600*1000+1154*1000+999));
((BaseNotification)q.list().get(0)).getCreationDate().equals(d); // why its true!!!!!!!
believe me I'm not kidding!!!!
also if i get an object from hibernate with some date property and then want to get all objects with that date it doesn't even return the object itself!
my timezone is +3:30 is there any thing related to it?
but DB and Java code are in the same machine!.

Java play framework 2.0.4 ebean query

I am wondering how to query the database using the model in play 2.0 with a query like the one I listed below. I didn't see an option to pass in direct sql into the play framework 2.0.
I am trying to get a list of the expenses from a particular month.
SELECT * FROM Expensesdb.expense
WHERE month(expense.purchase_date) = 01
The option I see is to query for all the expenses and then parse each one for the month they are listed using the Date object.
I think there should be an efficient way, I can't seem to find a way to do this using ebean with Java play framework 2.0 to perform this query.
Update
Thanks Nico, I tried the exact code you have, with DateTime and I tried to use the code below, it doesn't return any Expenses. Am I doing something wrong?
Calendar calendar = Calendar.getInstance();
calendar.set(2012, 0, 01);
Date startDate = calendar.getTime();
calendar.set(2012, 0, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
Date endDate = calendar.getTime();
List<Expense> expenses = find.where().between("purchaseDate", startDate, endDate).findList();
return expenses;
I see two options:
1 - Using Ebean mapping
The idea is to search the expenses between the beginning and the end of the month, something like:
Datetime firstDayOfMonth= new Datetime().withDayOfMonth(1);
Datetime lastDayOfMonth = new Datetime().dayOfMonth().withMaximumValue();
return finder.where()
.between("purchaseDate", firstDayOfMonth, lastDayOfMonth).findList();
2 - Using RawSQL
For this, please take a look at the Ebean documentation.
The main drawback of raw sql is that this code will not be portable for different SQL servers (if you don't plan to use several db engine, it will not matter).
+1 for #nico_ekito
On the other hand, while you are suggesting getting all rows from DB and then parsing them in the loop, I'd rather suggest to parse them... while creating and store in format easier to search and index. Just create additional column(s) in your DB, and override save() and/or update(Object o) methods in your model, to make sure, that every change will set the field, ie use String purchasePeriod for storing string like 2012-11;
you can find then:
# in November of ANY year
SELECT * FROM table WHERE purchase_period LIKE '%-11';
# in whole 2012
SELECT * FROM table WHERE purchase_period LIKE '2012-%';
# in December 2012
SELECT * FROM table WHERE purchase_period LIKE '2012-12';
alternatively you can divide it into two Integer fields: purchaseYear, purchaseMonth.
For the first scenario the overriden save() method in the Expense model can look ie like this:
public void save() {
this.purchaseDate = new Date();
this.purchasePeriod = new SimpleDateFormat("yyyy-MM").format(this.purchaseDate);
super.save();
}

java mysql select statement not returning full date

I'm a java newbie but I'm not sure what I'm doing wrong. When I try to retrieve the last two dates from a database it only displays the year(while in mysql the same command provides the correct result).
Mysql command: SELECT DISTINCT date From fundanalysis ORDER BY date DESC LIMIT 2
Expected result:
2011-06-13
2011-06-08
Here's my java code:
preparedStatement = con.prepareStatement("SELECT DISTINCT date From fundanalysis ORDER BY date DESC LIMIT 2");
ResultSet numberofrowsresultset = preparedStatement.executeQuery();
numberofrowsresultset.next();
// most recent date
currentdate.add(numberofrowsresultset.getInt("date"));
System.out.print(numberofrowsresultset.getInt("date"));
numberofrowsresultset.next();
// last date before most recent
currentdate.add(numberofrowsresultset.getInt("date"));
return currentdate;
The final result is: [2011, 2011]
I basically want the exact same result as I get when I run the mysql query because I have to submit it as is to do another query later in the program.
pls help!
it is .getDate not .getInt
try:
numberofrowsresultset.getDate("date");
Try use .getDate() instead of .getInt():
currentdate.add(numberofrowsresultset.getDate("date"));
You are using .getInt which returns a numerical value. You need to use .getDate instead when you are getting a date value:
System.out.print(numberofrowsresultset.getDate("date"));
^^^^ change Int to Date
Date is not an integer so your '.getInt("date")' method is not returning the result you expect.
You need
java.sql.Date myDate = numberofrowsresultset.getDate("date");

Categories