spring存储库EntityGraph JoinFormula即使在我不想要的时候也会加载

时间:2018-04-27 07:57:36

标签: spring hibernate repository lazy-loading entitygraph

我有3个实体,Mouvement链接Agent和Poste。我不能直接加入poste和agent,因为它取决于移动的日期。

@NamedEntityGraph(name = "graph.Agent.poste",
        attributeNodes = @NamedAttributeNode(value = "poste"))
@Entity
@Table(name = "agent")
public class Agent extends RestaurableEntity<Long>  {
    //fields firstname lastname birthdate...
     @ManyToOne(fetch = FetchType.LAZY)
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @JoinFormula("(" +
            "SELECT TOP 1 CASE WHEN (tm.arrivee=1 ) THEN m.id_poste ELSE (NULL) END " +
            "FROM mouvement m, type_mouvement tm " +
            "WHERE m.id_agent = id " +
            "AND m.id_type_mouvement=tm.id "+
            "AND m.supprime=0 "+
            "AND m.date<=GETDATE() "+
            "ORDER BY m.date DESC " +
            ")")
    private Poste poste;

}
@Entity
@Table(name = "poste")
@NamedEntityGraph(name = "graph.Poste.agent",
        attributeNodes = @NamedAttributeNode(value = "agent", subgraph = "agent"))
public class Poste extends RestaurableEntity<Integer> {
     @ManyToOne(fetch = FetchType.LAZY)
    @JoinFormula("(" +
            "SELECT TOP 1 CASE WHEN (tm.arrivee=1) THEN m.id_agent ELSE (NULL) END " +
            "FROM mouvement m, type_mouvement tm " +
            "WHERE m.id_poste = id " +
            "AND m.id_type_mouvement=tm.id " +
            "AND m.supprime=0 " +
            "AND m.date<=GETDATE() " +
            "ORDER BY m.date DESC " +

            ")")

    private Agent agent;
}
@Entity
@Table(name = "mouvement")
public class Mouvement extends RestaurableEntity<Long> {

    @Column(name = "date", nullable = false)
    private Date date;

    @ManyToOne
    @JoinColumn(name = "id_agent")
    private Agent agent;

    @ManyToOne
    @JoinColumn(name = "id_poste", nullable = false)
    private Poste poste;
}
@Transactional
public interface AgentRepository extends JpaRepository<Agent, Long> {
  @EntityGraph(value="graph.Agent.poste",type = EntityGraph.EntityGraphType.LOAD)
    @Query("select a from Agent a")
    List<Agent> findAllWithPoste();
}

我的问题是,当我调用findAllWithPoste()时,我用他们的poste检索代理列表,但我也在poste中找到了我不想加载的代理以节省时间。有没有人知道如何加载poste而不在poste中加载代理?

PS:我已经尝试将我的JoinFormula转换为存储库方法但它没有用。

 @Query("select new Agent(a,( select limit 1 p from Mouvement m, Poste p where m.agent.id=a.id and m.id_poste=p.id and m.date<= current_date() order by m.date desc) )  from Agent a")
    List<Agent> findAllWithPoste();

0 个答案:

没有答案