Spring Roo会产生大量查询

时间:2012-01-18 19:04:55

标签: java hibernate spring-mvc spring-roo many-to-one

我正在努力学习Spring Roo,而我正在做我的小应用程序。 我有产品类:

@RooJavaBean
@RooToString
@RooEntity(table = "TOWARY")
public class Product {
    @Id
    @GeneratedValue
    @Column(name = "ID")
    private int id;

    @Column(name = "NAZWA")
    private String name;

    @Version
    @Column(name = "VERSION")
    private int version;
}

一个事实类:

@RooJavaBean
@RooToString
@RooEntity(table = "FACTS")
public class Fact {
    @Id
    @GeneratedValue
    @Column(name = "ID")
    private int id;

    @Column(name = "KWOTA")
    private float kwota;

    @Column(name = "NCZAS")
    private int nczas;

    @Version
    @Column(name = "VERSION")
    private int version;

    @NotNull
    @ManyToOne(fetch=FetchType.EAGER)
    @Fetch(FetchMode.JOIN)
    @JoinColumn(name="ID_TOWAR")
    private Product product;
}

在Sprinng Roo完成魔术之后,我开始申请并看到网页。干得好,代码很少,而且几乎可以正常工作。
在预览产品时,它运行良好:

Hibernate: select product0_.ID as ID0_, product0_.NAZWA as NAZWA0_, product0_.VERSION as VERSION0_ from TOWARY product0_
Hibernate: select product0_.ID as ID0_, product0_.NAZWA as NAZWA0_, product0_.VERSION as VERSION0_ from TOWARY product0_ limit ?
Hibernate: select count(product0_.ID) as col_0_0_ from TOWARY product0_ limit ?

但是当我查看事实时,我有很多疑问(基本上每个事实表行一个):

Hibernate: select fact0_.ID as ID1_, fact0_.KWOTA as KWOTA1_, fact0_.NCZAS as NCZAS1_, fact0_.ID_TOWAR as ID5_1_, fact0_.VERSION as VERSION1_ from FACTS fact0_
Hibernate: select product0_.ID as ID0_0_, product0_.NAZWA as NAZWA0_0_, product0_.VERSION as VERSION0_0_ from TOWARY product0_ where product0_.ID=?
Hibernate: select product0_.ID as ID0_0_, product0_.NAZWA as NAZWA0_0_, product0_.VERSION as VERSION0_0_ from TOWARY product0_ where product0_.ID=?
Hibernate: select product0_.ID as ID0_0_, product0_.NAZWA as NAZWA0_0_, product0_.VERSION as VERSION0_0_ from TOWARY product0_ where product0_.ID=?
...

搜索后我发现“N + 1选择问题”帖子。我是对的 - 那也是我的问题?
我认为@Fetch(FetchMode.JOIN)强制hibernate使用join而不是subselects。

在方面文件中,我发现生成的查询负责获取我的数据:

public static List<Fact> Fact.findAllFacts() {
    return entityManager().createQuery("SELECT o FROM Fact o", Fact.class).getResultList();
}

如何强制Spring Roo使用join?我做错了什么?

1 个答案:

答案 0 :(得分:0)

FetchType.EAGER从ManyToOne更改为FetchType.LAZY。渴望加载是获取整个对象图。而且我很确定你可以摆脱@Fetch(FetchMode.JOIN)注释。