映射一对多单向关系 [英] Mapping a OneToMany unidirectional relationship

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

问题描述

以这些表为例,其中每个person可以具有多个address es.

 CREATE TABLE person (
    id INTEGER NOT NULL PRIMARY KEY,
    name VARCHAR(100) NOT NULL
);
 

 CREATE TABLE address (
    id INTEGER NOT NULL PRIMARY KEY,
    address VARCHAR(100) NOT NULL,
    city VARCHAR(100) NOT NULL,
    person_id INTEGER NOT NULL
);
 

我想将这些表映射到JPA实体,但是我不想使用mappedBy映射它们之间的双向关系.

PersonAddress之间映射OneToMany单向关系的正确方法是什么?考虑到Person必须知道他们的Address es,但是Address一定不知道它属于的Person.

解决方案

您无需使其双向.您只需将@OneToMany批注放在Person中的集合类型的字段上,然后指定address表的JoinColumn.

请参见此处,示例3.这就是您要寻找的.

所以您将得到类似的东西:

// In Person class:

@OneToMany
@JoinColumn(name="person_id")
public Set<Address> getAddresses() {return addresses;}

没有mappedBy属性,没有双向映射.

Considering these tables as example, where each person can have multiple addresses.

CREATE TABLE person (
    id INTEGER NOT NULL PRIMARY KEY,
    name VARCHAR(100) NOT NULL
);

CREATE TABLE address (
    id INTEGER NOT NULL PRIMARY KEY,
    address VARCHAR(100) NOT NULL,
    city VARCHAR(100) NOT NULL,
    person_id INTEGER NOT NULL
);

I would like to map these tables to JPA entities, but I wouldn't like to map a bidirectional relationship between them using mappedBy.

What's the proper way to map a OneToMany unidirectional relationship between Person and Address? Considering that the Person must know their Addresses, but the Address must not know the Person it belongs to.

解决方案

You don't need to make it bidirectional. You can simply place the @OneToMany annotation on you collection-typed field in Person and specify the JoinColumn of the address table.

See here, Example 3. I think that's what you're looking for.

So you will have something like:

// In Person class:

@OneToMany
@JoinColumn(name="person_id")
public Set<Address> getAddresses() {return addresses;}

No mappedBy attribute, no bidirectional mapping.

这篇关于映射一对多单向关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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