0
我在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
}
的Book
和Shelf
的持久性是通過以下無狀態會話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>
<% }
%>
你需要展示你如何堅持這本書,重新裝載書架以及如何管理事務(PS:「J2EE」在5年前被升級爲「Java EE」。絕對沒有JPA的概念,保持自己最新)。 – BalusC 2011-12-16 13:24:06