当我尝试使用Hibernate OneToMany Mapping获取资源时,我正在使用Hibernate和Jersey创建一个项目并收到500 Internel Server error
。我正在使用Apache TomCat进行部署。细节如下。
有两个具有OneToMany关系的模型类。 Category
和Book
,类别可以包含多本图书。 POST请求工作正常,但当我尝试使用以下URL获取书籍时,会发生500内部服务器。我无法找到原因并且不知道我做错了什么,因为我已经检查了将资源返回给泽西岛,资源对象似乎完全没问题。
请帮助我
API网址为。
/webapi/category/{categoryID}/books
/webapi/category/{categoryID}/books/{bookID}
下面给出了类的代码。
模型类
这是分类。
@Entity
@Table(name = "category")
@XmlRootElement
public class Category {
@Id
@GeneratedValue
private int categoryID;
private String categoryName;
@OneToMany(cascade = { CascadeType.ALL }, mappedBy = "category", fetch = FetchType.EAGER)
private List<Book> Book = new ArrayList<Book>();
public Category(){
}
// Getters and Setters
}
这是Book Class。
@Entity
@Table(name = "book")
@XmlRootElement
public class Book {
@Id
@GeneratedValue
private int bookID;
private String bookName;
private String bookAuthor;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "Category_ID")
private Category category;
//getter and setters
}
DAO类用于从数据库中使用Hibernate获取数据。 这是CateogryDAO。
public class CategoryDAO {
@SuppressWarnings("unchecked")
public List<Category> getCategoryList() {
Session session = HibernateUtil.openSession();
session.beginTransaction();
List<Category> categoryList = (List<Category>)session.createQuery("from Category").list();
session.getTransaction().commit();
session.close();
return categoryList;
}
public Category addCategory(Category cat) {
Session session = HibernateUtil.openSession();
session.beginTransaction();
// for updating existing labels and creating new ones
session.persist(cat);
session.getTransaction().commit();
session.close();
return cat;//changing also return type
}
public Category updateCategory( Category cat) {
Session session = HibernateUtil.openSession();
session.beginTransaction();
// for updating existing labels and creating new ones
session.update(cat);
session.getTransaction().commit();
session.close();
return cat;//changing also return type
}
public Category getCategoryById(int categoryID) {
Session session = HibernateUtil.openSession();
session.beginTransaction();
Category category = (Category) session.get(Category.class, categoryID);
System.out.println("CATDAO"+ category.getCategoryName());
session.getTransaction().commit();
session.close();
return category;
}
public void removeCategory(Category category) {
Session session = HibernateUtil.openSession();
session.beginTransaction();
session.delete(category);
session.getTransaction().commit();
session.close();
}
}
这是BookDAO Class。
public class BookDAO {
@SuppressWarnings("unchecked")
public List<Book> getBooksList(int categoryID) {
Session session = HibernateUtil.openSession();
session.beginTransaction();
String sql = "SELECT * FROM Book WHERE Category_ID ="+ categoryID;
System.out.println(sql);
SQLQuery query = session.createSQLQuery(sql);
query.addEntity(Book.class);
List<Book> bookList = query.list();
System.out.println(bookList.get(0).getBookAuthor());
session.getTransaction().commit();
session.close();
return bookList;
}
public Book addBook(Book book) {
Session session = HibernateUtil.openSession();
session.beginTransaction();
// for updating existing labels and creating new ones
session.persist(book);
session.getTransaction().commit();
session.close();
return book;// changing also return type
}
public Book updateBook(Book book) {
Session session = HibernateUtil.openSession();
session.beginTransaction();
// for updating existing labels and creating new ones
session.update(book);
session.getTransaction().commit();
session.close();
return book;// changing also return type
}
public Book getBookById(int bookID) {
Session session = HibernateUtil.openSession();
session.beginTransaction();
Book book = (Book) session.get(Book.class, bookID);
session.getTransaction().commit();
session.close();
return book;
}
public void removeBook(Book book) {
Session session = HibernateUtil.openSession();
session.beginTransaction();
session.delete(book);
session.getTransaction().commit();
session.close();
}
}
泽西岛资源类。
类别资源类。
@Path("/category")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class CategoryResource {
CategoryDAO catdao = new CategoryDAO();
@GET
@Path("/hello")
@Produces(MediaType.TEXT_PLAIN)
public String getIt() {
return "Got it!";
}
@GET
public List<Category> getCategories() {
System.out.println("Getting All Categories");
List<Category> catlist = catdao.getCategoryList();
for (Category tempcat : catlist) {
System.out.println(tempcat.getCategoryName());
List<Book> booklist = tempcat.getBook();
for (Book book : booklist) {
System.out.println(book.getBookName());
}
}
return catlist;
}
// to get a single book for this LinksGetter is used
@GET
@Path("/{categoryID}")
public Response getCategoryById(@PathParam("categoryID") int categoryID, @Context UriInfo caturiInfo) {
System.out.println("Category ID = " + categoryID);
Category category = catdao.getCategoryById(categoryID);
String catselfUrl = LinksGetter.getLinkForSelfCategory(caturiInfo, category);
category.addcatLink(catselfUrl, "self");
return Response.status(Status.OK).entity(category).build();
}
@POST
public Category addCategory(Category category) {
return catdao.addCategory(category);
}
@PUT
@Path("/{categoryID}") // --->http://localhost:8080/helloworld/webapi/category/2
public Category updateCategory(@PathParam("categoryID") int categoryID, Category category) {
category.setCategoryID(categoryID);
return catdao.updateCategory(category);
}
@DELETE
@Path("/{categoryID}")
public void deleteCategory(@PathParam("categoryID") int categoryID) {
Category category = catdao.getCategoryById(categoryID);
catdao.removeCategory(category);
}
//we dont use GET POST because we want it for every request
@Path("/{categoryID}/books")
public BookResource getBookResource() {
return new BookResource();
}
}
这是图书资源类。
@Path("/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class BookResource {
BookDAO bookdao = new BookDAO();
CategoryDAO catdao = new CategoryDAO();
@GET
public List<Book> getBooks(@PathParam("categoryID") int categoryID) {
java.awt.Toolkit.getDefaultToolkit().beep();
System.out.println("Getting Books");
List<Book> books = null;
books = bookdao.getBooksList(categoryID);
System.out.println(books.get(0).getCategory().getCategoryName());
return books;
}
@GET
@Path("/{bookID}")
public Response getBookById(@PathParam("bookID") int bookID, @Context UriInfo uriInfo) {
Book book = bookdao.getBookById(bookID);
java.awt.Toolkit.getDefaultToolkit().beep();
String selfUrl = LinksGetter.getLinkForSelfBook(uriInfo, book);
book.addLink(selfUrl, "self");
return Response.status(Status.OK).entity(book).build();
}
@POST
public Book addBook(@PathParam("categoryID") int categoryID, Book book) {
Category category=catdao.getCategoryById(categoryID);
book.setCategory(category);
return bookdao.addBook(book);
}
@PUT
@Path("/{bookID}")
public Book updateBook(@PathParam("bookID") int bookID, Book book){
book.setBookID(bookID);
return bookdao.updateBook(book);
}
@DELETE
@Path("/{bookID}")
public void deleteBook(@PathParam("bookID") int bookID) {
System.out.println("Deleting Book");
Book book = bookdao.getBookById(bookID);
bookdao.removeBook(book);
}
}
这是我运行服务器时的consol日志
org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre8\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x86;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x64;C:\Program Files (x86)\Skype\Phone\;.
Mar 24, 2016 1:52:57 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:helloworld' did not find a matching property.
Mar 24, 2016 1:52:57 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Mar 24, 2016 1:52:57 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Mar 24, 2016 1:52:57 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1089 ms
Mar 24, 2016 1:52:57 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Mar 24, 2016 1:52:57 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.39
Mar 24, 2016 1:53:01 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Mar 24, 2016 1:53:01 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Mar 24, 2016 1:53:01 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 3890 ms