小编典典

Spring Data'Left Join Fetch'查询返回null

sql

我的查询如下所示:

@Query("SELECT p FROM Pilot p LEFT JOIN FETCH p.playerShips WHERE p.nickname = (:nickname)")

到目前为止,一切都很好。即使playerShips为空,我也正在获得Pilot实例。
现在,我只想获取不活动的船只,因此我将查询修改为如下所示:

@Query("SELECT p FROM Pilot p LEFT JOIN FETCH p.playerShips s WHERE p.nickname = (:nickname) AND s.active = false")

而且我作为飞行员变得空无一人,所以它显然行不通。
如果有人可以向我解释如何使用适用于子元素的WHERE子句创建JOIN FETCH查询,我将感到非常高兴。提前致谢。


阅读 215

收藏
2021-04-22

共1个答案

小编典典

经过大量研究,我决定实现一个自定义存储库,以便可以使用Hibernate Filters,现在它可以工作了。

试点存储库:

@Repository
public interface PilotRepository extends JpaRepository<Pilot, Long>, PilotRepositoryCustom{
/*spring data methods here*/
}

PilotRepositoryCustom:

public interface PilotRepositoryCustom {
    public Pilot findByNicknameFetchInactiveShips(String nickname);
}

PilotRepositoryImpl:

public class PilotRepositoryImpl implements PilotRepositoryCustom{

    @PersistenceContext
    EntityManager entityManager;

    @Override
    public Pilot findByNicknameFetchInactiveShips(String nickname) {
        Session session = entityManager.unwrap(Session.class);
        session.enableFilter("active").setParameter("active", false);
        Query query = entityManager.createQuery(
                "SELECT p FROM Pilot p " +
                "LEFT JOIN FETCH p.playerShips ps " +
                "LEFT JOIN FETCH ps.ship s " +
                "WHERE p.nickname = (:nickname)");
        query.setParameter("nickname", nickname);
        return (Pilot)query.getSingleResult();
    }
}

弹簧数据就是这样。现在,过滤器配置:

试点实体:

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "pilot")
    @Filter(name="active", condition = "active = :active")
    private List<PlayerShip> playerShips;

PlayerShip实体:

@Entity
@Table(name="player_ship")
@FilterDef(name="active", parameters=@ParamDef(name="active",type="java.lang.Boolean"))
public class PlayerShip {
    /*...*/
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "pilot_id")
    private Pilot pilot;
    /*...*/
}

重要说明:
如果在@ParamDef中使用布尔值,请确保键入 java.lang.Boolean 而不是 Boolean
。我已经花了一个多小时的时间想知道为什么我不断得到 参数未找到/未定义的错误

2021-04-22