简体   繁体   English

如何使用Spring Data从不同的表中获取额外的列?

[英]How to get additional column from different table with Spring Data?

So lets imagine following situation.所以让我们想象以下情况。 I have an entity such as this:我有一个这样的实体:

@Entity
public class Price {

    @Id
    private int id;

    @Column
    private int amount;

    private String currency;

}

And I have two tables:我有两个表:

CREATE TABLE currency (
id integer not null primary key,
name varchar
);
CREATE TABLE price (
    id integer not null primary key,
    amount integer,
    currency_id integer references currency(id)
);

I want to tell Spring that when I access Price.getCurrency() I want to have whatever is stored in column "name" of the "currency" table.我想告诉 Spring,当我访问 Price.getCurrency() 时,我想要存储在“currency”表的“name”列中的任何内容。 In other words, I want to connect two tables in one entity.换句话说,我想在一个实体中连接两个表。

I can make currency a separate class, annotate the property with @OneTo... and get it like price.getCurrency().getName().我可以使货币成为一个单独的类,用@OneTo... 注释属性,并像 price.getCurrency().getName() 一样得到它。 But I don't want a separate class, I just need this specific column.但我不想要一个单独的类,我只需要这个特定的列。

I tried adding it via @SecondaryTable annotation like this:我尝试通过 @SecondaryTable 注释添加它,如下所示:

@SecondaryTable(name = "currency",
            pkJoinColumns = @PrimaryKeyJoinColumn(name = "id", referencedColumnName = "currency_id"))

But in this case Spring connect two tables by it's ids like this:但在这种情况下,Spring 通过它的 id 连接两个表,如下所示:

SELECT * FROM price LEFT JOIN price ON price.id = currency.id

And of course it is not working.当然,它不起作用。 So how do I do this?那么我该怎么做呢? Is @SecondaryTable a correct way and if so how do I connect it through non-primary key column? @SecondaryTable 是正确的方法吗?如果是,我该如何通过非主键列连接它?

Yes, you can use @SecondaryTable :是的,您可以使用@SecondaryTable

@Entity
@Table(name = "price")
@SecondaryTable(
    name = "currency",
    pkJoinColumns = {
        @PrimaryKeyJoinColumn(name = "id", referencedColumnName = "currency_id")
    })
public class Price {

    @Id
    private int id;

    @Column
    private int amount;

    @Column(table = "currency", name = "name")
    private String currency;

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM