Lazy loading method, immediate loading method

Occurs when using hibernate to get multi-party information from one party:

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.haowei.carmanager.model。。。。
  • 1

Searching from the Internet is roughly related to the way hibernate loads associated objects, one is lazy loading, and the other is immediate loading.
The original configuration was:

Many of one party:

@OneToMany(mappedBy = "carFirm",cascade = CascadeType.ALL,fetch = FetchType.LAZY)
    private Set<CarBrandType> brandTypeSet;    //汽车厂商与汽车品牌为一对多的关系
  • 1
  • 2

One of the parties:

@ManyToOne(cascade = CascadeType.ALL,optional = false)
    @JoinColumn(name="brandid",referencedColumnName = "carfirm_id")
    private CarFirm carFirm;             //汽车厂商与汽车品牌为一对多的关系
  • 1
  • 2
  • 3

Note that the configuration of one party in the multi-party does not specify the loading method, and the multi-party in one party is lazy loading, so when one party is acquired, one party is obtained, but when the multi-party is acquired again, the session has been closed, and it will not be obtained at this time. Multi-party information, so an error is reported.
Solution:
Many in one party:

@OneToMany(mappedBy = "carFirm",cascade = CascadeType.ALL,fetch = FetchType.EAGER)
    private Set<CarBrandType> brandTypeSet;    //汽车厂商与汽车品牌为一对多的关系
  • 1
  • 2

One of the parties:

@ManyToOne(cascade = CascadeType.ALL,optional = false,fetch = FetchType.LAZY)
    @JoinColumn(name="brandid",referencedColumnName = "carfirm_id")
    private CarFirm carFirm;             //汽车厂商与汽车品牌为一对多的关系
  • 1
  • 2
  • 3

That is to change the loading method of multiple parties in one party to immediate loading, and one party in the multiple parties can be changed to lazy loading. As for whether the loading method of one of the multiple parties is also related to the exception, we will not experiment here.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326517894&siteId=291194637