Parent class:
Code:
@Entity
public class TestParent implements Serializable {
@Id @GeneratedValue
private Long id;
@OneToMany(mappedBy="parent", targetEntity=TestChild.class)
@LazyCollection(LazyCollectionOption.EXTRA)
private List<TestChild> children = new ArrayList<TestChild>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public List<TestChild> getChildren() {
return children;
}
public void setChildren(List<TestChild> children) {
this.children = children;
}
}
Child class:
Code:
@Entity
public class TestChild implements Serializable {
@Id @GeneratedValue
private Long id;
@ManyToOne(targetEntity=TestParent.class)
private TestParent parent;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public TestParent getParent() {
return parent;
}
public void setParent(TestParent parent) {
this.parent = parent;
}
}
The schema:
Code:
CREATE MEMORY TABLE TESTPARENT(
ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 1) NOT NULL PRIMARY KEY
)
CREATE MEMORY TABLE TESTCHILD(
ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 1) NOT NULL PRIMARY KEY,
PARENT_ID BIGINT
)
ALTER TABLE TESTCHILD ADD CONSTRAINT FK2F8AEB8A499EB72D FOREIGN KEY(PARENT_ID) REFERENCES TESTPARENT(ID)
The data:
Code:
INSERT INTO TESTPARENT VALUES(1)
INSERT INTO TESTPARENT VALUES(2)
INSERT INTO TESTCHILD VALUES(1,1)
INSERT INTO TESTCHILD VALUES(2,1)
INSERT INTO TESTCHILD VALUES(3,1)
INSERT INTO TESTCHILD VALUES(4,1)
INSERT INTO TESTCHILD VALUES(5,1)
INSERT INTO TESTCHILD VALUES(6,1)
INSERT INTO TESTCHILD VALUES(7,1)
INSERT INTO TESTCHILD VALUES(8,1)
INSERT INTO TESTCHILD VALUES(9,1)
INSERT INTO TESTCHILD VALUES(10,1)
INSERT INTO TESTCHILD VALUES(11,2)
INSERT INTO TESTCHILD VALUES(12,2)
INSERT INTO TESTCHILD VALUES(13,2)
INSERT INTO TESTCHILD VALUES(14,2)
INSERT INTO TESTCHILD VALUES(15,2)
INSERT INTO TESTCHILD VALUES(16,2)
INSERT INTO TESTCHILD VALUES(17,2)
INSERT INTO TESTCHILD VALUES(18,2)
INSERT INTO TESTCHILD VALUES(19,2)
The code:
Code:
transaction = session.beginTransaction();
List parents = session.createQuery("from TestParent").list();
transaction.commit();
TestParent parent = (TestParent) parents.get(0);
System.out.println(parent.getChildren().size());
for (TestChild child : parent.getChildren()) {
System.out.println(child.getId());
}
Generated queries for the above code:
Code:
For getChildren().size():
select count(id) from TestChild where parent_id =?
For child.getId():
select children0_.parent_id as parent2_1_, children0_.id as id1_, children0_.id as id5_0_, children0_.parent_id as parent2_5_0_ from TestChild children0_ where children0_.parent_id=?
The last query is generated only once for the entire loop so the entire collection is loaded into memory on first child access.