Java - Query Spring with current date

Asked

Viewed 847 times

0

I have the following repository with the following method

@Query("SELECT m FROM Money m WHERE m.data = CURRENT_DATE()")
Money findTop1IfHasMoneyInCurrentDate();    

My money class is like this:

 @Entity
@Table(name="MONEY_DATA", schema="DEMO_PIMS")
@JsonIgnoreProperties(allowGetters=true)
public class Money  {

    @Id
    @Column(name="ID_REG")
    private Long Id;

    @Column(name="DATA")
    @JsonFormat(pattern="dd/MM/yyyy")
    @Temporal(TemporalType.TIMESTAMP)
    private Date data;

    @Column(name="DOLAR")
    private Double dolar;

    @Column(name="EURO")
    private Double euro;

    @Column(name="LIBRA")
    private Double libra;

    public Money() {

    }   

But it is always returning null when I call the "findTop1IfHasMoneyInCurrentDate()" and it has records on the current day.

What to do in Query to get a record according to the current day?

  • The function that calls the repository that executes the query, have you tried to see how it returns? From what I saw, the query would return an object Money. Have you ever done any System.out.println with the result of the query? Already took the body of the received request as String to check that everything is in order?

  • CURRENT_DATE() - java.sql.Date - returns the date only, your field is mapped as TIMESTAMP - java.sql.Timestamp. Use CURRENT_TIMESTAMP() - probably won’t, since you want the day and not the exact date time - or change your query. Your query also does not limit, so you can make an error too, so it returns a collection.

  • What SQL is generated when this query is executed?

  • Did you get the solution? The answer below helped you?

1 answer

1

According to the Java Persistence API specification, there are predefined functions CURRENT_DATE, CURRENT_TIME and CURRENT_TIMESTAMP.

The detail is in the use of it, that does not take parentheses, common for functions in programming languages. See:

@Query("SELECT m FROM Money m WHERE m.data = CURRENT_DATE")
Money findTop1IfHasMoneyInCurrentDate();    

Browser other questions tagged

You are not signed in. Login or sign up in order to post.