Hibernate-仅连接单列而不是整个实体 [英] Hibernate - Join only single column instead of whole entity

查看:72
本文介绍了Hibernate-仅连接单列而不是整个实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,我只需要另一个映射实体的一列即可.我宁愿没有完整的参考.有没有办法做到这一点?我已经详尽搜索过Google,但是我一定没有正确的术语.

I have a class and I need just a single column from another mapped entity. I would prefer to void having a full reference. Is there a way to do this? I've exhaustively googled but I must not have the terminology right.

解释:

@Entity
@Table(name = "foo")
@Data
public class Foo {
    @Id
    @Column(name = "itemid")
    private long id;

    @Column(name = "name")
    private String name;
}

这有效:

@Entity
@Table(name = "bar")
@Data
public class Bar{
    @Id
    @Column(name = "itemid")
    private long id;

    @Column(name = "other_name")
    private String otherName;

    @OneToOne
    @PrimaryKeyJoinColumn
    private Foo foo;
}

但我想要

@Entity
@Table(name = "bar")
@Data
public class Bar{
    @Id
    @Column(name = "itemid")
    private long id;

    @Column(name = "other_name")
    private String otherName;

    @OneToOne
    @JoinColumn(name = "itemid")
    @Formula("SELECT name FROM FOO v where v.id = id")
    // Something here...not sure what. Where name is the name from Foo
    private String name;
}

推荐答案

您有两种选择.

第一个是,正如您所暗示的,使用@Formula-仅使用@Formula,而无需在其上具有其他注释.这应该完全符合您的期望.

The first is to, as you allude to, use @Formula - without the other annotations you have on there, just using @Formula. This should do exactly what you expect.

或者,如果您发现自己经常需要此视图,则可以创建一个将两列连接在一起的视图,并使对象基于该视图而不是原始表.

Alternatively, if you find yourself needing this often, you could make a view which joins the two columns and have your object based off that view instead of the original tables.

这篇关于Hibernate-仅连接单列而不是整个实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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