2

I am using Hibernate in my java project. I am having following entity structure:

@Entity
@Table(name = "car")
public class Car implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private long id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "engine_id", nullable = false)
    private Engine engine;
}

Now when I load Car entity from db, obviously Engine entity won't be loaded as it is lazy loaded field, but the id (primary key) for the Engine will be loaded.

Now if I do car.getEngine().getId(), then it is throwing LazyInitialization Exception. As Id part is already loaded, then why getId() is throwing exception?

Arjit
  • 147
  • 1
  • 2
  • 9
  • Please post the exception if you get one... Also, probably http://stackoverflow.com/questions/9250414/hibernate-getid-is-loading-the-object-even-though-it-is-lazy explains your problem (if you have your fields annotated in your Engine class too) – MikeN Mar 28 '13 at 10:47

1 Answers1

0

when I load Car entity from db

Are you absolutely sure this object is fully loaded?

If it's lazy loaded, Engine id as well as other attributes aren't loaded yet hence the exception. I would suggest you to play with Hibernate.initialize(obj) at every level to see where exactly the failure is.

mindas
  • 26,463
  • 15
  • 97
  • 154