JPA:在很多方面将结果连接到NULL结果 [英] JPA: Join Fetch results to NULL on empty many side

查看:123
本文介绍了JPA:在很多方面将结果连接到NULL结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在User和GameMap之间有一对多的关系。一位用户可以有多个地图。



用户类别:

  // LAZY LOADED 
@OneToMany(cascade = CascadeType.ALL,mappedBy =creater)
private final List< GameMap> maps = new ArrayList<>();

但是,有时我需要加载地图。为了避免关闭Session之后的 LazyInitializationException ,我有两种检索用户的变体。

p>

  public interface UserRepository扩展JpaRepository< User,Long> {

可选< User> findById(Long id);

@Query(SELECT u FROM User u JOIN FETCH u.maps WHERE u.id =(:id))
public User findByIdEagerFetch(@Param(id)Long id );
}

问题:

但是,JPQL JOIN FETCH变体预先加载到用户,并且如果表中没有此用户的地图,则其地图将返回NULL用户



问题:

如何重写JPQL语句以检索用户和(可选)(!)所有地图,但如果没有地图,

解决方案

  @Query(SELECT u FROM User u LEFT JOIN FETCH u.maps WHERE u.id =(:id))
public User findByIdEagerFetch(@Param(id)Long id);


I have a one to many relationship between User and GameMap. One user can have many maps.

User class:

// LAZY LOADED
@OneToMany(cascade = CascadeType.ALL, mappedBy = "creater")
private final List<GameMap> maps = new ArrayList<>();

However, sometimes I need to eager load the maps. To avoid the LazyInitializationException after closing Session, I have two variants of retrieving Users.

User Repository:

public interface UserRepository extends JpaRepository<User, Long> {

    Optional<User> findById( Long id );

    @Query("SELECT u FROM User u JOIN FETCH u.maps WHERE u.id = (:id)")
    public User findByIdEagerFetch( @Param("id") Long id );
}

Problem:
However, the JPQL JOIN FETCH variant to eager load in one go the user and his maps returns a NULL user if there are no maps for this user in the table.

Question:
How can I rewrite the JPQL statement in order to retrieve the user and optionally(!) all his maps but if there are no maps, than thats okay, but dont return a NULL user.

解决方案

@Query("SELECT u FROM User u LEFT JOIN FETCH u.maps WHERE u.id = (:id)")
public User findByIdEagerFetch( @Param("id") Long id );

这篇关于JPA:在很多方面将结果连接到NULL结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆