Video in progress

Strong Middle 🐻 Hibernate and JPA

Why is `@OneToOne(mappedBy, fetch = LAZY)` loaded like EAGER anyway, and what are the fixes?

The inverse (mappedBy) side has no FK, so Hibernate doesn't know whether the related row exists, and to choose between a proxy and null it has to run a SELECT. The fixes are a shared primary key with @MapsId, making the association unidirectional, or bytecode enhancement.

📖 Answer

@Entity
class User {
    @OneToOne(mappedBy = "user", fetch = FetchType.LAZY)
    private UserProfile profile;
}

@Entity
class UserProfile {
    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id")
    private User user;
}

On the UserProfile side everything is fine: there's a user_id column, and it's null if null, a proxy otherwise. On the User side, though, the user table has no column at all. If a proxy were returned, getProfile() != null would lie for a user who has no profile. That's why Hibernate ignores LAZY and sends the query right away. A list of 100 users means 100 extra SELECTs.

I usually use @MapsId:

@Entity
class UserProfile {
    @Id
    private Long id;          // same as user.id

    @OneToOne(fetch = FetchType.LAZY)
    @MapsId
    private User user;
}

Now the profile is found by the User's id, and you can drop the inverse association from User entirely: when needed, em.find(UserProfile.class, userId). You don't need an extra unique index either, because the PK is unique by itself.

Other options: if you need the inverse side, bytecode enhancement (enableLazyInitialization) makes it truly lazy, but a plugin gets added to the build. Or merge the data into a single table: often you didn't need two tables at all.