0

I have a JPA entity Rent that has 1:M relationship with the items that are rented (called "Rentable"). I want that this rentables be lazily loaded, but it seems that they are always loaded, even when I use fetch = FetchType.LAZY. Here is my code:

@Entity
@Table (name = "rent")
public class Rent implements Serializable{

    ........

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinTable(name = "rent_rentable")
    private List <Rentable> rentables = new ArrayList <Rentable> ();

Here is how I load the rents:

 from Rent r  where r.kunde.id = 83

but I also get the associated rentables too. Rent with its rentables loaded

Could somebody help me, please? I want the rentables to be lazily loaded!

Thank you!

Alex Mi
  • 1,409
  • 2
  • 21
  • 35
  • 4
    Can't say for sure, but it's possible that they're loaded because you inspect the values in the debugger. It's a bit like [the cat in that box](https://en.wikipedia.org/wiki/Schr%C3%B6dinger%27s_cat). Turn on query logging and check at what point the query is executed. – Robby Cornelissen Jan 25 '18 at 06:00
  • @RobbyCornelissen thank you, will check it – Alex Mi Jan 25 '18 at 06:05
  • Not to mention one-to-many is lazy by default, so it's not likely to be related to configuration. – Kayaman Jan 25 '18 at 07:05

1 Answers1

4

When you inspect the collection in the debugger your ORM framework (Hibernate) is forced to lazily load it from the database.

You need to turn on SQL logging and you will see that your Rentables are only loaded when you either inspect it in the debugger or you call getRentables() on a Rent instance.

saw303
  • 8,051
  • 7
  • 50
  • 90