2011-12-16 2 views
0

어떻게 작동하는지 이해하기 위해 Java EE에서 매우 기본적인 라이브러리 응용 프로그램을 작성하고 있습니다. 이 응용 프로그램을 사용하면 사용자가 선반과 연결된 책을 추가 할 수 있습니다. 협회는 양방향으로, 다 대일이므로 책이 속한 책장을 book.getShelf(), 책꽂이에 shelf.getBooks()이 포함되어있는 책을 가져올 수 있기를 기대합니다.다 대일 관계 로딩

불행히도 ShelfBook을 새로 추가하면이 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의 지속성은 다음 무 상태 세션 빈에 의해 관리되고, BookManager :

다음은 엔티티의 코드의 일부입니다. 또한 선반에있는 서적 목록을 검색하는 방법이 포함되어 있습니다 (getBooksInShelf). 는 JSP에서

@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: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

5 년 전부터 "J2EE"가 "Java EE"로 업그레이드 된 상태에서 책을 유지하고 선반을 다시로드하는 방법과 트랜잭션을 관리하는 방법을 보여줄 필요가 있습니다. "J2EE"는 JPA에 대한 개념이 전혀 없습니다. 최신 상태로 유지하십시오.) – BalusC

+0

@BalusC 답장을 보내 주셔서 감사합니다. 지금 볼 수 있듯이 나는 거래를 관리하지 않는다 (어쩌면 그것이 문제 일까?) – Ale

답변

1

당신은 양방향 관계를 유지해야합니다. 새 책을 만들고 선반을 설정할 때 선반 책에 책을 추가해야합니다.

관련 문제