Work with Date in Mysql, JPA

Asked

Viewed 290 times

0

I’m using JPA and creating an entity to store one date within the database. So far so good, the problem is that I need to display the database information according to the month of my date. Do you happen to have a way when you perform JPQL ask to return only with the selected month? Example:

public void exemplo(Date data){     
    String jpql = "select t from time t where t.data.getmes() = cData"
    Query query = em.createQuery(jpql);

    query.setParameter("cData", data);
}

1 answer

1


First you can make a change in your query to check only the month, using the method MONTH. Behold:

select t from time t where MONTH(t.data.getmes()) = cData

Then simply redeem the month you are spending on your variable data as parameter using Calendar. Behold:

Calendar cal = Calendar.getInstance();
cal.setTime(data);
int month = cal.get(Calendar.MONTH);

query.setParameter("cData", month);

Upshot:

public void exemplo(Date data){     
    String jpql = "select t from time t where MONTH(t.data.getmes()) = cData"
    Query query = em.createQuery(jpql);

    Calendar cal = Calendar.getInstance();
    cal.setTime(data);
    int month = cal.get(Calendar.MONTH);

    query.setParameter("cData", month);
}

Browser other questions tagged

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