hibernate可选连接 [英] hibernate optional join

查看:138
本文介绍了hibernate可选连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  @Entity $ b $我有一个映射到One-To-One的实体b @Table(name =my_entity)
public class MyEntity
{
...
@OneToOne
@JoinColumn(name =site_id)
私人网站网站;
...
}

我刚才被告知我必须开始存储可能不存在于Site表中的'site_id'值的MyEntity条目。我仍然需要存储'site_id'的值,但它不会匹配Site实体。



我唯一能想到的是创建第二种类型的实体映射到不映射站点表上的One-To-One / join的同一个表。



有没有办法在不创建第二个映射的情况下执行此操作对象为同一张表吗?



谢谢,paul。

这是非常糟糕的设计。外键应该是外键,不应该指向不存在的行。我会修正数据/设计。



如果你真的不行,可以使用 here


默认情况下,当Hibernate无法解析关联,因为期望的关联元素不在数据库中(关联列中的id错误),Hibernate会引发异常。这可能不便于传统和维护不当的模式。您可以让Hibernate忽略这些元素,而不是使用@NotFound注释引发异常。此批注可用于@OneToOne(带FK),@ManyToOne,@OneToMany或@ManyToMany关联。



I have an entity mapped with a One-To-One as per the following code:

@Entity
@Table(name = "my_entity")
public class MyEntity
{
    ...
    @OneToOne
    @JoinColumn(name = "site_id")
    private Site site;
    ...
}

I've just been told that I must start storing MyEntity entries with a value for 'site_id' which may not exist within the Site table. I still need to store the value for 'site_id' however it will not match a Site entity.

The only thing I can think of is to create a 2nd type of Entity mapped to the same table that doesn't map a One-To-One/join on the site table.

Is there a way to do this without creating a 2nd mapped object for the same table?

thanks, paul.

解决方案

This is very bad design. A foreign key should be a foreign key, and should not point to non-existing rows. I would fix the data/design.

If you really really can't, use the NotFound annotation described here :

By default, when Hibernate cannot resolve the association because the expected associated element is not in database (wrong id on the association column), an exception is raised by Hibernate. This might be inconvenient for legacy and badly maintained schemas. You can ask Hibernate to ignore such elements instead of raising an exception using the @NotFound annotation. This annotation can be used on a @OneToOne (with FK), @ManyToOne, @OneToMany or @ManyToMany association.

这篇关于hibernate可选连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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