Search code examples
javajpaconstructorjpql

JPQL getResultList cast to class with more attributes than selected from database


I'm trying to do something like:

List<Report> results = new ArrayList<Report>();
results = em.createQuery("SELECT u.firstname, u.lastname, u.workEmail FROM Employee u", Report.class)
                        .getResultList();

However, Report has more attributes than the 3 columns selected from the database(and does not have a specific constructor for those exact 3 attributes), so results is turned into a Vector of Object instead of an ArrayList of Report. Is there a way to keep the results as an ArrayList and make all the other attributes of Report null ?


Solution

  •  List data =em.createQuery("SELECT u.firstname, u.lastname, u.workEmail FROM Employee u", Report.class)
                        .getResultList();
     List<Report> results = new ArrayList<Report>();
    
     for (Object object : data) {
        Map row = (Map) object;
        Report report = new Report();
        report.setFirstName(row.get("0"));
        report.setLastName(row.get("1"));
        report.setWorkEmail (row.get("2"));
        results.add(report); 
     }