gpt4 book ai didi

java - Embeddable、Hibernate 中的多对一关系

转载 作者:太空宇宙 更新时间:2023-11-04 11:36:55 24 4
gpt4 key购买 nike

我有一个场景,hibernate 中的 Embeddable 类使用Entity。根据我在SO和其他链接上找到的各种答案,我们可以在Embeddable类中编写@ManyToOne,@OneToMany

但是这样做会给我 HibernateMappingExeption

考虑以下示例:我有两个实体和一个可嵌入类,如下所示:

实体A

@Entity
@Table(name = "A")
public class A {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int a_id;

@ElementCollection
@JoinTable(name = "embeded_class_table", joinColumns = @JoinColumn(name = "a_id"))
private List<EmbeddedClass> embeddedClass;

实体B

@Entity
@Table(name = "B")
public class B {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int b_id;

使用实体 B 的嵌入式类

@Embeddable
public class EmbeddableClass {

@ManyToOne
@JoinColumn(name = "b_id")
private B b;

我收到的错误如下:

org.hibernate.MappingException: Could not determine type for: app.model.B, at table: embeded_class_table, for columns: [org.hibernate.mapping.Column(b)]

有人可以建议我是否正确使用这些东西,如果是的话,我错过了什么?

最佳答案

假设您的情况我尝试了以下操作,但没有遇到任何问题:

@Entity
@Table(name = "A")
public class A {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int a_id;

@ElementCollection
@JoinTable(name = "embeded_class_table", joinColumns = @JoinColumn(name = "a_id"))
private List<EmbeddableClass> embeddedClass;

public int getA_id() {
return a_id;
}

public void setA_id(int a_id) {
this.a_id = a_id;
}

public List<EmbeddableClass> getEmbeddedClass() {
return embeddedClass;
}

public void setEmbeddedClass(List<EmbeddableClass> embeddedClass) {
this.embeddedClass = embeddedClass;
}

}

@Entity
@Table(name = "B")
public class B {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int b_id;
}

@Embeddable
public class EmbeddableClass {

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "b_id")
private B b;

public B getB() {
return b;
}

public void setB(B b) {
this.b = b;
}


}

hibernate.cfg.xml

<hibernate-configuration>
<session-factory>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.password">xxxx</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="hibernate.connection.username">elias</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="hibernate.hbm2ddl.auto">create-drop</property>
<property name="show_sql">true</property>
<mapping class="com.springex.dto.A"></mapping>
<mapping class="com.springex.dto.B"></mapping>
<mapping class="com.springex.dto.EmbeddableClass"></mapping>
</session-factory>
</hibernate-configuration>

关于java - Embeddable、Hibernate 中的多对一关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43185365/

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