加载多对一关系

时间:2011-12-16 13:17:02

标签: jsp java-ee jpa

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

不幸的是,如果我向Book添加新的Shelf,则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>
<%  } 
%>

1 个答案:

答案 0 :(得分:1)

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