1

I tried with this :

@OneToOne(mappedBy = "user", fetch = FetchType.LAZY)
private UserInfo userInfo;

But the above code doesn't fetch lazily.

And also tried with the following code :

@Entity
@NamedEntityGraph(name = "User.detail", attributeNodes = {} )
public class User extends AbstractEntity {

    @Enumerated(EnumType.ORDINAL)
    @Column(name = "country", nullable = false)
    private Country country;

    @Column(name = "mobile_no", nullable = false)
    private String mobileNo;

    @Column(name = "password", nullable = false)
    private String password;

    @OneToOne(mappedBy = "user", fetch = FetchType.LAZY)
    private UserInfo userInfo;

    // Getter & setter
}

@Repository
public interface UserRepository extends JpaRepository<User, Long> {

    @EntityGraph(value = "User.detail", type = EntityGraphType.FETCH)
    User findById(Long id);
}

This too doesn't work.

Can anybody help me?

  • 3
    Does every User have a UserInfo? If so, you should mark the association as optional=false. Otherwise, Hibernate has no idea if it must set the field to null or to a proxy, and is thus force to check if a UserInfo exists for the user. – JB Nizet Aug 21 '16 at 07:40
  • 1
    http://stackoverflow.com/questions/1444227/making-a-onetoone-relation-lazy – Maciej Marczuk Aug 21 '16 at 07:47
  • @jbnizet, I tried using optional=false, but it's not working. I also tried with @LazyToOne(value = LazyToOneOption.PROXY), but still not working. – Aviskar Basnet Aug 21 '16 at 10:42

1 Answers1

1

As per JPA 2.1 (JSR 338) specification, section 11.1.41 the value FetchType.LAZY for the parameter fetch is only a hint:

Whether the association should be lazily loaded or must be eagerly fetched. The EAGER strategy is a requirement on the persistence provider runtime that the associated entity must be eagerly fetched. The LAZY strategy is a hint to the persistence provider runtime.

So if the association is eagerly fetched it does not mean that FetchType.LAZY dose not work (as specified).

A possible solution to your problem could be to remove private UserInfo userInfo; from your entity mapping and add a fetchUserInfo(Long userId) to your UserRepository.

8hZWKA
  • 363
  • 2
  • 10