0

User relates to Employee as one-to-many.
The problem is the list of Employees within PeristentSet is empty.
It's seen from debug.
And it's at least one Employee exists in DB for User.

sql:

create table users(
      id int not null primary key,
...
 constraint `emp_constr` foreign key(`empid`) references `employee`(`id`));

User bean:

@ManagedBean
@SessionScoped
public class User {
    private long id;
    private List<Employee> employees = new ArrayList<Employee>();
...

user.hbm.xml config:

<list name="employees" cascade="all" inverse="false" fetch="join">
        <key>
            <column name="userid" not-null="true"/>
        </key>
        <index column="idx"/>
    <one-to-many class="entry.Employee"/>
</list>

DAO call:

@Transactional
public List<User> getUsers() {
    return sessionFactory.getCurrentSession().createCriteria(User.class)
            .list();
}

Are there mistakes in .hbm.xml file or I should add setFetchMode() to DAO explicitly?

EDIT :

I can get one sized collection only,in real it contains more elements with such config:

<list name="employees" table="employee" lazy="false">
        <key column="userid" not-null="true"/>
    <list-index column="idx"/>
    <one-to-many class="entry.Employee"/>
</list>

that's because idx=0
if idx=7 collection size will be 8

sergionni
  • 12,462
  • 41
  • 121
  • 182

1 Answers1

1

This is a classic case of Lazy loading in hibernate.

<list name="employees" .... lazy="false" >

You need to add the lazy="false" to the list mapping. Read here for the hibernate reference.

Community
  • 1
  • 1
ManuPK
  • 10,995
  • 9
  • 54
  • 75
  • i tried this config already,it's the same,size of related collection is 0. – sergionni Mar 22 '12 at 15:39
  • ManuPK,see EDIT section,please.For now I can fetch related collection with one element only,but in real it contains 3. – sergionni Mar 22 '12 at 16:44
  • Try with **set** or **bag** instead on **list**. Say you have entries at **idx** 0, 5, 8 then the item in the list at position 1 will be null. – ManuPK Mar 23 '12 at 03:25