JPA:如何避免生成多个“从中选择”查询

时间:2018-04-20 06:23:44

标签: java jpa jpql

这不是经典的N + 1问题。我的问题是在Jpa中使用投影和DTO对象。

我有JPA Query的下一个方法:

public List<MeterDTO> getAllBrokenMeterByHouseServ(House house, Serv serv, Date dt) {
    Query query =em.createQuery("select new MeterDTO(m, g.kart.lsk, nvl(e.tp,0)) from Meter m "
        + "join m.exs e with m.id=e.meter.id "
        + "join m.meterLog g with m.meterLog.id=g.id "
        + "join g.kart k with g.kart.id=k.id and :dt between k.dt1 and k.dt2 " 
        + "join g.serv s with g.serv.id=s.id "
        + "join k.kw kw with k.kw.id=kw.id "
        + "join kw.house h with kw.house.id=h.id "
        + "where s.id = :servId "
        + "and kw.house.id = :houseId "
        + "and :dt between e.dt1 and e.dt2 and nvl(e.tp,0) in (2,3,4) "
        + "");
    query.setParameter("servId", serv.getId());
    query.setParameter("houseId", house.getId());
    query.setParameter("dt", dt);
    return query.getResultList();
}

我从上面的查询中获取记录到 数据传输对象:

    meterDao.getAllBrokenMeterByHouseServ(house, serv, dt2).stream().forEach(t-> {
        log.info("meter.id={}, lsk={}, tp={} ", t.getMeter().getId(), t.getLsk(), t.getTp());
    });

MeterDTO:

@Getter @Setter
public class MeterDTO {

    private Meter meter;
    private Integer lsk;
    private Double tp;

    public MeterDTO(Meter meter, Integer lsk, Double tp) {
        super();
        this.meter = meter;
        this.lsk = lsk;
        this.tp = tp;
    }
}

为什么hibernate会产生一个主要查询:

select
    meter0_.ID as col_0_0_,
    kart3_.lsk as col_1_0_,
    nvl(exs1_.TP,
    0) as col_2_0_ 
from
    MT.METER meter0_ 
inner join
    MT.METER_EXS exs1_ 
        on meter0_.ID=exs1_.FK_METER 
        and (
            meter0_.ID=exs1_.FK_METER
        ) 
inner join
    MT.METER_LOG meterlog2_ 
        on meter0_.FK_METER_LOG=meterlog2_.ID 
        and (
            meter0_.FK_METER_LOG=meterlog2_.ID
        ) 
inner join
    AR.KART kart3_ 
        on meterlog2_.FK_KLSK_OBJ=kart3_.FK_KLSK_OBJ 
        and (
            kart3_.lsk=kart3_.lsk 
            and (
                ? between kart3_.DT1 and kart3_.DT2
            )
        ) 
inner join
    AR.KW kw6_ 
        on kart3_.FK_KW=kw6_.ID 
        and (
            kart3_.FK_KW=kw6_.ID
        ) 
inner join
    AR.HOUSE house7_ 
        on kw6_.FK_HOUSE=house7_.ID 
        and (
            kw6_.FK_HOUSE=house7_.ID
        ) 
inner join
    TR.SERV serv5_ 
        on meterlog2_.FK_SERV=serv5_.ID 
        and (
            meterlog2_.FK_SERV=serv5_.ID
        ) 
where
    serv5_.ID=? 
    and kw6_.FK_HOUSE=? 
    and (
        ? between exs1_.DT1 and exs1_.DT2
    ) 
    and (
        nvl(exs1_.TP, 0) in (
            2 , 3 , 4
        )
    )

和具有不同绑定参数的多个查询“?”加载每个实体:

select
    meter0_.ID as ID1_44_0_,
    meter0_.FK_K_LSK as FK_K_LSK2_44_0_,
    meter0_.FK_METER_LOG as FK_METER_LOG4_44_0_,
    meter0_.TRANS_RATIO as TRANS_RATIO3_44_0_ 
from
    MT.METER meter0_ 
where
    meter0_.ID=?

如何避免此问题?我想在一个主查询中加载所有实体Meter。 有可能吗?

我用:

<spring-framework.version>5.0.5.RELEASE</spring-framework.version>
<hibernate.version>5.1.0.Final</hibernate.version>

非常感谢任何帮助。

upd1

我将我的JPA查询代码简化为:

    public List<MeterDTO> getAllBrokenMeterByHouseServ(House house, Serv serv, Date dt) {
        Query query =em.createQuery("select new com.ric.bill.dto.MeterDTO(m) from Meter m ");
}

但它仍会产生多个查询:

    select
        meter0_.ID as ID1_44_0_,
        meter0_.FK_K_LSK as FK_K_LSK2_44_0_,
        meter0_.FK_METER_LOG as FK_METER_LOG4_44_0_,
        meter0_.TRANS_RATIO as TRANS_RATIO3_44_0_ 
    from
        MT.METER meter0_ 
    where
        meter0_.ID=?
20-04-2018 12:52:49.482 [main] DEBUG o.h.l.p.e.p.i.ResultSetProcessorImpl - Starting ResultSet row #0
20-04-2018 12:52:49.482 [main] DEBUG org.hibernate.SQL - 
    select
        meter0_.ID as ID1_44_0_,
        meter0_.FK_K_LSK as FK_K_LSK2_44_0_,
        meter0_.FK_METER_LOG as FK_METER_LOG4_44_0_,
        meter0_.TRANS_RATIO as TRANS_RATIO3_44_0_ 
    from
        MT.METER meter0_ 
    where
        meter0_.ID=?
<Skipped>
很奇怪!

upd2 Meter实体:

@SuppressWarnings("serial")
@Entity
@Table(name = "METER", schema="MT")
@Getter @Setter
public class Meter extends Base implements java.io.Serializable, Storable {

    public Meter (){

    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "ID", updatable = false, nullable = false)
    protected Integer id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="FK_METER_LOG", referencedColumnName="ID")
    private MeterLog meterLog ; 

    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval=true)
    @JoinColumn(name="FK_METER", referencedColumnName="ID")
    @BatchSize(size = 50)
    private List<Vol> vol = new ArrayList<Vol>(0);

    @OneToMany(fetch = FetchType.LAZY)
    @JoinColumn(name="FK_METER", referencedColumnName="ID")
    @BatchSize(size = 50)
    private List<MeterExs> exs = new ArrayList<MeterExs>(0);

    @Column(name = "TRANS_RATIO", updatable = true, nullable = true)
    private Double trRatio; 

}

2 个答案:

答案 0 :(得分:1)

在DTO中,您有“仪表”和“仪表”。字段,在米字段中你有&#39; MeterLog仪表日志&#39;在这种情况下,Hibernate还为整个对象加载字段。这个DTO要复杂得多。尝试创建更多扁平对象:

var fs = require('fs');
var x =   
{
    "members": {
        "Thing": {
            "someValue": "1",
            "anotherValue": "2"
        },
        "secondThing":{
            "secondValue":"3",
            "anotherSecondVal":"4"
        }
    }
}


fs.writeFile('members.json', JSON.stringify(x), 'utf8', (err,data)=>{
    //callback
});

fs.readFile('members.json','utf8',(err,data)=>{
    if(data){
        console.log(JSON.parse(data))
    } else{
        console.log(err)
    }
})

查询将是:

public class MeterDTO {

    private Integer meterId
    private Double meterTrRatio
    private Integer lsk;
    private Double tp;
    (...)

之后,您可以将DTO扩展到您想要的下一个字段。

答案 1 :(得分:0)

接受的答案建议更改 DTO,这并不总是可接受的解决方案。

这是一个无需更改 DTO 的解决方案。

像这样编写您的 HQL:

from Meter m 
join m.exs e with m.id=e.meter.id 
join m.meterLog g with m.meterLog.id=g.id 
join g.kart k with g.kart.id=k.id and :dt between k.dt1 and k.dt2 " 
join g.serv s with g.serv.id=s.id "
join k.kw kw with k.kw.id=kw.id "
join kw.house h with kw.house.id=h.id "
(more joins and wheres)

请注意,不应有任何 select

getResultList 会给你 List<Object[]>。每个条目都是一个 {Meter, m.exs, m.meterLog, g.kart, ....} 数组。选择您需要的并制作您的 MeterDTO

就我而言:

jpa 仓库

    @Query("from Bind bind "
        + "left join Employee employee "
        + "with bind.empCode = employee.empCode "
        + "where bind.accountName = :hiveAccount and bind.disabled = 1 ")
    List<Object[]> listMembers(@Param("hiveAccount") String hiveAccount);

DTO

public class BindDTO {
    Bind bind;
    Employee emp;

    public BindDTO(Object[] objs) {
        this((Bind) objs[0], (Employee) objs[1]);
    }

服务

myRepo.listMembers(hiveAccount).stream().map(BindDTO::new).collect(Collectors.toList());