Fetching data from mysql database table based on condition of date - java

Can anyone suggest me the solution of fetching data on condition of current date which i am passing in dao layer method of type system current date.
for e.g I have to fetch data from table "X" which have a column "startdate" of Date type(Mysql) on the basis if that date is greater with the current date passed to the query in java.
I have tried with java.util.Date but not working and also my requirement is not to used database specific function like curr() or Now().
I found a relative post but none helped.Is there no alternative apart from using JodaTime.
Thanks.

In your Entity class mark 'startdate' field with
#Column(name = "startdate")
#Temporal(TemporalType.DATE)
private Date startdate;
And create query like this one:
#NamedQuery(name = "Entity.findAfterDate", query = "SELECT e FROM Entity e WHERE e.startdate >= :dateAfter")
In your EntityDAOImpl
public List<Entity> getEntitiesAfterDate(Date date) {
Query query = openSession().getNamedQuery("Entity.findAfterDate");
query.setParameter("dateAfter", date);
return query.list();
}

Related

issue with createNativeQuery when binding date type parameter

i use an EntityManager to create a nativeQuery.
My database is a Postgres database.
The date field i request is modelised like that..
#Column(name = "date", columnDefinition = "date", nullable = false)
private LocalDate date;
when i write this, all is fine..
String sqlRequest = "select insurer from stock where date='2021-01-01'";
Query query = entityManager.createNativeQuery(sqlRequest);
List<Object[]> records = query.getResultList();
but i when i wanna use the setParameter function..
String sqlRequest = "select insurer from stock where date=:param";
Query query = entityManager.createNativeQuery(sqlRequest);
query.setParameter("param", "2022-03-11");
List<Object[]> records = query.getResultList();
i got this issue..
No operator matches the given name and argument types. You might need to add explicit type casts.
any idea ?
I think it's because you tried to set the param as String type instead of Date.
You should try to set LocalDate as time instead of "2022-03-11".

Hibernate and Mysql object does not refresh timestamp column

I am currently developing a web-application with spring, hibernate and mysql.
The problem was to add a created_at and updated_at timestamp to all the objects.
I have the following abstract #MappedSuperClass:
#MappedSuperclass
public abstract class AbstractTimestampEntity {
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "created_at", nullable = false)
private Date created;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "updated_at", nullable = false, updatable = false)
private Date updated;
...
}
And in Mysql defined CURRENT_TIMESTAMP for created_at and CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP for updated_at.
When I manually test it, it works fine after inserting an object and updating it the times in mysql are correct. However I wanted to write automatic tests and it does not retrieve the values from the DB and refresh the object.
// before update
sessionFactory.getCurrentSession().refresh(tester1);
Date before = tester1.getUpdated();
// update
userResource.updateUser(new UserDTO(tester1), tester1.getUserId());
// after update
sessionFactory.getCurrentSession().refresh(tester1);
Date after = ((User) sessionFactory.getCurrentSession().get(User.class, tester1.getUserId())).getUpdated();
// verify
assertTrue(before.before(after));
It will result in a nullpointer exception because the date of the tester1 object is never set. (Tester1 Object extends AbstractTimestampEntity)
I manually retrieved the date with a sql-query:
SQLQuery sqlQuery = sessionFactory.getCurrentSession().createSQLQuery("SELECT updated_at FROM smarterTestDB.User WHERE userId="+tester1.getUserId());
sqlQuery.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
List list = sqlQuery.list();
String test = list.get(0).toString();
And it gave me the set value from mysql:
Date: {updated_at=2017-01-06 12:25:59.0}
Why does it not write it in the object? And it does not give any error about TypeMissmatch or similar. Is the #Temporal(TemporalType.TIMESTAMP) not converting from sql.Timestamp to util.Date?
Kind regards
Update:
I got the error by passing the object to the userResource I construct a the UserDAO object the user would actually send. This one gets updated but not the original User-Object as long as it is not newly retrieved from the database. Simple pass by reference/value error.
Modifications made by the database (like CURRENT_TIMESTAMP or any kind of trigger) aren't recognized by the entity you are trying to save. All modifications have to be made by the java application. Doing so the correct values are in the database and in your entity without doing a "refresh". I've used the following code.
#Column(nullable = false)
#Temporal(TemporalType.TIMESTAMP)
#Version
private Date updated_at;
The database column is a simple "TIMESTAMP" without any further functionality.
So the database hasn't any logic, all is done by the application in one place. The application is responsible for all modifications. Maintaining your code will be easier this way.

Hibernate: using LocalDateTime to query a range

I'm using hibernate 5 with the hibernate-java8 addon to use LocalDateTime fields. I now have an entity which has a date field and a user field like in:
#Entity
public class Transaction {
// ...
private User user;
private LocalDateTime date;
// ..
}
Now I simply want to query all transactions of a user within a certain time range. So I use the following query:
SELECT t FROM Transaction t WHERE t.user = :owner AND t.date BETWEEN :from AND :to
Strange enough this query does not give me any results. I also tried using the < and > operators but that did not help either. When I leave out the time range part I get the correct list of transactions for the user. When I execute the SQL query generated by Hibernate in the MySQL workbench I also get the expected results. I use the following snippet to execute the (named) query:
public <T> List<T> findList(Class<T> type, String queryName,
Map<String, Object> params) {
final EntityManager em = this.entityManager.get();
final TypedQuery<T> query = em.createNamedQuery(queryName, type);
params.forEach(query::setParameter);
return query.getResultList();
}
This is simply called providing the query listed above and a map of named parameters like:
findList(Transaction.class, Transaction.BY_USER_AND_RANGE,
ImmutableMap.of("owner", owner, "from", from, "to", to));
In my test case a persisted a single Transaction with the current date and created a range from yesterday to tomorrow for the query. Inspecting the table in the MySQL workbench shows that the transaction is there and that the date field has the correct type and contains the correct value. Yet my query won't give me any results.
Is there anything I'm missing?
The date you are passing as param should also be
LocalDateTime
see the example code below might help you
LocalDate date = LocalDate.of(2015, 8, 11);
TypedQuery<MyEntity> query = this.em.createQuery("SELECT e FROM MyEntity e WHERE date BETWEEN :start AND :end", MyEntity.class);
query.setParameter("start", date.minusDays(2));
query.setParameter("end", date.plusDays(7));
MyEntity e = query.getSingleResult();

Hibernate - compare DateTime field with Restrictions.like

I have a createDateTime field with Date dataType in my entity class and hibernate generated a column with datetime type in the mysql table. Now, I need to compare createDateTime field with values without seconds. In fact, one user can enter for example 2015-01-01 12:10 in the search field and I want to show the record that has 2015-01-01 12:10:10 crateDateTime as a result. I know this is possible with flat query:
SELECT * FROM table_test WHERE crateDateTime LIKE "2015-01-01 12:10 %"
But I don't know how I can do this via hibernate.
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
data = formatter.parse("2015-01-01 12:10");
//This returned null.
Criterion crtmp = Restrictions.like("createDateTime", data);
//This returned ClassCastException. Because second argument must have "Date" dataType not "String"
Criterion crtmp = Restrictions.like("createDateTime", data + "%");
You should create a Date variable e.g. createDateTimePlusOneMinute, than find a time range between your createDateTime and createDateTimePlusOneMinute, using the following restrictions
criteria.add(Restrictions.ge("createDateTime", createDateTime));
criteria.add(Restrictions.lt("createDateTime", createDateTimePlusOneMinute));
// datetime comparison
Select c from Customer c where c.date<{d '2000-01-01'}

JPA timestamp comparison not working

I have a persistent object with two Date fields, like this
#Temporal(TemporalType.TIMESTAMP)
private Date generated;
#Temporal(TemporalType.TIMESTAMP)
private Date expirationTime;
On object construction the expirationTime is initialized based on the generated field
this.expirationTime = new Date(generated.getTime() + ttlMillis);
Now I'm trying to delete all expired objects from the database with a JPA query
Query q = em.createQuery("delete from MyObject t where CURRENT_TIMESTAMP > t.expirationTime");
q.executeUpdate();
But running a simple test
MyObject o = new MyObject(somePastDate, someTTL);
em.persist(o);
... create the query above
q.executeUpate();
shows no row is being deleted. Any clue on what I'm doing wrong? I'm running tests on HSQLDb and using Hibernate as my JPA provider.
Edit: solved, but I'm not sure why this version should work differently.
Query q = em.createQuery("delete from MyObject t where :now > t.expirationTime");
q.setParameter("now", new Date());
q.executeUpdate();
What's the use of CURRENT_TIMESTAMP if comparisons with other fields fail?
You did not set any parameter, and the query has to get a named parameter:
Query q = em.createQuery("delete from MyObject t where CURRENT_TIMESTAMP > :expirationTime");
q.setParameter("expirationTime" , yourObject.getExpirationTime());//or your getter
q.executeUpdate();
I add a link to enforce the topic here.
Check if it works :-)

Categories