gpt4 book ai didi

java - 如何连接非主键列上的表?

转载 作者:行者123 更新时间:2023-11-30 06:30:02 25 4
gpt4 key购买 nike

我在 ORM 类层次结构中的对象上连接表时遇到问题,其中连接列不是基类的主键,原因是滞后数据库结构。这是表格设计的示例:

CREATE TABLE "SCH"."FOO"
(
"OWNERID" NUMBER(10,0) NOT NULL ENABLE,
"FOOID" NUMBER(10,0) NOT NULL ENABLE,
CONSTRAINT "FOO_PK" PRIMARY KEY ("OWNERID", "FOOID")
CONSTRAINT "FOO_FK1" FOREIGN KEY ("OWNERID") REFERENCES "SCH"."OWNERS" ("OWNERID") ENABLE
)

CREATE TABLE "SCH"."BAR"
(
"BARID" NUMBER(10,0) NOT NULL ENABLE,
"FOOID" NUMBER(10,0)
CONSTRAINT "BAR_PK" PRIMARY KEY ("BARID")
)

这是映射(删除了不必要的信息)

@Entity
@IdClass(FooId.class)
@Table(name = "FOO")
public class Foo implements java.io.Serializable
{
@Id
@Column(name = "OWNERID")
private BigInteger ownerId;

@Id
@SequenceGenerator(name = "FOO_GENERATOR", sequenceName = "SEQ_FOO")
@GeneratedValue(generator = "FOO_GENERATOR")
@Column(name = "FOOID")
private BigInteger id;

@OneToMany(fetch = FetchType.LAZY)
@JoinColumn(name = "FOOID", referencedColumnName = "FOOID")
@Fetch(value = FetchMode.SUBSELECT)
@Cascade(value = {CascadeType.ALL})
private Set<Bar> bar = new LinkedHashSet<Bar>(0);
}


@Entity
@Table(name = "BAR")
public class Bar implements java.io.Serializable
{
@Id
@Column(name = "BARID")
private BigInteger id;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "FOOID", referencedColumnName = "FOOID")
private Foo foo;
}

失败并出现异常:

Caused by: org.hibernate.AnnotationException: referencedColumnNames(FOOID) of com.package.Bar.foo referencing com.package.Foo not mapped to a single property
at org.hibernate.cfg.BinderHelper.createSyntheticPropertyReference(BinderHelper.java:204)
at org.hibernate.cfg.ToOneFkSecondPass.doSecondPass(ToOneFkSecondPass.java:114)
at org.hibernate.cfg.Configuration.processEndOfQueue(Configuration.java:1580)
at org.hibernate.cfg.Configuration.processFkSecondPassInOrder(Configuration.java:1503)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1419)
at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1375)

你能帮忙解决一下吗?

最佳答案

您不得两次映射双向关联。必须使用 mappedBy 属性将 One side 标记为 Many side 的反面:

@OneToMany(fetch = FetchType.LAZY, mappedBy = "foo")
@Fetch(value = FetchMode.SUBSELECT)
@Cascade(value = {CascadeType.ALL})
private Set<Bar> bar = new LinkedHashSet<Bar>(0);

...

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "FOOID", referencedColumnName = "FOOID")
private Foo foo;

没有理由两次告诉 Hibernate 该关联是由连接列 FOOID 映射的。而这样做实际上是一个错误,因为它定义了两个不同的单向关联,而不是一个双向关联。

编辑

上面的代码应该可以工作,但由于以下 Hibernate 错误而无法正常工作:这是一个 Hibernate 错误。参见 HHH-4284 .

为了避免这个问题,因为FOOID足以确保唯一性,解决方案是从所有者ID和中删除@Id注解@IdClass注解。

关于java - 如何连接非主键列上的表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10895173/

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