gpt4 book ai didi

java - 带接口(interface)的 Hibernate 一对一映射。我需要建议

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:29:15 24 4
gpt4 key购买 nike

我正在开发一个应用程序,其中所有的 pojo 都作为接口(interface)公开,但我们映射了真正的实现类。我们正在使用 spring 和 JPA 注释。我将要测试一对一关系,我正在界面有轻微问题。

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionContainer' defined in class path resource [META-INF/model-config.xml]:
Cannot resolve reference to bean 'sessionFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'sessionFactory' defined in class path resource [META-INF/model-config.xml]:
Invocation of init method failed; nested exception is org.hibernate.AnnotationException:
@OneToOne or @ManyToOne on com.mycompany.project.subproject.model.UserAccountImpl.profile references an unknown entity: com.mycompany.project.

所以在这个类之前,所有其他映射类都按预期工作,所以我只会发布我命名为 model-config.xmlapplicationContext 文件的一部分>/p>

<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.javaUserAccountImpl.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;
....
}

我对 hibernate 还不太适应,所以我想知道是否应该将 UserAccountImpl 中的 UserProfile 引用更改为 UserProfileImpl .然后在 UserProfileImpl 中同样会发生 userAccount 引用,因为它是双向导航的东西。不会破坏结构一致性的最佳选择是什么?感谢阅读本文

最佳答案

您有以下选择:

  1. 您必须以某种方式告诉 Hibernate 将哪个类用于接口(interface) UserAccount。目前,最简单的解决方案是在 UserProfileImpl 中使用具体类型而不是接口(interface)。

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

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

关于java - 带接口(interface)的 Hibernate 一对一映射。我需要建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1700690/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com