我有一对多的关系(个人资料到消息)。我试图保存某个用户/个人资料拥有的消息。下面的代码有什么问题?
public Message createMessage(Message msg, String recepient) {
EntityManager em = EMF.get().createEntityManager();
UserAccess access = new UserAccess();
Profile user = access.searchUser(recepient);
msg.setUser(user);
em.getTransaction().begin();
em.persist(msg);
em.getTransaction().commit();
em.close();
return msg;
}
搜索用户方法
public Profile searchUser(String displayName){
EntityManager em = EMF.get().createEntityManager();
Profile user;
try{
Query q = em.createNamedQuery("Profile.searchByDisplayName");
q.setParameter("displayName", displayName);
user = (Profile) q.getSingleResult();
} catch(javax.persistence.NoResultException e){
user = null;
}
em.close();
return user;
}
我遇到了以下错误:
java.lang.IllegalStateException: Primary key for object of type Profile is null.