TastyCode
TastyCode

Reputation: 5799

Spring CrudRepository findOne(id) method throwing org.hibernate.LazyInitializationException: could not initialize proxy - no Session

I have an Employee entity where i am able to retrieve description and name correctly but its failing when it tries to retrieve a collection. I have set fetch type as eager.

I have following code in my controller:

Employee emp = employeeRepository.findOne(id);
emp.getName()
emp.getDescription();
emp.getProjects() // throws exception on this line

Here is my Employee entity

@Entity
public class Employee {

....

    /** The name. */
    @NotNull
    @Size(max = 30)
    private String name;

    /** The description. */
    @NotNull
    @Size(max = 250)
    private String description;

....

    @ElementCollection
    @CollectionTable(name = "Projects", joinColumns = @JoinColumn(name = "emp_ID"))
    @Basic(fetch = FetchType.EAGER)
    private Set<Project> projects = new HashSet<Project>();

I am not sure why the session ceases to exist.

Upvotes: 2

Views: 1359

Answers (1)

Rafa
Rafa

Reputation: 2027

As far as I know, ElementCollection only works for basic types.

The documentation says:

In some situations you don't need to associate two entities but simply create a collection of basic types or embeddable objects. Use the @ElementCollection for this case.

In this case you need to use a traditional OneToMany relationship. Here is a good tutorial: http://viralpatel.net/blogs/hibernate-one-to-one-mapping-tutorial-using-annotation/

Upvotes: 1

Related Questions