代码之家  ›  专栏  ›  技术社区  ›  black sensei

用接口休眠一对一的映射。我需要建议

  •  7
  • black sensei  · 技术社区  · 16 年前

    我正在开发一个应用程序,其中所有POJO都作为接口公开,但我们映射了真正的实现类。我们使用的是Spring和JPA注释。我将要测试一对一关系,我的接口有点问题。

    原因:org.springframework.beans.factory.beanCreationException:创建类路径资源[META-INF/model config.xml]中定义的名为“sessioncontainer”的bean时出错:
    设置构造函数参数时无法解析对bean“sessionFactory”的引用;嵌套的异常为org.springframework.beans.factory.beanCreationException:
    在类路径资源[META-INF/model config.xml]中创建名为“sessionFactory”的bean时出错:
    调用init方法失败;嵌套异常为org.hibernate.annotationException:
    @com.mycompany.project.subproject.model.useraccountimpl.profile上的onetoone或@manytoone引用了未知实体:com.mycompany.project。

    所以在这个类之前,所有其他映射类都按预期工作,所以我只发布 applicationContext 我命名的文件 model-config.xml

    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">${hibernate.dialect}</prop>
            <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
            <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
            <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
        </props>
    </property>
    <property name="annotatedClasses">
        <list>
           ...
            <value>com.mycompany.project.subproject.model.UserProfileImpl</value>
            <value>com.mycompany.project.subproject.model.UserAccountImpl</value>
           ...
        </list>
    </property>
    

    这是两个涉及的班级 UserProfileImpl.java UserAccountImpl.java

    //UserAccountImpl Class
    @Entity
    @Table(name ="USER_ACCOUNT")
    public class UserAccountImpl implements UserAccount {
    
      @Id @GeneratedValue
      @Column(name="USER_ACCOUNT_ID")
      private Long ID;
    
      ...
    
      @OneToOne
      @JoinColumn(name="USER_PROFILE_ID")
      private UserProfile profile;
    
      ...
    }
    
    //UserProfileImpl class
    @Entity
    @Table(name="USER_PROFILE")
    public class UserProfileImpl implements UserProfile {
    
      @Id @GeneratedValue
      @Column(name="USER_PROFILE_ID")
      private Long ID;
      ....
    
      @OneToOne(mappedBy="profile")
      private UserAccount userAccount;
      ....
    }
    

    我对冬眠还不是很满意,所以我想知道我是否应该改变 UserProfile 参考文献 UserAccountImpl UserProfileImpl 同样的情况也会发生在 用户界面IMPL 对于 userAccount 因为它是双向导航的东西。 什么是不会破坏结构一致性的最佳选择? 谢谢你看这个

    3 回复  |  直到 7 年前
        1
  •  2
  •   Nicolas Filotto    7 年前

    您可以尝试以下操作:

    @OneToOne(mappedBy="profile", targetEntity=UserAccountImpl.class)
    private UserAccount userAccount
    
        2
  •  3
  •   Aaron Digulla    16 年前

    您有以下选项:

    1. 您必须以某种方式告诉Hibernate接口要使用哪个类 UserAccount . 目前,最简单的解决方案是在 UserProfileImpl .

    2. 你可以使用 @Target 指定要使用的实现(请参见[文档][1])。

    3. 您可以使用自定义映射字段 UserType . 这允许在运行时选择映射(用于接口的实现),但您必须编写代码来复制业务对象和数据库之间的字段(不再自动映射)。

        3
  •  0
  •   alasdairg    16 年前

    用户配置文件必须是单独的实体吗?您可以将其建模为一个组件,并将useraccount和userprofile表组合为一个。您的对象模型仍然有一个单独的userprofile对象,它只是一个由useraccount拥有的值对象。

    并不是每个对象都必须作为一个实体来实现,而且一对一的映射在实践中非常罕见……