Hibernate/JPA中如何使用JOIN FETCH获取一个懒加载集合?

19-02-10 banq
         

默认情况下,如果使用@ElementCollection标注一个实体中的子集合,这个集合是懒加载的,不会随着这个实体加载而立即加载:

@Entity
public class ShoppingCart implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    
    // LAZY is default懒加载默认
    @ElementCollection(fetch = FetchType.LAZY)
    private List<Product> products = new ArrayList<>();

@Embeddable
public class Product implements Serializable {

    private static final long serialVersionUID = 1L;
    
    private String name;
    private int price;

当我们获取ShoppingCart这个实体时,其Product子集合是没有加载,只有访问这个集合时才会加载,但是如果需要这个子集合随着ShoppingCart加载,两个办法,去除懒加载策略;或者在Spring Boot的Repository中使用JOIN FETCH:

@Repository
public interface ShoppingCartRepository extends JpaRepository<ShoppingCart, Long> {  
    
    @Query(value = "SELECT p FROM ShoppingCart p JOIN FETCH p.products")
    ShoppingCart fetchShoppingCart();
    
    @Query(value = "SELECT p FROM ShoppingCart p JOIN FETCH p.products q WHERE q.price > ?1")
    ShoppingCart fetchShoppingCartByPrice(int price);
}

点击标题见Github源码