user3796703
user3796703

Reputation: 189

How can i fetch foreign key id directly instead of entire entity in case of lazy loading using Hibernate?

My Entity is as follows:-

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

}

In this entity instead of Entire country just i want to fetch foreign key id value...

For accessing foreign key (id) directly, is there any option in Hibernate?

Upvotes: 1

Views: 1104

Answers (2)

Quincy
Quincy

Reputation: 4433

A workaround is to add a dummy property to your entity and set it as insertable = false, updatable = false.

String countryKey;

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

Upvotes: 0

Tõnis Ojandu
Tõnis Ojandu

Reputation: 3746

You can also add (depending on you id column name):

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

Upvotes: 1

Related Questions