I'm trying to learn Spring Roo, and I'm doing my little application. I have product class:
@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;
}
And a fact class:
@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;
}
After Sprinng Roo has done it magic, I'm starting application and I see webpage. Nice work, so little code and it's almost working.
When doing preview of products it's working fine:
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 ?
But when I'm viewing facts I have a lot of queries (basically one for each fact table row):
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=?
...
After searching I have found "N+1 selects problem" posts. Am I right – that also my problem?
I thought that @Fetch(FetchMode.JOIN)
forces hibernate to use join and not subselects.
In aspect files I've found generated query which is responsible for fetching my data:
public static List<Fact> Fact.findAllFacts() {
return entityManager().createQuery("SELECT o FROM Fact o", Fact.class).getResultList();
}
How can I force Spring Roo to use join? What I'm doing wrong?
Change FetchType.EAGER
from the ManyToOne to FetchType.LAZY
. Eager-loading is fetching the whole object graph. And I'm pretty-sure you can get rid of the @Fetch(FetchMode.JOIN)
annotation.