Java.Hibernate.Middle.How do you configure fetch type for an association?

You configure the fetch type for an association directly on your entity mapping using the fetch attribute of @OneToOne, @OneToMany, @ManyToOne, or @ManyToMany. Here’s how:

✅ For @OneToOne and @ManyToOne

By default, these are EAGER, but you can override:

@Entity
public class Order {
    @ManyToOne(fetch = FetchType.LAZY) // Explicitly set LAZY
    private Customer customer;
}

✅ For @OneToMany and @ManyToMany

By default, these are LAZY, but you can override:

@Entity
public class Customer {
    @OneToMany(mappedBy = "customer", fetch = FetchType.EAGER) // Explicitly set EAGER
    private List<Order> orders;
}

📌 Syntax summary:

@OneToOne(fetch = FetchType.LAZY)
@ManyToOne(fetch = FetchType.LAZY)
@OneToMany(fetch = FetchType.EAGER)
@ManyToMany(fetch = FetchType.LAZY)

🚨 Important notes:

  • EAGER means the associated entity or collection is always loaded immediately with the parent entity.
  • LAZY means the association is fetched only when you access it (via proxy initialization).
  • Hibernate best practice: keep associations LAZY by default and use JOIN FETCH or EntityGraph for specific queries needing eager loading → this avoids unexpected performance problems like N+1 or massive joins.

🔥 Example with both types:

@Entity
public class Author {
    @OneToMany(mappedBy = "author", fetch = FetchType.LAZY) // collection, defaults to LAZY
    private List<Book> books;

    @OneToOne(fetch = FetchType.EAGER) // single association, defaults to EAGER
    private Biography biography;
}
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.