简体   繁体   中英

Hibernate errors in named queries

I am trying to pull information from a table where the current date is between the first and last day of any given month.

I am getting a runtime error "Errors in named queries: Department.byDate"

I am providing you with what code I think could be causing the problem, if any additional code is needed please let me know in a comment.

My named query which looks like this:

@NamedQuery(name="Department.byDate", query="select * from department where date >= :first AND date <= :last")

I am using this named query in my DAO in a method which looks like this:

public List<Department> getRecords(Date dateFirst, Date dateLast){
    Session session= sessionFactory.openSession();
    session.beginTransaction();

    Query query = session.getNamedQuery("Department.byDate");
    query.setDate("first", dateFirst);
    query.setDate("last", dateLast);

    List<Department> depList = (List<Department>)query.list();

    session.getTransaction().commit();
    session.close();

    return depList;
}

My method of getting that first and last days of the months looks like this:

Calendar first = Calendar.getInstance();
first.set(Calendar.getInstance().get(Calendar.YEAR), Calendar.getInstance().get(Calendar.MONTH), Calendar.getInstance().getActualMinimum(Calendar.DAY_OF_MONTH));
Date dateFirst = first.getTime();

Calendar last = Calendar.getInstance();
first.set(Calendar.getInstance().get(Calendar.YEAR), Calendar.getInstance().get(Calendar.MONTH), Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH));
Date dateLast = last.getTime();
  1. In HQL/JPQL you are working with entities and their properties, thus * character has no meaning.
  2. HQL/JPQL class and property names are case sensitive .

You should write your query the following way:

select d from Department d where d.date >= :first AND d.date <= :last

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM