I'm starting to learn java. Tell me, because I already had a bunch of articles, but I could not find a solution. Feeling that I'm starting to get more and more confused.

There is the following class:

@Entity @Table(name = "CalendarResPlan") public class CalendarResPlanSet implements Serializable { @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "day") @Temporal(value=TemporalType.DATE) private Date day; @Column(name = "idRes") private String idRes; @Column(name = "needTime") private Long needTime; @Column(name = "idOperation") private String idOperation; 

I do the sample as follows:

  Query query = session.createQuery("SELECT " + "SUM(R.needTime), " + "R.day, " + "R.idRes " + "FROM " + "CalendarResPlanSet R " + "WHERE R.day = :day " + "AND R.idRes = :idRes " + "GROUP BY " + "R.day, " + "R.idRes"); query.setParameter("day", day); query.setParameter("idRes", idRes); CalendarResPlanSet planSet = (CalendarResPlanSet) query.uniqueResult(); 

Conversion fails. Gives the following message: cannot be cast to base.dataSets.CalendarResPlanSet

  • 2
    Though I’m not a Hibernate specialist, I don’t want to group by a table with a sum calculation and try to pretend to be a normal record from a table. Here it is not cast, as I understand it. - Eugene Krivenja September

1 answer 1

If you want to use aggregate functions in HQL / JPQL, then you have two options for obtaining results:

  1. Get a list of arrays of objects - List<Object[]> . The list item is a string, the array element is a field in a string:

     Query query = session.createQuery("SELECT " + "SUM(R.needTime), " + "R.day, " + "R.idRes " + "FROM " + "CalendarResPlanSet R " + "WHERE R.day = :day " + "AND R.idRes = :idRes " + "GROUP BY " + "R.day, " + "R.idRes"); query.setParameter("day", day); query.setParameter("idRes", idRes); List<Object[]> data = query.list(); if (data.size() > 0) { Long needTimeSum = data.get(0)[0]; ... } 
  2. Creating objects in the request:

     @Entity public class CalendarResPlanSet { ... public CalendarResPlanSet(Date day, String idRes, Long needTime) { this.day = day; this.idRes = idRes; this.needTime = needTime; } ... } Query query = session.createQuery("SELECT " + "new CalendarResPlanSet(" + "R.day, " + "R.idRes, " + "SUM(R.needTime)" + ") " + "FROM " + "CalendarResPlanSet R " + "WHERE R.day = :day " + "AND R.idRes = :idRes " + "GROUP BY " + "R.day, " + "R.idRes"); query.setParameter("day", day); query.setParameter("idRes", idRes); CalendarResPlanSet calResPlanSet = (CalendarResPlanSet) query.uniqueResult(); 

    Just keep in mind that the resulting entity will be transient and not fully initialized.