【问题标题】:Using JPA mapped by not primary key field?使用非主键字段映射的 JPA?
【发布时间】:2010-08-30 05:23:34
【问题描述】:

我无法让这项工作正常进行,我想知道我正在做的事情是否没有意义?

public class Application {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="id")
    private long id;
    ....
}

@MappedSuperclass
public abstract class Sample {
    @Id @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @OneToOne (cascade=CascadeType.ALL)
    protected Application application;
    ....
}

// TestSample contains a list that is mapped not by the primary key of the Sample
public class TestSample extends Sample {
    @OneToMany(mappedBy="application", cascade=CascadeType.ALL, fetch=FetchType.LAZY)
    private List<Part> parts = new ArrayList<Part>();
    ....
}

public class Part {
    @Id @GeneratedValue(strategy = GenerationType.AUTO)
    private long id = 0;

    @ManyToOne (cascade=CascadeType.ALL, fetch=FetchType.LAZY)
    Application application;
}

我遇到的问题是我能够添加部分,数据库看起来正确,然后当我尝试获取 parts 列表时,我得到一个空列表。

如果我通过更改这些类在数据库结构上妥协,我可以让它工作:

// TestSample contains a list that is mapped not by the primary key of the Sample
public class TestSample extends Sample {
    @OneToMany(mappedBy="testSample", cascade=CascadeType.ALL, fetch=FetchType.LAZY)
    private List<Part> parts = new ArrayList<Part>();
    ....
}

public class Part {
    @Id @GeneratedValue(strategy = GenerationType.AUTO)
    private long id = 0;

    @ManyToOne (cascade=CascadeType.ALL, fetch=FetchType.LAZY)
    TestSample testSample;
}

表格是由休眠自动生成的,所以它们是这样出来的:

application
  id : number
  ....

test_sample
  id : number
  application_id : number
  ...

part
  id : number
  application_id : number

如果我将其更改为不太理想的工作方式,最后一张表会有所不同:

part
  id : number
  test_sample_id : number

因为所有情况下的 id 都是自动生成的,所以没有共享主键。本质上,我想要做的是使用 mappedby,其中 mappedby 指的是一个不是名为“TestSample”的表/类的主键的字段。我不确定这在 JPA 中是否有意义。

【问题讨论】:

  • 我不明白您的映射(您的一侧有 OneToOne,另一侧有 OneToMany)。如果不在 PK 上,外键是如何定义的?你能展示你的桌子吗?
  • 我已经添加了最后一课,希望这可以清除它。 TestSampleParts。但是因为TestSampleApplication 是一对一的关系,所以我在parts 列表中使用Application 的主键。
  • OneToMany 来自TestSample 不是双向的,为什么它有一个mappedBy?另外,请显示表格和约束,我想了解这应该如何工作(您是否在 ApplicationSample 之间使用共享主键?)
  • OneToMany 与“Part”类是双向的。我认为这很难解释(:

标签: java hibernate orm jpa


【解决方案1】:

OneToMany 与“Part”类是双向的。我认为这很难解释(:

TestSamplePart 之间的一对多关联不是双向的,mappedBy 不正确(application > 拥有关系,它甚至不知道test_sample),你的映射没有意义。有什么要改变的。

我认为您应该显示预期表是什么,而不是生成的表(由于映射不连贯,生成的结果不能令人满意)。您正在谈论妥协,所以我相信您对预期结果应该有一个想法。请出示。

【讨论】:

    猜你喜欢
    • 2019-10-04
    • 2011-02-26
    • 1970-01-01
    • 2017-01-30
    • 1970-01-01
    • 2015-02-03
    • 2019-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多