我正在創建一種像Facebook這樣的社交網站,作爲一個大學項目。用戶可以上傳照片,但我無法檢索特定用戶的照片列表。JPA - 如何避免獲取空列表?
以下是我正在做它現在:
@Entity
@Table(name = "users")
public class User implements Serializable {
@Id
private String emailAddress;
private String password;
private String firstName;
private String lastName;
(...)
@OneToMany(mappedBy = "owner", fetch = FetchType.EAGER)
private List<Photo> photos;
public User() {
}
(...)
public void addPhoto(Photo photo){
photos.add(photo);
}
public List<Photo> getPhotos() {
return photos;
}
}
而這裏的照片實體:
@Entity
public class Photo implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String url;
private String label;
@ManyToOne
private User owner;
public Photo() {
}
(...)
public User getOwner() {
return owner;
}
}
每張照片是通過創建一個包含它的後上傳。下面是做它的EJB:
@Stateless
public class PublicPost implements PublicPostRemote {
@PersistenceContext
EntityManager em;
@Override
public void createPost(LoginUserRemote loginUserBean, String targetEmail, final String content, final String photoURL) {
if (loginUserBean.isLoggedIn()) {
final User author = loginUserBean.getLoggedUser();
System.out.println(targetEmail);
final User target = em.find(User.class, targetEmail);
if (author != null && target != null) {
//See if there's a photo to post as well
Photo photo = null;
if (photoURL != null) {
photo = new Photo(photoURL, author, content);
em.persist(photo);
}
MessageBoard publicMessageBoard = target.getPublicMessageBoard();
Post post = new Post(author, content);
post.setMessageBoard(publicMessageBoard);
if (photo != null) {
post.setPostPhoto(photo);
}
em.persist(post);
em.refresh(publicMessageBoard);
//Send an e-mail to the target (if the author and the target are different)
if (!author.getEmailAddress().equals(target.getEmailAddress())) {
final String subject = "[PhaseBook] " + author.getEmailAddress() + " has posted on your public message board.";
Thread mailThread = new Thread() {
@Override
public void run() {
try {
GMailSender.sendMessage(target.getEmailAddress(), subject, content);
} catch (MessagingException ex) {
Logger.getLogger(PublicPost.class.getName()).log(Level.SEVERE, null, ex);
}
}
};
mailThread.start();
}
}
}
}
}
那麼什麼情況是:我創建一個包含照片,再稍後一個新的職位,當我用這個,在Web層...
LoginUserRemote lur = (LoginUserRemote)session.getAttribute("loginUserBean");
User user = lur.getLoggedUser();
List<Photo> photos = user.getPhotos();
System.out.println();
System.out.println("This user has this many photos: " + photos.size());
...它總是告訴我,用戶有0張照片。爲什麼是這樣?我是否錯誤地定義了用戶和照片之間的關係?我忘了堅持/刷新任何東西嗎?還是問題在別的地方?