问题描述:

Sorry for posting this same question again but i am curious to know.

I want to know how we can compare a current date from java with stored date in mysql.

date stored in MySQL is 2013-01-04 13:15:00

when i compare this date in java by getting current date

Date date = new Date();

then wrote a query if the date stored in MySQL is less than current display the result. but query is returning 0 result in the List or an exception I have pasted the exception at the end.

select model from abc model where model.abcStartDate <= :? and model.abcEndDate >= :?

In ":?" date is passed

In the MySQL The start date and end date are of timestamp data type.

Below is the EJB entity class

@Entity

@Table(name = "abc_table", uniqueConstraints = {})

public class ABCClass implements java.io.Serializable {

private static final long serialVersionUID = -1924961655993587546L;

// Fields

private Date abcStartDate;

private Date abcEndDate;

// Constructors

/** default constructor */

public ABCClass() {

}

@OrderBy(value="3")

@Temporal(TemporalType.TIMESTAMP)

@Column(name = "abc_start_date", unique = false, nullable = false, insertable = true, updatable = true, length = 19)

public Date getabcStartDate() {

return this.abcStartDate;

}

public void setabcStartDate(Date abcStartDate) {

this.abcStartDate = abcStartDate;

}

@OrderBy(value="4")

@Temporal(TemporalType.TIMESTAMP)

@Column(name = "abc_end_date", unique = false, nullable = false, insertable = true, updatable = true, length = 19)

public Date getabcEndDate() {

return this.abcEndDate;

}

public void setabcEndDate(Date abcEndDate) {

this.abcEndDate = abcEndDate;

}

}

and it throws an exception

Exception thrown from bean; nested exception is: Exception [EclipseLink-3001] (Eclipse Persistence Services - 2.2.1.v20110722-r9776): org.eclipse.persistence.exceptions.ConversionException

Exception Description: The object [65464533565], of class [class java.lang.String], could not be converted to [class java.lang.Integer].

Internal Exception: java.lang.NumberFormatException: For input string: "65464533565"

网友答案:

Date comparison in JPQL can be done by following ways.

If you are comparing with current date & time

select model from abc model where model.abcStartDate >= CURRENT_TIMESTAMP 
and model.abcEndDate >= CURRENT_TIMESTAMP 

or create a query and pass parameter

query = em.createQuery("select model from abc model where model.abcStartDate >= 
:time and model.abcEndDate >= :time");
query.setParameter("time", new Date(), TemporalType.TIMESTAMP);
相关阅读:
Top