2011-12-16 47 views
0

我在Java EE中编写了一个非常基本的库应用程序,以了解它是如何工作的。此应用程序允许用户添加与书架关联的书籍。该协会是双向的,多对一,所以我期望能够获得该书所属的书架book.getShelf()以及书架包含shelf.getBooks()的书籍。加载多对一的关系

不幸的是,如果我添加一个新的BookShelf,这Book直到我重新部署我的应用程序不会被shelf.getBooks()返回。我需要你的帮助才能明白我做错了什么。

这里是实体的部分代码:

@Entity 
public class Book implements Serializable { 
    private static final long serialVersionUID = 1L; 
    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private Long id; 
    protected String title; 
    protected String author; 
    @ManyToOne(fetch=FetchType.EAGER) 
    protected Shelf shelf; 

    //getters and setters follow 
} 

@Entity 
public class Shelf implements Serializable { 
    private static final long serialVersionUID = 1L; 
    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private Long id; 

    @OneToMany(mappedBy = "shelf") 
    private List<Book> books; 

    protected String genre; 

    //getters and setters follow 
} 

BookShelf的持久性是通过以下无状态会话bean管理,BookManager。它还包含检索书架中书籍列表的方法(getBooksInShelf)。

@Stateless 
@LocalBean 
public class BookManager{ 
    @EJB 
    private ShelfFacade shelfFacade; 
    @EJB 
    private BookFacade bookFacade; 

    public List<Shelf> getShelves() { 
     return shelfFacade.findAll(); 
    } 

    public List<Book> getBooksInShelf(Shelf shelf) { 
     return shelf.getBooks(); 
    } 

    public void addBook(String title, String author, String shelf) { 
     Book b = new Book(); 
     b.setName(title); 
     b.setAuthor(author); 
     b.setShelf(getShelfFromGenre(shelf)); 
     bookFacade.create(b); 
    } 

    //if there is a shelf of the genre "shelf", return it 
    //otherwise, create a new shelf and persist it 
    private Shelf getShelfFromGenre(String shelf) { 
     List<Shelf> shelves = shelfFacade.findAll(); 
     for (Shelf s: shelves){ 
      if (s.getGenre().equals(shelf)) return s; 
     } 
     Shelf s = new Shelf(); 
     s.setGenre(shelf); 
     shelfFacade.create(s); 
     return s; 
    } 

    public int numberOfBooks(){ 
     return bookFacade.count(); 
    } 

} 

在JSP:(我只写了本书介绍的部分代码)

<jsp:useBean id="bookManager" class="sessionBean.BookManager" scope="request"/> 
// ... 
<% List<Book> books; 
    for(Shelf s: shelves){ 
     books = bookManager.getBooksInShelf(s); 
%> 
     <h2><%= s.getGenre() %></h2> 
     <ul> 
<%  if (books.size()==0){ 
%>   <p>The shelf is empty.</p> 
<%  } 
     for (Book b: books){ 
%>   <li> <em><%= b.getAuthor()%></em>, <%= b.getName() %> </li> 
<%  } 
%>  </ul> 
<% } 
%> 
+0

你需要展示你如何坚持这本书,重新装载书架以及如何管理事务(PS:“J2EE”在5年前被升级为“Java EE”。绝对没有JPA的概念,保持自己最新)。 – BalusC 2011-12-16 13:24:06

回答

1

你必须保持双向的关系。当您创建新书并设置书架时,您必须将书添加到书架的书籍中。