【问题标题】:Persisting entities with references to other entity classes in JPA在 JPA 中使用对其他实体类的引用来持久化实体
【发布时间】:2012-01-12 06:46:40
【问题描述】:

我正在使用 JSF 2.1、Netbeans 7.0.1、Glassfish 3.1.1、JPA + EJB。

例如,我有一个名为 User 的实体类,它与实体类 UserType 具有引用(多对一关系)。

与实体 UserType 关联的表 user_type 已经加载了所有可能的用户类型,并且不应将任何数据添加到该表中。表 user_type 中的数据仅用于选择。

在其中一种形式中,我要求用户为正在创建的用户选择 UserType h:selectOneListBox 标记。在支持 bean 中,我创建了新的 UserType 对象,将选择的 id 设置为它并将 UserType 放入 User 实体类中。但是,创建的 UserType 对象中的所有其他字段都是空的。

我的问题是,当我将 User 持久保存到数据库中时,JPA 会“理解”具有 User 实体引用的此类 id 的 UserType 已经存在于数据库中,并且只会更新(合并)现有记录而不尝试创建新的一个。 或者我必须通过其 id 从数据库中预加载所需的实体 UserType,然后将其放入 User 并要求 JPA 更新 UserType?

【问题讨论】:

    标签: jpa jsf-2 merge entity persist


    【解决方案1】:

    <h:selectOneListBox> 组件中,我认为您应该只取出UserTypeID。之后,您可以要求您的 EJB 为您创建关系。它应该是这样的:

    @Stateless
    public class MrStatelessBean {
       public void createUser(User u, long typeID) {
          UserType type = em.find(UserType.class, typeID);
          u.setUserType(type);
          em.persist(u);
       }
    }  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-22
      • 1970-01-01
      • 2016-03-13
      • 1970-01-01
      • 2011-07-16
      • 2011-12-22
      相关资源
      最近更新 更多