Read the rules before posting!
http://www.hibernate.org/ForumMailingli ... AskForHelp
Hibernate version:
3.0 rc1 with annotations
Mapping documents:
Code:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Don't forget to copy your JDBC driver to the lib/ directory! -->
<!-- Settings for a remote MSSqlServer database. -->
<property name="dialect">org.hibernate.dialect.SQLServerDialect</property>
<property name="connection.driver_class">net.sourceforge.jtds.jdbc.Driver</property>
<property name="connection.url">jdbc:jtds:sqlserver://STAGEDB/CBAS</property>
<property name="connection.username">cbasapp</property>
<property name="connection.password">****</property>
<!-- Print SQL to stdout. -->
<property name="show_sql">true</property>
<!-- Mapping files. -->
<mapping class="model.Foo"/>
<mapping class="model.Bar"/>
</session-factory>
</hibernate-configuration>
Relevant annotationsCode:
/* From Foo.java */
@ManyToMany(
fetch=FetchType.LAZY
)
@AssociationTable(
table=@Table(name="FooBarRel"),
joinColumns={@JoinColumn(name="fooId")},
inverseJoinColumns={@JoinColumn(name="barId")}
)
public final Collection<Bar> getBars() {
return bars;
}
/* From Bar.java */
@ManyToMany(
fetch=FetchType.LAZY,
isInverse=true
)
@AssociationTable(
table=@Table(name="FooBarRel"),
joinColumns={@JoinColumn(name="barId")},
inverseJoinColumns={@JoinColumn(name="fooId")}
)
public final Collection<Foo> getFoos() {
return foos;
}
Code between sessionFactory.openSession() and session.close(): Code:
Foo foo = new Foo();
Criteria criteria = session.createCriteria(foo.getClass());
criteria = criteria.add(Example.create(foo));
Collection results = criteria.list();
for (Object o : results) {
foo = (Foo) o;
Collection<Bar> bars = foo.getBars();
System.out.println(bars.size());
for (Bar bar : bars) {
System.out.println(bar.getId());
}
}
Full stack trace of any exception that occurs:Name and version of the database you are using:SQL Server Standard Edition v8 (SP3)
The generated SQL (show_sql=true):Hibernate: select this_.id as id0_ from Foo this_ where (1=1)
Hibernate: select bars0_.fooId as fooId__, bars0_.barId as barId__ from FooBarRel bars0_ where bars0_.fooId=?
Debug level Hibernate log excerpt:I have a many-to-many mapping as shown in the code snippets above using annotations. When using FetchType.LAZY as above, the collections are being initialized but filled with 'blank' objects (the fields of the objects are all null). If the database had one Foo record and one Bar record, related with a record in the FooBarRel table, the output for the above program is
Code:
1
null
If I use FetchType.EAGER, this works fine and the output of the above program is
Code:
1
1
which is what I am after.
Is there something I am not doing right here to do with lazy initialization?