2

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.

Explained:

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

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

This works:

@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;
}

But I want:

@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;
}
Rig
  • 1,276
  • 3
  • 22
  • 43
  • Did you try that last snippet, just without the `@OneToOne` and `@JoinColumn`? Just the `@Formula`? – corsiKa Oct 17 '17 at 21:10

2 Answers2

1

You have a couple options.

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.

corsiKa
  • 81,495
  • 25
  • 153
  • 204
  • So, I've dropped OneToOne and JoinColumn leaving just the Formula and I get "could not extract ResultSet; SQL [n/a]". I need the "where" part of this but I'm not sure if that is correct. – Rig Oct 18 '17 at 14:56
0

I believe you should not do that. Your entity class should describe only how data are stored. You are adding some logic where it is not supposed to be.

Also consider what happens when you do not store foreign key to the other table. If the entity is changed you do not get the update.

prosteja
  • 21
  • 1
  • 4