hibernate optional join

我只是一个虾纸丫 提交于 2019-12-23 02:31:04

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/5231579/hibernate-optional-join

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!