我正在尝试缩小我的实体之一,因为它不需要加载整个相关对象。我要实现的不是加载映射为@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;
是否有可能仅从反射实体中获取一列?
最佳答案
这就是我的代码中的内容。尝试一下:
@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;
}