我是 vaadin 的新手,我正在尝试使用 vaadin 实现 EclipseLink,在我的项目中,我正在尝试使用 eclipselink 从 db 获取状态列表,并且我正在我的主文件中获取结果集,但是当尝试使用 for each loop 将这些项目添加到表中,我遇到了一个奇怪的错误
com.vaadin.server.ServiceException: java.lang.ClassCastException: com.example.dao.States cannot be cast to com.example.dao.States.
PFB 代码片段
主要 Java 文件:
@WebServlet(value = "/*", asyncSupported = true)
@VaadinServletConfiguration(productionMode = false, ui = VaadintestUI.class)
public static class Servlet extends VaadinServlet {
}
@Override
protected void init(VaadinRequest request) {
final String PERSISTENCE_UNIT_NAME = "com.test.jpa";
EntityManagerFactory factory;
final VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = factory.createEntityManager();
Query q = em.createQuery("select s from States s");
List<States> stateList = q.getResultList();
System.out.println("Size: " + stateList.size());
Table table = new Table("The US States");
table.addContainerProperty("Name", String.class, null);
table.addContainerProperty("Population", Integer.class, null);
for (int i = 0; i < stateList.size(); i++)
{
table.addItem(new Object[]{ stateList.get(i).getState(),stateList.get(i).getPopulation()},i);
}
table.setPageLength(table.size());
layout.addComponent(table);
}
}
持久化.xml
<persistence-unit name="com.test.jpa" transaction-type="RESOURCE_LOCAL">
<class>com.example.dao.States</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/testdb" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="root" />
</properties>
</persistence-unit>
状态.java
@Entity
public class States {
@Id
private Long id;
private String state;
private String population;
//Setters and getters//
堆栈跟踪导致:java.lang.ClassCastException:com.example.dao.States 无法转换为 com.example.dao.States 在 com.example.vaadintest.VaadintestUI.init(VaadintestUI.java:69) 在 com.vaadin.ui.UI.doInit(UI.java:645) 在 com.vaadin.server.communication.UIInitHandler.getBrowserDetailsUI(UIInitHandler.java:222) 在 com.vaadin.server.communication.UIInitHandler.synchronizedHandleRequest(UIInitHandler.java:74) 在 com.vaadin.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:41)
最佳答案
尝试使用 TypedQuery 而不是 Query:
TypedQuery q = em.createQuery("select s from States s", States.class); 列表 stateList = q.getResultList();
另请参阅以下内容:java.lang.ClassCastException: sametype cannot be cast to sametype 一些遇到此错误的人在重新启动服务器时已将其清除。因此,请尝试全新构建、重新启动并重新部署。
关于java - 将列表中的项目添加到 vaadin 表的 Vaadin 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27295586/