在使用Hibernate进行延迟加载的情况下,如何直接获取外键id而不是整个实体?

时间:2014-07-02 08:20:05

标签: java hibernate jpa

我的实体如下: -

@Entity
@Table(name = "state")
@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "@id")
public class State implements java.io.Serializable {

private Integer id;
private Country Country;
private String name;

@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
    return this.id;
}

public void setId(Integer id) {
    this.id = id;
}

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "country", nullable = false)
@JsonManagedReference(value="country-state")
public Country getCountry() {
    return this.country;
}

public void setCountry(Country country) {
    this.country = country;
 }

}

在此实体而不是整个国家/地区,我想获取外键ID值...

直接访问外键(id),Hibernate中有没有选项?

2 个答案:

答案 0 :(得分:1)

您还可以添加(取决于您的id列名称):

@Column(name = "COUNTRY_ID")
private Long countryId;

答案 1 :(得分:0)

解决方法是向您的实体添加虚拟属性并将其设置为insertable = false, updatable = false

String countryKey;

@Column(name = "country",  insertable = false, updatable = false)
public String getCountryKey() {
    return this.countryKey;
}