【问题标题】:Hibernate/JPA Join Two Tables With Composite Keys (No Foreign Relationship) [duplicate]Hibernate/JPA 使用复合键连接两个表(无外部关系)[重复]
【发布时间】:2016-03-18 20:28:26
【问题描述】:

我对使用 JPA/Hibernate 还是很陌生。我正在尝试找出用复合键连接两个表且没有真正的数据库关系的最佳方法。

enter image description here

@Embeddable
public class StepPK implements Serializable{
    @Column(name = "step_id")
    protected String stepId;

    @Column(name = "packet_id")
    protected String packetId;
    ...
}


@Entity
@Table(name = "step_def")
@IdClass(StepPK.class)
public class InprocessPacketStep implements Serializable{

    @Id
    private String stepId;

    @Id
    private String packetId;

}


@Embeddable
public class StepDetailPK implements Serializable {
    @Column(name = "step_id")
    protected String stepId;

    @Column(name = "packet_id")
    protected String packetId;

    @Column(name="user_id")
    protected String userId;

    @Column(name="parallel_step_id")
    protected String parallelId;
    ...
}

@Entity
@Table(name = "step_detail")
@IdClass(StepDetailPK.class)
public class InprocessPacketStepDetail implements Serializable {

    @Id
    private String stepId;

    @Id
    private String packetId;

    @Id
    private String parallelId;

    @Id
    private String userId;
}

到目前为止,我在单独从表格中提取信息时效果很好,但我需要一些方法将它们加入 step_id。由于确实没有分配关系,因此执行 OneToMany 和 JoinColumns 似乎不起作用。

我尝试过使用 ManyToMany,它在编译时不会崩溃,但在检查我的测试时,它会导致 SQLGrammar 异常。

我唯一的另一个想法是通过查询手动加入它们,但运行 entityManager.createQuery("select InprocessPacketStep step join inprocessPacketStepDetail d on d.stepId = step.stepId") 会导致运行时错误。

任何建议将不胜感激。我花了很多时间在谷歌上搜索尝试不同的东西,但没有成功。

【问题讨论】:

  • 哦,上面的图片链接是基本的表格描述
  • 请提供有关所遇到错误的更多信息。另外,你想得到什么输出?
  • 为什么不能使用附加关系表?这些实体之间是什么关系?

标签: java hibernate jpa


【解决方案1】:

如果您的数据库架构不是旧的并且您可以更改它,那么 @ManyToMany 与附加关系表的关联应该可以解决问题:

网络上有很多 examples 用于流行的 JPA 2.x 实现框架(当然包括 Hibernate)

否则你应该尝试从这个线程解决: @ManyToMany without join table (legacy database)

【讨论】:

    猜你喜欢
    • 2016-10-06
    • 1970-01-01
    • 2011-03-20
    • 2021-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-18
    • 2018-02-02
    相关资源
    最近更新 更多