【发布时间】:2011-10-29 16:57:45
【问题描述】:
我正在创建一个社交网站,比如 Facebook,作为一个大学项目。用户可以上传照片,但我无法检索特定用户的照片列表。
这是我现在的做法:
@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;
}
}
这是 Photo 实体:
@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();
}
}
}
}
}
所以发生的事情是:我创建了一个包含照片的新帖子,但后来,当我在网络层使用它时...
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 张照片。为什么是这样?我是否错误地定义了用户和照片之间的关系?我是否忘记坚持/刷新任何东西?还是问题出在其他地方?
【问题讨论】: