从@ManyToOne关系中仅获取一列

时间:2019-01-29 17:09:52

标签: java jpa

我正尝试缩小我的实体之一,因为它不需要加载整个相关对象。我要实现的目标不是加载映射为@ManyToOne关系的整个实体,而是仅加载其字段之一。假设我们有以下两个实体(来自样本的实体组成):

@Entity
public class Session {
    @Id
    private Long id;
    private String someField;
    @ManyToOne
    @JoinColumn(name = "sessionId", referencedColumnName = "id")
    private User user;
}

@Entity
public class User {
    @Id
    private Long id;
    private String username;
    private String address;
    private LocalDateTime lastLogin;
}

我想以较小的Session实体结束,就像:

@Entity
public class Session {
    @Id
    private Long id;
    private String someField;
    @ManyToOne
    @JoinColumn(name = "sessionId", referencedColumnName = "id")
    private LocalDateTime lastLogin; // lastLogin value from User Entity
}

我试图通过混入@Column注释来实现这一点,但是忘记了@ManyToOne不允许这样做。我在考虑可以通过@ElementCollection完成的事情:

    @ElementCollection(fetch = FetchType.EAGER)
    @CollectionTable(name = "OTHER_TABLE")
    @Column(name = "someFieldFromOtherTable")
    private Set<String> someFieldFromOtherTableValues;

是否有可能仅从反射实体中获取一列?

1 个答案:

答案 0 :(得分:1)

这就是我代码中的内容。试试吧:

@Entity
@Table(name = "t_address")
@SecondaryTables({
    @SecondaryTable(name="t_city"),
    @SecondaryTable(name="t_country")
})
public class FirstTable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String street1;
    private String street2;

    @Column(table="t_city")
    private String city;
    @Column(table="t_city")
    private String state;
    @Column(table="t_city")
    private String zipcode;

    @Column(table="t_country")
    private String country;
}