5

why java.lang.ClassCastException is triggered in my program ?

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.App.Equip]

The query returns the list of checklists that are answered (found in the CheckLists calsse) and not yet answered by Equip object

-Here is the code:

import org.json.simple.*;

    @SuppressWarnings("unchecked")

public JSONObject ListCheckListsNonETRepondu( long idEqp, long idmiss){

       Query query = manager.createNativeQuery("SELECT"
        + " checksl.id_check_lists as IdCheckLists,"
        + " checksl.titre_check as NomCheckLists,"
        + " checksl.recommendation as Recommendation, "
        + " resp.id_responsescheck as IdResponse, "
        + " resp.conformite as Conformite, "
        + " resp.date_response as DateResponse, "
        + " resp.missions_id as IdMission "
        + " FROM equipements eq "
        + " LEFT JOIN check_lists checksl"
        + " ON eq.id_equipements= checksl.equipements_id "
        + " LEFT JOIN responses_check_lists resp "
        + " ON checksl.id_check_lists = resp.check_lists_id "
        + " AND resp.missions_id ="+idmiss+""
        + " AND eq.id_equipements ="+idEqp
        + " ORDER BY checksl.id_check_lists"
         );

   List<Equip> res = query.getResultList();

   JSONObject obj = new JSONObject();

   for( Equip eq: res) //--The problem is here --
   {
       for(CheckLists checks : eq.getChecks())
       {
              obj.put("idCheckLists", checks.getIdCheckLists());
              obj.put("NomCheckLists", checks.getTitreCheck());
              obj.put("Recommendation", checks.getRecommendation());

              for(ResponsesCheckLists resp :checks.getResponsesChecks())
               {
                  obj.put("IdResponse",resp.getIdResponsesCHeck());
                  obj.put("DateResponse",resp.getDateResponse());
                  obj.put("Conformite",resp.isConformite());
                  obj.put("IdMission",resp.getRespmission().getIdMission());
               }
       }

   }
   return (JSONObject)obj; 
   }

-My java classes:

@Entity
public class CheckLists implements Serializable{

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="idCheckLists")
    private long idCheckLists;

    @Column(name="titreCheck")
    private String titreCheck;

    @Column(name="recommendation")
    private String recommendation;

    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name="equipements_id")
    @JsonBackReference
    private Equipements equipements;

    @OneToMany(mappedBy="CheckLts", cascade=CascadeType.ALL, fetch=FetchType.EAGER)
    //@Fetch(value = FetchMode.SUBSELECT)
    private Set<ResponsesCheckLists> ResponsesChecks;
 ..
}

//
@Entity
public class ResponsesCheckLists implements Serializable{

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="idResponsesCHeck")
    private long idResponsesCHeck;

    @Column(name="conformite")
    private boolean conformite;

    @Column(name="dateResponse")
    private String dateResponse;

    @ManyToOne
    @JoinColumn(name="missionsId")
    private Missions Respmission;

    @ManyToOne
    @JoinColumn(name="checkLists_Id")
    private CheckLists CheckLts;

....
}

//
@Entity
public class Equip implements Serializable{


    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="idEquipements")
    private long idEquipements;

    @Column(name="nomEq")
    private String nomEq;

    @Column(name="dateAjoutEq")
    private String dateAjoutEq;

    @Column(name="dateModificationEq")
    private String dateModificationEq;

    @OneToMany(mappedBy="equipements", cascade=CascadeType.ALL, fetch=FetchType.EAGER)
    //@Fetch(value = FetchMode.SUBSELECT)
    @JsonManagedReference
    private Set<CheckLists> checks;

    @ManyToOne
    @JoinColumn(name="actifs_id")
    private Actifs actifsEquipements;
}

I want to format the result of my SQl query in Json format. Here is what the SQL query returns query.getResultList():

[
   [
    1,
   "2.1 Create Separate Partition ",
   "Description.... ",
    1,
    false,
   "25/05/2017",
    15
  ],
  [
    2,
   "2.2 Set nodev option ",
  " Description:.... ",
    1,
    false,
   "25/05/2017",
   15
   ]
......
]

could anyone mind giving some advice for me?

Thanks a lot!!!

9
  • At which line this exception is thrown? Commented May 31, 2017 at 12:49
  • What is Equip? What is Query? are you using some library? The main problem is, probably, that the list returned by query.getResultList(); has pure Object elements which cannot be cast to Equip, a reference to the classes you are using is necessary to understand the real problem. Commented May 31, 2017 at 12:50
  • In this line for( Equip eq: res) //--The problem is here -- Commented May 31, 2017 at 12:50
  • Your query is returning an Object. Use the createNativeQuery(String sqlString, Class resultClass) method with a class parameter, eg createNativeQuery(sql, Equip.class). This might not work if query return column names don't map to the entity class. Commented May 31, 2017 at 12:51
  • @bracco23 I updated the post, thanks Commented May 31, 2017 at 13:02

3 Answers 3

10

Your query is returning a List of Object[] because you aren't selecting an Equip Entity, but you are only selecting columns in :

   Query query = manager.createNativeQuery("SELECT"
    + " checksl.id_check_lists as IdCheckLists,"
    + " checksl.titre_check as NomCheckLists,"
    + " checksl.recommendation as Recommendation, "
    + " resp.id_responsescheck as IdResponse, "
    + " resp.conformite as Conformite, "
    + " resp.date_response as DateResponse, "
    + " resp.missions_id as IdMission "

Hibernate won't convert the ResultSet results to an Equip entity object, the result will be an array of objects because Hibernate won't determine the types of selected columns.

You need to loop over this List elements and transform each Object[] to an Equip object manually.

Edit:

This is how you should implement it:

List<Object[]> res = query.getResultList();
List<Equip> list= new ArrayList<Equip>();
JSONObject obj = new JSONObject();

Iterator it = res.iterator();
while(it.hasNext()){
     Object[] line = it.next();
     Equip eq = new Equip();
     eq.setIdEquipement(line[0]);
     eq.setTitre(line[1]);
     eq.setDescription(line[2]);
     //And set all the Equip fields here
     //And last thing add it to the list

     list.add(eq);
}
Sign up to request clarification or add additional context in comments.

5 Comments

How to get the text in Object [] and display it like this { "idEquipement":"1", "titre":2.1 Create Separate Partition , "description":"Description: ......", }
You need to lop over this array of objects.
how @chsdk,? I am a beginner in java
@Michel Check my eDit.
Thanks for your reply @ chsdk , i will test now
2

My problem is solved through the use of the List: using the following code:

List<Object[]> res = query.getResultList(); 
List<Equip> list= new ArrayList<Equip>(); 

Iterator it = res.iterator();
while(it.hasNext()){
     Object[] line = it.next();
     Equip eq = new Equip();
     eq.setIdEquipement(line[0]);
     eq.setTitre(line[1]);
     eq.setDescription(line[2]);

     list.add(eq);
}

We return afterwards list

Comments

0

query.getResultList() returns List<Object[]>

So you can either use JPA query to return List<Equip> or

From JPA 2.0

use mapped entities (as Jure Kolenko said)

createNativeQuery(sql, Equip.class) 

From JPA 2.1

If you want map your result to POJO class use SqlResultSetMapping

Example:

Query q = em.createNativeQuery(
    "SELECT o.id AS order_id, " +
        "o.quantity AS order_quantity, " +
        "o.item AS order_item, " +
        "i.name AS item_name, " +
    "FROM Order o, Item i " +
    "WHERE (order_quantity > 25) AND (order_item = i.id)",
"OrderResults");

@SqlResultSetMapping(name="OrderResults", 
    entities={ 
        @EntityResult(entityClass=com.acme.Order.class, fields={
            @FieldResult(name="id", column="order_id"),
            @FieldResult(name="quantity", column="order_quantity"), 
            @FieldResult(name="item", column="order_item")})},
    columns={
        @ColumnResult(name="item_name")}
)

@FieldResult is the field from your Entity class

@ColumnResult is the result column from your ResultList that not exist into the your Entity class

See complete example here

4 Comments

I did not understand what this line is: @ColumnResult(name="item_name")} @Mike Adamenko
@MikeAdamenko isn't it only copy paste from this url -- >> docs.oracle.com/javaee/7/api/javax/persistence/… Need to delete this..
@VikrantKashyap this example is rather copied from url link SqlResultSetMapping right above the example
complete example here link is broken

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.