failed to lazily initialize a collection of role for a Map<Integer,String>

Viewed 162

I have the follwoing entity

@Entity
@Table(name = "Parent")
public class Parent  {

@ElementCollecion(fetch = FetchType.Eager)
Map<Integer,String> myMap;

public Map<Integer,String> getMyMap() {
return this.myMap;
 }
}

Then somewhere in the code I have the follwoing

parent.getMyMap().get(someKey);

This line consistently throws a LazyInitialization exception. I have set the fetchType to eagerly load the collection so that the values are available at all times. What have I missed> Is it because of the access of the getMap.GetKey call?

I dont see any more information in the debug logs or anywhere else.

1 Answers

Generally the @ElementCollection is accompanied with a @CollectionTable along with @MapKeyColumn & @Column annotation to provide the table and values to load the content for the map.

@Entity
@Table(name = "Parent")
public class Parent {

    @ElementCollection(fetch = FetchType.Eager)
    @CollectionTable(name="example_attributes", joinColumns=@JoinColumn(name="example_id"))    
    @MapKeyColumn(name="name")
    @Column(name="value")
    Map<Integer,String> myMap;

    public Map<Integer,String> getMyMap() {
        return this.myMap;
    }
}
Related