Springboot репозиторий jpa ClassCastException - PullRequest
0 голосов
/ 31 августа 2018

У меня есть проект springboot, и я подключаюсь к своей базе данных mysql для выполнения запросов. У меня есть объект Exportbatch:

@Entity(name = "Exportbatch")
@Table(name = "exportbatch")
public class Exportbatch
{
@EmbeddedId
private ExportbatchId id;

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

@Column(name = "serverurl")
private String serverURL;

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

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

@Column(name = "size")
private int size;

public Exportbatch()
{

}

public Exportbatch(ExportbatchId id, String container, String serverURL, String owner, String date, int size)
{
    this.id = id;
    this.container = container;
    this.serverURL = serverURL;
    this.owner = owner;
    this.batchlastupdate = date;
    this.size = size;

}

public ExportbatchId getId()
{
    return id;
}

public void setId(ExportbatchId id)
{
    this.id = id;
}

public String getContainer()
{
    return container;
}

public void setContainer(String container)
{
    this.container = container;
}

public String getServerURL()
{
    return serverURL;
}

public void setServerURL(String serverURL)
{
    this.serverURL = serverURL;
}

public String getOwner()
{
    return owner;
}

public void setOwner(String owner)
{
    this.owner = owner;
}

public String getBatchlastupdate()
{
    return batchlastupdate;
}

public void setBatchlastupdate(String batchlastupdate)
{
    this.batchlastupdate = batchlastupdate;
}

public int getSize()
{
    return size;
}

public void setSize(int size)
{
    this.size = size;
}

public String toString()
{
    String string = "project name: " + this.id.getProjectname() + "\n" + "building id: " + this.id.getBuildingId()
            + "\n" + "container id: " + this.container + "\n" + "hemis url: " + this.serverURL + "\n"
            + "lastTimeUpdate: " + this.batchlastupdate;

    return string;
}

уникальный ключ exportbatch - составной объект exportbatchId:

@Embeddable
public class ExportbatchId implements Serializable
{

private static final long serialVersionUID = 1L;

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

@Column(name = "buildingid")
private String buildingId;

@Column(name = "timestamp")
private Timestamp timestamp;

public ExportbatchId(String projectname, String buildingId, Timestamp timestamp)
{
    this.projectname = projectname;
    this.buildingId = buildingId;
    this.timestamp = timestamp;
}

public ExportbatchId()
{

}

public String getProjectname()
{
    return projectname;
}

public void setProjectname(String projectname)
{
    this.projectname = projectname;
}

public String getBuildingId()
{
    return buildingId;
}

public void setBuildingId(String buildingId)
{
    this.buildingId = buildingId;
}

public Timestamp getTimestamp()
{
    return timestamp;
}

public void setTimestamp(Timestamp timestamp)
{
    this.timestamp = timestamp;
}
}

Я определил новый метод в ExportbatchRepository:

public interface ExportbatchRepository extends JpaRepository<Exportbatch, ExportbatchId>
{

@Query(value = "select id.buildingId, id.projectname, id.timestamp, container, serverURL, owner, batchlastupdate, size,  max(timestamp)  from Exportbatch group by id.buildingId")
List<Exportbatch> findlatest();

Page<Exportbatch> findAll(Pageable pageable);
}

И в моем контроллере я делаю это:

@RestController
public class Controller
{

@Autowired // This means to get the bean called userRepository
// Which is auto-generated by Spring, we will use it to handle the data
private ExportbatchRepository exportbatchRepository;

@RequestMapping("/getlastbatchsproblemes")
public void getbatchinfo()
{
    try
    {
        List<Exportbatch> list = exportbatchRepository.findlatest();

        for (Exportbatch exportbatch : list)
        {
            // System.out.println(exportbatch.getBatchlastupdate());
            System.out.println(exportbatch.toString());
        }

        System.out.println(list.size());
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
}
}

Я получаю это исключение, когда звоню "/ getlastbatchsproblemes": java.lang.ClassCastException: [Ljava.lang.Object; не может быть приведен к example.domain.Exportbatch .

Но когда я звоню find, все работает нормально.

Почему я получаю это исключение, может ли кто-нибудь помочь мне с этим?

1 Ответ

0 голосов
/ 31 августа 2018

Я думаю, что проблема в вашем запросе, помните, что jpql требует, чтобы вы поместили псевдоним в таблицу, и что псевдоним должен использоваться в каждом поле, попробуйте это:

@Query(value = "select ex.id.buildingId, ex.id.projectname, ex.id.timestamp, ex.container, ex.serverURL, ex.owner, ex.batchlastupdate, ex.size,  max(ex.id.timestamp)  from Exportbatch ex group by ex.id.buildingId") 
List<Exportbatch> findlatest();

Обратите внимание на ex. в начале каждого поля, которое вы извлекаете, и в качестве псевдонима в части from.

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