I would like to compare date in Hibernate query. In my database data is in TIMESTAMP but my input in string so I would like to convert TIMESTAMP to string and compare my date.
List<User> usersList = session.createQuery("from User where CAST(DATE(created_date) as CHAR)=2015-01-19").list();
This is working in MySQL but not in Hibernate, please give me solution for this issue.
You can use SimpleDateFormat here
First create Date object from timestamp
Date createdDateTemp= new Date(timestamMillis);
Using SimpleDateFormat convert date in to formated string
String createdDateString = new SimpleDateFormat("yyyy-MM-dd").format(createdDateTemp));
now your HQL query will look like below
List<User> usersList=session.createQuery("from User where :createdDate = 2015-01-19").setParameter("createdDate", createdDateString).list();
Related
I have to build a criteria of a find query using a date field which is stored in String format.
The criteria I've written is like this:
Query findQuery = new Query()
findQuery.addCriteria(Criteria.where(mongoField).gt(startDate).lt(endDate));
where the "mongofield" is a String type, but "startDate" and "endDate" are a LocalDate type.
This criteria obviously doesn't work because the comparison is ineffective.
I've found that I should use $expr operator together with $dateFromString, but I didn't find any clear example of use in Java code.
Please, can anyone help me in writing a good statement in Spring Java code?
You can convert LocalDate to a string and then compare
LocalDate startDate = LocalDate.now();
LocalDate endDate = LocalDate.now().plusDays(20);
// Define time format converter
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
// Convert LocalDate type to String type
Criteria criteria = Criteria.where("mongoField").is("").gte(startDate.format(formatter)).lt(endDate.format(formatter));
Query query = new Query(criteria);
This question already has answers here:
Converting ISO 8601-compliant String to java.util.Date
(31 answers)
Closed 8 years ago.
For example, I have this String: 06/10/2013 18:29:09. I want to convert this string and put it in a SQL database (as Date).
How can I convert this to an sql date, so that it could be inserted into a database? I want the hours minutes and seconds to remain as well.
I tried the following:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date javaDate = sdf.parse("06/10/2013 18:29:09");
java.sql.Date date = new java.sql.Date(javaDate.getTime());
The problem is here:
java.sql.Date date = new java.sql.Date(javaDate.getTime());
java.sql.Date stores the date part of your timestamp. If you want/need to handle both date and time, use java.sql.Timestamp instead:
java.sql.Timestamp date = new java.sql.Timestamp (javaDate.getTime());
More info:
Date vs TimeStamp vs calendar?
You will use a SimpleDateFormat object to parse the string to java.util.date and then use the getTime() method to instantiate a java.sql.Date.
String input = "06/10/2013 18:29:09";
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
java.util.Date dt = sdf.parse(input);
java.sql.Date dtSql = new java.sql.Date(dt.getTime());
If you are working with String type for date input and then you want to save that in a database like MySQL, you should use an appropriate Date Format for it. There's a class called "SimpleDateFormat" which you can use for that purpose. You can find a sample in the following link, also a brief explanation on how it works. Hope it helps.
Example: http://www.java2s.com/Tutorial/Java/0040__Data-Type/SimpleDateFormat.htm
Best Regards.
Here's a simple demo. In a Database table like this.
You can insert into it like this.
//the SQL statement for creating the database table
create table user(id, integer primary key, username varchar(100), date_created varchar(100));
//the java code to insert into the table created above.
try{
String date = new SimpleDateFormat("dd/MM/YYYY HH:mm:ss").format(new Date());
String sql = "insert into user(username, date_created) values('olupotd', '"+date+"')";
int done = statement.executeUpdate(sql);
if(done > 0)
//inserted
else
//not inserted.
}catch(java.sql.SQLException e){}
Hope that helps
I have stored the date in my database (not months).i want to get the records from particular month.Is it possible to write criteria for this in hibernate3?
You can write like this
Date startDate = 2014-03-01
Date endDate = 2014-03-31
Criteria criteria = getSession().createCriteria(getDomainClass());
criteria.add(Restrictions.between("date", startDate, endDate));
(OR)
If your date format is "YYYY-MM-DD"
String date = "2014-03";
Criteria criteria = getSession().createCriteria(getDomainClass());
criteria.add(Restrictions.like("date", date));
I am looking for a way to get today's date and pass to sql table and save there. Call the saved date and do some task with JODA TIME API. The changed Joda time Date to sql table and save there and process continues..
I tried this way,
//prints todays date
java.sql.Date sqlDate = new java.sql.Date(new Date().getTime());
//passes wrong date to the table like 1970-07-01 instead of 2013-03-01
String insert = "INSERT INTO TEST_TABLE VALUES(1,"+sqlDate+")";
pStmt = conn.prepareStatement(insert);
pStmt.executeUpdate();
//converting to joda time
LocalDate ld = new LocalDate(sqlDate);
//some calculations, and how to convert back to sql date?
What I am trying to do here is, A table with 3 columns (id, startdate, finishdate). id will be entered by user, start date should be automatically entered todays date. after some calculations with joda time and finish date will be set to date it is finished.
Code
String insert = "INSERT INTO TEST_TABLE VALUES(2,'"+timestamp+"')";
Error
Data type mismatch in criteria expression
//I have created table using MS access
//the format of the date column is Date/Time.
You Can use Timestamp here. java.sql.Timestamp extends java.util.Date, so anything you can do with a java.util.Date you can also do with a java.sql.Timestamp.
To convert LocalDateTime to Timestamp
Timestamp timestamp = new Timestamp(localDateTime.toDateTime().getMillis());
But if You still want to convert Timestamp into java.sql.Date then use this
java.sql.Date date = new java.sql.Date(timeStamp.getTime());
I am using the criteria query as follows:I want to fetch the reservations after the time and date I have passed.but now i am getting the reservation before the time which i have passed for the same date.Please help..
#GET
#Path("/getReservationByUserIdAndTypeAndDateTime/{userid}/{type}/{date}/{time}")
public List<Reservation> getReservationByAndUserIdAndTypeAndDateTime(#PathParam("userid") int uid, #PathParam("type") int tid,#PathParam("date") Date date,#PathParam("time") Time time) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Reservation> criteria = builder.createQuery(Reservation.class);
Root<Reservation> r = criteria.from(Reservation.class);
TypedQuery<Reservation> query = em.createQuery(
criteria.select(r).where(new Predicate[]{
builder.equal(r.get(Reservation_.usersId), uid),
builder.equal(r.get(Reservation_.reservationsType), tid),
builder.greaterThanOrEqualTo(builder.concat(r.get(Reservation_.date), " "+r.get(Reservation_.time)), date.toString()+" "+time.toString())}));
return query.getResultList();
}
Comparing dates and times formatted as string is not advisable, results can depend on the format. It would be better having a unique Date field in the Reservation class:
#Temporal(TIMESTAMP) Date date;
and using date comparison in the query:
builder.greaterThanOrEqualTo(r.get(Reservation_.date), date)
This way the time parameter in the getReservationByAndUserIdAndTypeAndDateTime method can be omitted, since the date parameter would hold both date and time.