java .lang.Object; не может быть приведен к классу модели: ошибка в Spring Boot - PullRequest
7 голосов
/ 21 февраля 2020

При извлечении данных из базы данных с использованием запроса JPQL с использованием весенней загрузки и попытке l oop данных я получаю следующую ошибку:

{
"message": "[Ljava.lang.Object; cannot be cast to com.spacestudy.model.RoomCPCMapping",
"error": "Internal Server Error",
"path": "/spacestudy/rockefeller/survey/surveyform/occupant/getClientCPCWithPercentage"
}

Мой запрос к репозиторию, подобный следующему,

@Query("SELECT u.nCCPCode,u.nPercent FROM RoomCPCMapping u JOIN u.clientCPC ur where u.nRoomAllocationId=:nRoomAllocationId")
List<RoomCPCMapping> findNCCPCodeByNRoomAllocationID(@Param(value="nRoomAllocationId") Integer nRoomAllocationId );

И я вызываю функцию запроса, как показано ниже,

List<RoomCPCMapping> 
        roomCpcMappingCodeObj = roomCPCMappingRepositoryObj.findNCCPCodeByNRoomAllocationID(nRoomAllocationID);

Используя объект результата, я пытаюсь l oop, как показано ниже,

for(RoomCPCMapping rpcLoopObj:roomCpcMappingCodeObj)
    {
        if(clientCpcCodeMappingLoopObj.nClientCPCMappingId==rpcLoopObj.getnCCPCode())                    
             {
                clientCpcCodeMappingLoopObj.nPercentage=rpcLoopObj.nPercent;
                }
    }

Мой класс Model, подобный следующему,

@Entity
@Table(name="roomccpcmapping")
public class RoomCPCMapping implements Serializable
{   

/**
 * 
 */
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "roomccpcmapping_seq_generator")
@SequenceGenerator(name = "roomccpcmapping_seq_generator", sequenceName = "roomccpcmapping_seq",allocationSize=1)

@Column(name="nroom_ccpc_mapping_id", columnDefinition="serial")
public Integer nRoomCcpcMappingId;

@Column(name="nroom_allocation_id")
public Integer nRoomAllocationId;

@Column(name="nccp_code")
public Integer nCCPCode;

@Column(name="npercent")
public Integer nPercent;

@Column(name="nresponsible_person_id")
public Integer nResponsiblePersonId;

@ManyToOne(optional = true, cascade = { CascadeType.MERGE })
@JoinColumn(name = "nccp_code", insertable = false, updatable = false)
public ClientCostPoolCodes clientCPC ;

public Integer getnRoomCcpcMappingId()
{
    return nRoomCcpcMappingId;
}

public void setnRoomCcpcMappingId(Integer nRoomCcpcMappingId) 
{
    this.nRoomCcpcMappingId = nRoomCcpcMappingId;
}

public Integer getnRoomAllocationId()
{
    return nRoomAllocationId;
}

public void setnRoomAllocationId(Integer nRoomAllocationId)
{
    this.nRoomAllocationId = nRoomAllocationId;
}

public Integer getnCCPCode() 
{
    return nCCPCode;
}

public void setnCCPCode(Integer nCCPCode) 
{
    this.nCCPCode = nCCPCode;
}

public Integer getnPercent()
{
    return nPercent;
}

public void setnPercent(Integer nPercent)
{
    this.nPercent = nPercent;
}

public Integer getnResponsiblePersonId() 
{
    return nResponsiblePersonId;
}

public void setnResponsiblePersonId(Integer nResponsiblePersonId)
{
    this.nResponsiblePersonId = nResponsiblePersonId;
}

public ClientCostPoolCodes getClientCPC() 
{
    return clientCPC;
}

public void setClientCPC(ClientCostPoolCodes clientCPC)
{
    this.clientCPC = clientCPC;
}


public RoomCPCMapping(Integer nRoomCcpcMappingId, Integer nRoomAllocationId, Integer nCCPCode, Integer nPercent,
        Integer nResponsiblePersonId, ClientCostPoolCodes clientCPC) {
    super();
    this.nRoomCcpcMappingId = nRoomCcpcMappingId;
    this.nRoomAllocationId = nRoomAllocationId;
    this.nCCPCode = nCCPCode;
    this.nPercent = nPercent;
    this.nResponsiblePersonId = nResponsiblePersonId;
    this.clientCPC = clientCPC;
}

public RoomCPCMapping() {

 }
}

Почему я получаю ошибки такого типа?

Ответы [ 3 ]

3 голосов
/ 21 февраля 2020

Опция 1) Убедитесь, что RoomCPCMapping является интерфейсом проекции:

public interface RoomCPCMappingResult {

    String getNCCPCode();
    String getNPercent();

    ...
}

Опция 2) Используйте устаревшую опцию класса результата:

SELECT new com.my.package.RoomCPCMappingResult(u.nCCPCode,u.nPercent)
FROM RoomCPCMapping u JOIN u.clientCPC ur 
where u.nRoomAllocationId=:nRoomAllocationId

просто убедитесь, что у вас есть соответствующий конструктор.

0 голосов
/ 02 марта 2020

вы можете использовать отдельный bean-компонент с конструктором с двумя параметрами, как упомянул Мачей Ковальский.

@Query("SELECT u.nCCPCode,u.nPercent FROM RoomCPCMapping u JOIN u.clientCPC ur where u.nRoomAllocationId=:nRoomAllocationId")
List<RoomCPCMapping> findNCCPCodeByNRoomAllocationID(@Param(value="nRoomAllocationId") Integer nRoomAllocationId );

Или ELSE просто обновите запрос

   @Query("SELECT u FROM RoomCPCMapping u JOIN u.clientCPC ur where u.nRoomAllocationId=:nRoomAllocationId")
    List<RoomCPCMapping> findNCCPCodeByNRoomAllocationID(@Param(value="nRoomAllocationId") Integer nRoomAllocationId );

Hope It помогает.

0 голосов
/ 21 февраля 2020

Согласно Spring Data JPA, когда вы выполняете собственный запрос с селективным параметром (u.nCCPCode, u.nPercent), а не целой сущностью (*), он возвращает объект или массив объектов.

Итак, измените ваш тип возвращаемого значения,

List<RoomCPCMapping> => List<Object[]>

И после этого вы поместите его в свой класс сущности на сервисном уровне (как и ранее, мы делаем, чтобы связать значение ResultSet в сущности).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...