java.lang.ClassCastException:[Ljava.lang.Object;无法投放到

时间:2017-05-31 12:44:42

标签: java jpa

为什么在我的程序中触发了java.lang.ClassCastException?

  

java.lang.ClassCastException:[Ljava.lang.Object;无法施展   com.App.Equip]

查询返回已回答的检查表列表(可在CheckLists calsse中找到)但尚未通过Equip对象回答

- 这是代码:

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; 
   }

- 我的java类:

@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;
}

我想以Json格式格式化SQl查询的结果。 以下是SQL查询返回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
   ]
......
]

有人会介意给我一些建议吗?

非常感谢!!!

3 个答案:

答案 0 :(得分:3)

您的查询返回的List Object[]因为您没有选择Equip实体,但您只选择了以下列:

   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不会将ResultSet结果转换为Equip实体对象,结果将是object的数组,因为Hibernate不会确定所选列的类型。

您需要遍历此List元素并手动将每个Object[]转换为Equip对象。

修改

这是你应该如何实现的:

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);
}

答案 1 :(得分:2)

通过使用List解决了我的问题:使用以下代码:

<html>
<head>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  
<script src="https://code.angularjs.org/1.6.1/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-animate.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-sanitize.js"></script>
    <script src="https://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.5.0.js"></script>
  
</head>

<div class="container">

<div ng-app="myApp" ng-controller="MyCtrl">


    <pre>Selected date is: <em>{{dt | date:'MM/dd/yyyy' }}</em></pre>
    <p>above filter will just update above UI but I want to update actual ng-modle</p>


    <h4>Popup</h4>
    <div class="row">
      <div class="col-md-6">
        <p class="input-group">
          <input type="text" class="form-control" uib-datepicker-popup="{{format}}" 
          ng-model="dt" is-open="opened" min-date="minDate" max-date="'2018-06-22'"
          ng-model-options="{timezone: 'UTC'}" 
          datepicker-options="dateOptions" date-disabled="disabled(date, mode)"
          ng-required="true" close-text="Close" />
          
          
          <span class="input-group-btn"> 
                <button type="button" class="btn btn-default" ng-click="open($event)">
                <i class="glyphicon glyphicon-calendar"></i></button>
              </span>
        </p>
      </div>
    </div>


<table  class="table table-striped table-bordered">
    <thead>
      <tr>
	 <th>Employee ID</th>
	<th>name</th>
    </thead>
    <tbody>
  
   <tr ng-repeat="data in list">
      <td> {{ data.eid }} </td>
      <td> {{ data.ename }} </td>
    </tr>
</tbody>
  
</table>

</div>



</div>

我们之后返回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); }

答案 2 :(得分:0)

query.getResultList()返回List<Object[]>

因此,您可以使用JPA查询返回List<Equip>

来自JPA 2.0

使用映射实体(如Jure Kolenko所说)

createNativeQuery(sql, Equip.class) 

来自JPA 2.1

如果您想将结果映射到POJO类,请使用SqlResultSetMapping

  

示例:

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是您的实体类

中的字段

@ColumnResult是ResultList中的结果列,不存在于您的实体类

请参阅完整示例here