如何在 JPA 中定义单向 OneToMany 关系 [英] How to define unidirectional OneToMany relationship in JPA

查看:24
本文介绍了如何在 JPA 中定义单向 OneToMany 关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 JPA 中的实体映射有以下问题.我有两个实体,第一个是 Lookup,第二个是代表实体翻译的 Text.现在我需要将 Lookup 绑定到 Text,但我不希望 Text 引用 Lookup.为了使这更复杂,Text 在此关系中不使用其主键,而是使用 TXTHEAD_CODE 列中定义的元代码.

I have a following problem with entity mapping in JPA. I have two entities, first one is Lookup and the second is Text which represents translations for entities. Now I need to bound Lookup to the Text but I don't want Text to have reference to Lookup. To make this more complicated, Text does not use its primary key in this relationship but a metacode defined in a TXTHEAD_CODE column.

Lookup.java

@Entity
@Table(name = "DATREG")
public class Lookup implements PersistableEntity {

    @Id
    @Column(name = "DATREG_META_CODE")
    private String metaCode;

    @OneToMany
    @JoinTable(name="TXT", 
            joinColumns=@JoinColumn(name="DATREG_META_CODE", referencedColumnName="TXTHEAD_CODE"),
            inverseJoinColumns=@JoinColumn(name="DATREG_META_CODE"))
    private List<Text> text;

Text.java

@Entity
@Table(name = "TXT")
public class Text {

    @Id
    @Column(name = "TXT_ID")
    private Long id;

    @Column(name = "TXTHEAD_CODE")
    private String code;

所以我尝试了这个(以及其他一些变体)但没有结果.我也无法在数据库中创建连接表,并且我不想将 Lookup 绑定到我的 Text 类.所以有没有人可以告诉我是否有其他方法?

So I have tried this (and few other variations) but with no result. I also can't create join table in the DB and I don't want bound Lookup to my Text class. So can anyone please tell me if there is some other way?

推荐答案

我的 JPA 工作圣经是 Java持久性维基书.它有一个 部分关于单向 OneToMany/code> 解释了如何使用 @JoinColumn 注释来做到这一点.在你的情况下,我认为你会想要:

My bible for JPA work is the Java Persistence wikibook. It has a section on unidirectional OneToMany which explains how to do this with a @JoinColumn annotation. In your case, i think you would want:

@OneToMany
@JoinColumn(name="TXTHEAD_CODE")
private Set<Text> text;

我使用了 Set 而不是 List,因为数据本身没有排序.

I've used a Set rather than a List, because the data itself is not ordered.

以上使用的是默认的referencedColumnName,这与维基书中的示例不同.如果这不起作用,请尝试一个明确的:

The above is using a defaulted referencedColumnName, unlike the example in the wikibook. If that doesn't work, try an explicit one:

@OneToMany
@JoinColumn(name="TXTHEAD_CODE", referencedColumnName="DATREG_META_CODE")
private Set<Text> text;

这篇关于如何在 JPA 中定义单向 OneToMany 关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆