当我什至没有将 ArrayList 转换为 class 时,错误提示“java.lang.ClassCastException: java.util.ArrayList 无法转换为”
error says " java.lang.ClassCastException: java.util.ArrayList cannot be cast to" when I'm not even casting ArrayList to the class
我可能在这里遗漏了什么,但我一直没弄明白。
所以我写了一个 Servlet,从本质上讲,它旨在帮助我从数据库或书籍中下载文件,如果您愿意的话。现在我知道这个错误:
22:05:18,349 ERROR [io.undertow.request] (default task-6) UT005023: Exception handling request to /PubHub/DownloadBook: java.lang.ClassCastException: java.util.ArrayList cannot be cast to examples.pubhub.model.Book
at examples.pubhub.servlets.DownloadBookServlet.doGet(DownloadBookServlet.java:37)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
at org.apache.logging.log4j.web.Log4jServletFilter.doFilter(Log4jServletFilter.java:71)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.security.handlers.AuthenticationConstraintHandler.handleRequest(AuthenticationConstraintHandler.java:53)
at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
at io.undertow.servlet.handlers.security.ServletSecurityConstraintHandler.handleRequest(ServletSecurityConstraintHandler.java:59)
at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292)
at io.undertow.servlet.handlers.ServletInitialHandler.access0(ServletInitialHandler.java:81)
at io.undertow.servlet.handlers.ServletInitialHandler.call(ServletInitialHandler.java:138)
at io.undertow.servlet.handlers.ServletInitialHandler.call(ServletInitialHandler.java:135)
at io.undertow.servlet.core.ServletRequestContextThreadSetupAction.call(ServletRequestContextThreadSetupAction.java:48)
at io.undertow.servlet.core.ContextClassLoaderSetupAction.call(ContextClassLoaderSetupAction.java:43)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
at io.undertow.servlet.handlers.ServletInitialHandler.access[=16=]0(ServletInitialHandler.java:81)
at io.undertow.servlet.handlers.ServletInitialHandler.handleRequest(ServletInitialHandler.java:104)
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)
at io.undertow.server.HttpServerExchange.run(HttpServerExchange.java:805)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
意味着我不安全地将 ArrayList 转换为 ArrayList 不是其子类的对象。问题是,我什至没有将 ArrayList 转换为该对象,在本例中为 Book。
我不确定是什么导致了这个问题,我检查了实体,甚至在其他地方搜索了相同的转换:
Servlet 代码:
package examples.pubhub.servlets;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import examples.pubhub.dao.BookDAO;
import examples.pubhub.model.Book;
import examples.pubhub.utilities.DAOUtilities;
/**
* Servlet implementation class DownloadBookservlet
*/
@WebServlet("/DownloadBook")
public class DownloadBookServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
/* String isbn = request.getParameter("isbn_13"); */
String isbn = request.getParameter("isbn_13");
BookDAO dao = DAOUtilities.getBookDAO();
Book book = dao.getBookByISBN(isbn);
// In order to download the PDF to the client, we need to add a data stream to the response.
// First we set the content type to PDF, so the browser knows how to interpret the data it's receiving
response.setContentType("application/pdf");
// Then we set the filename to the book's title, so it's not a random string of characters
response.setHeader("Content-Disposition", "attachment; filename=" + book.getTitle() + ".pdf");
// Create the input stream (IN to the app FROM the book)
InputStream is = new ByteArrayInputStream(book.getContent());
// Create the output stream (OUT of the app TO the client)
OutputStream os = response.getOutputStream();
// We're going to read and write 1KB at a time
byte[] buffer = new byte[1024];
// Reading returns -1 when there's no more data left to read.
while (is.read(buffer) != -1) {
os.write(buffer);
}
// Always close your streams!
os.flush();
os.close();
is.close();
}
}
导致错误的方法代码:
@Override
public Book getBookByISBN(String isbn) {
Session session = DAOUtilities.getSessionFactory().openSession();
session.beginTransaction();
Query query = session.createQuery("from Book where isbn_13 =:isbn_13");
query.setParameter("isbn_13", isbn);
Book book = (Book) query.uniqueResult();
session.getTransaction().commit();
return book;
}
代码为实际class/object/entity,书:
package examples.pubhub.model;
import java.time.LocalDate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "books")
public class Book {
@Id
@Column(name="isbn_13")
public String isbn_13; // International Standard Book Number, unique
@Column(name="title")
private String title;
@Column(name="author")
private String author;
@Column(name="publish_date")
private LocalDate publish_date; // Date of publish to the website
@Column(name="price")
private double price;
@Column(name="content")
private byte[] content;
// Constructor used when no date is specified
public Book(String isbn, String title, String author, byte[] content, double price) {
super();
this.isbn_13 = isbn;
this.title = title;
this.author = author;
this.publish_date = LocalDate.now();
this.content = content;
this.price = price;
}
// Constructor used when a date is specified
public Book(String isbn, String title, String author, LocalDate publishDate, double price, byte[] content) {
super();
this.isbn_13 = isbn;
this.title = title;
this.author = author;
this.publish_date = publishDate;
this.content = content;
this.price = price;
}
// Default constructor
public Book() {
}
public String getIsbn_13() {
return isbn_13;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public LocalDate getPublish_date() {
return publish_date;
}
public void setPublish_date(LocalDate publishDate) {
this.publish_date = publishDate;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public byte[] getContent() {
return content;
}
public void setContent(byte[] content) {
this.content = content;
}
public void setIsbn_13(String isbn) {
this.isbn_13 = isbn;
}
如您所见,我没有将 Array List(我这样拼写以通过拼写检查)转换为它。但也许在尝试将它投射到这个实体时我没有得到一些东西。我使用的休眠版本是 5.1.6(5.2 有问题)。
如有任何建议,我们将不胜感激。
我解决了。问题在于我如何使用 Hibernate 映射其他 类。
我可能在这里遗漏了什么,但我一直没弄明白。
所以我写了一个 Servlet,从本质上讲,它旨在帮助我从数据库或书籍中下载文件,如果您愿意的话。现在我知道这个错误:
22:05:18,349 ERROR [io.undertow.request] (default task-6) UT005023: Exception handling request to /PubHub/DownloadBook: java.lang.ClassCastException: java.util.ArrayList cannot be cast to examples.pubhub.model.Book at examples.pubhub.servlets.DownloadBookServlet.doGet(DownloadBookServlet.java:37) at javax.servlet.http.HttpServlet.service(HttpServlet.java:687) at javax.servlet.http.HttpServlet.service(HttpServlet.java:790) at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85) at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129) at org.apache.logging.log4j.web.Log4jServletFilter.doFilter(Log4jServletFilter.java:71) at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61) at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131) at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84) at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62) at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36) at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78) at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131) at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57) at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) at io.undertow.security.handlers.AuthenticationConstraintHandler.handleRequest(AuthenticationConstraintHandler.java:53) at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46) at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64) at io.undertow.servlet.handlers.security.ServletSecurityConstraintHandler.handleRequest(ServletSecurityConstraintHandler.java:59) at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60) at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77) at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50) at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43) at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61) at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292) at io.undertow.servlet.handlers.ServletInitialHandler.access0(ServletInitialHandler.java:81) at io.undertow.servlet.handlers.ServletInitialHandler.call(ServletInitialHandler.java:138) at io.undertow.servlet.handlers.ServletInitialHandler.call(ServletInitialHandler.java:135) at io.undertow.servlet.core.ServletRequestContextThreadSetupAction.call(ServletRequestContextThreadSetupAction.java:48) at io.undertow.servlet.core.ContextClassLoaderSetupAction.call(ContextClassLoaderSetupAction.java:43) at io.undertow.servlet.api.LegacyThreadSetupActionWrapper.call(LegacyThreadSetupActionWrapper.java:44) at io.undertow.servlet.api.LegacyThreadSetupActionWrapper.call(LegacyThreadSetupActionWrapper.java:44) at io.undertow.servlet.api.LegacyThreadSetupActionWrapper.call(LegacyThreadSetupActionWrapper.java:44) at io.undertow.servlet.api.LegacyThreadSetupActionWrapper.call(LegacyThreadSetupActionWrapper.java:44) at io.undertow.servlet.api.LegacyThreadSetupActionWrapper.call(LegacyThreadSetupActionWrapper.java:44) at io.undertow.servlet.api.LegacyThreadSetupActionWrapper.call(LegacyThreadSetupActionWrapper.java:44) at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272) at io.undertow.servlet.handlers.ServletInitialHandler.access[=16=]0(ServletInitialHandler.java:81) at io.undertow.servlet.handlers.ServletInitialHandler.handleRequest(ServletInitialHandler.java:104) at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202) at io.undertow.server.HttpServerExchange.run(HttpServerExchange.java:805) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source)
意味着我不安全地将 ArrayList 转换为 ArrayList 不是其子类的对象。问题是,我什至没有将 ArrayList 转换为该对象,在本例中为 Book。
我不确定是什么导致了这个问题,我检查了实体,甚至在其他地方搜索了相同的转换:
Servlet 代码:
package examples.pubhub.servlets;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import examples.pubhub.dao.BookDAO;
import examples.pubhub.model.Book;
import examples.pubhub.utilities.DAOUtilities;
/**
* Servlet implementation class DownloadBookservlet
*/
@WebServlet("/DownloadBook")
public class DownloadBookServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
/* String isbn = request.getParameter("isbn_13"); */
String isbn = request.getParameter("isbn_13");
BookDAO dao = DAOUtilities.getBookDAO();
Book book = dao.getBookByISBN(isbn);
// In order to download the PDF to the client, we need to add a data stream to the response.
// First we set the content type to PDF, so the browser knows how to interpret the data it's receiving
response.setContentType("application/pdf");
// Then we set the filename to the book's title, so it's not a random string of characters
response.setHeader("Content-Disposition", "attachment; filename=" + book.getTitle() + ".pdf");
// Create the input stream (IN to the app FROM the book)
InputStream is = new ByteArrayInputStream(book.getContent());
// Create the output stream (OUT of the app TO the client)
OutputStream os = response.getOutputStream();
// We're going to read and write 1KB at a time
byte[] buffer = new byte[1024];
// Reading returns -1 when there's no more data left to read.
while (is.read(buffer) != -1) {
os.write(buffer);
}
// Always close your streams!
os.flush();
os.close();
is.close();
}
}
导致错误的方法代码:
@Override
public Book getBookByISBN(String isbn) {
Session session = DAOUtilities.getSessionFactory().openSession();
session.beginTransaction();
Query query = session.createQuery("from Book where isbn_13 =:isbn_13");
query.setParameter("isbn_13", isbn);
Book book = (Book) query.uniqueResult();
session.getTransaction().commit();
return book;
}
代码为实际class/object/entity,书:
package examples.pubhub.model;
import java.time.LocalDate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "books")
public class Book {
@Id
@Column(name="isbn_13")
public String isbn_13; // International Standard Book Number, unique
@Column(name="title")
private String title;
@Column(name="author")
private String author;
@Column(name="publish_date")
private LocalDate publish_date; // Date of publish to the website
@Column(name="price")
private double price;
@Column(name="content")
private byte[] content;
// Constructor used when no date is specified
public Book(String isbn, String title, String author, byte[] content, double price) {
super();
this.isbn_13 = isbn;
this.title = title;
this.author = author;
this.publish_date = LocalDate.now();
this.content = content;
this.price = price;
}
// Constructor used when a date is specified
public Book(String isbn, String title, String author, LocalDate publishDate, double price, byte[] content) {
super();
this.isbn_13 = isbn;
this.title = title;
this.author = author;
this.publish_date = publishDate;
this.content = content;
this.price = price;
}
// Default constructor
public Book() {
}
public String getIsbn_13() {
return isbn_13;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public LocalDate getPublish_date() {
return publish_date;
}
public void setPublish_date(LocalDate publishDate) {
this.publish_date = publishDate;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public byte[] getContent() {
return content;
}
public void setContent(byte[] content) {
this.content = content;
}
public void setIsbn_13(String isbn) {
this.isbn_13 = isbn;
}
如您所见,我没有将 Array List(我这样拼写以通过拼写检查)转换为它。但也许在尝试将它投射到这个实体时我没有得到一些东西。我使用的休眠版本是 5.1.6(5.2 有问题)。
如有任何建议,我们将不胜感激。
我解决了。问题在于我如何使用 Hibernate 映射其他 类。