1

I use Hibernate 4.2. I have two tables say Employee and Employer. I have employer_id in employee table as foreign key.

Now in Employee.java file can I have

@Column(name="employer_id") 
private Integer employerId;

I don't want to have a Employer reference in Employee as I don't want to fetch Employer data every time I fetch employee.

Also please let me know is there a way I can have Employer reference and make Hibernate not to fetch it unless an request is made say getEmployer();

1 Answer 1

4

You can do it using lazy loading put following annotation:

private Employer employer;
.
.
.

@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="employer_id")
public Employer getEmployer() {
   return this.employer;
}

And employer will be loaded only when you call getEmployer()

Sign up to request clarification or add additional context in comments.

3 Comments

Hi...I have other fields in Employee as well....And is being frequently fetched from database. In lazy whenever it also fetches the information form employer when I fetch some other employee. The employer_id in my case is not much used and being used in only very few scenarios. Hence I think to use lazy will also won't serve mine actual purpose of not having to fetch employer data from db.
I didn't get exactly what you meant! This won't fetch data unless you call the getter method. If you call getter you need it though!
Thanks for response. Just a doubt...It won't fetch employer details, if I fetch some other details from employee say employee.getDepartmentDetails();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.