Statix wrote:
When I use the fetch="join" I get a large exception...
This is my mapping:
Code:
<hibernate-mapping package="com.gfs.pojo">
<class name="User" table="USER" fetch="join">
<id name="userId" column="USER_ID" type="java.lang.Integer">
<generator class="increment"/>
</id>
<property name="userName" column="USER_NAME" type="java.lang.String" not-null="true" />
<property name="userPassword" column="USER_PASSWORD" type="java.lang.String" not-null="true" />
<many-to-one name="userGroup" column="USER_GROUP_ID" class="UserGroup" />
</class>
</hibernate-mapping>
My error:
Code:
20-jul-2005 19:57:25 org.hibernate.util.XMLHelper$ErrorLogger error
SEVERE: Error parsing XML: XML InputStream(11) Attribute "fetch" must be declared for element type "class".
...bla bla bla and a lot more scary red words indicating something is wrong...
Anyway.... I searched and searched a lot at this website, google and a few other websites. Nothing can tell me exactly what I need to know.
I use
Hibernate 3 so lazy="false" isn't necessary if i'm correct.
~I have usergroups and users.
~One usergroup can have more users
~A user must be in a usergroup
My piece of java code
Code:
User criteria = new User();
criteria.setUserName(username.toString());
criteria.setUserPassword(password.toString());
Session session = sessions.openSession();
Transaction tx = session.beginTransaction();
Criteria crit = session.createCriteria(User.class);
crit.add(Example.create(criteria));
System.out.println("Debug: HN: List()");
List result = crit.list();
Why can't i call 'criteria.getUserGroup().getUserGroupName();' ??
getUserGroup returns
Null so I need a sort of lazy loading right?
Thanks in advance.
Use fetch="join" on the association, not the class.
<many-to-one name="userGroup" column="USER_GROUP_ID" class="UserGroup" fetch="join"/>
The way you have the code set up, "criteria" is just an example User object. It only contains the values you set which are username and password.
The variable "result" should contain a java.lang.List of User Objects that match that username and password. These objects should be fully populated.
(The Transaction code isn't necessary for reading)
And, as long as you haven't closed your session, lazy-loading shouldn't even be an issue.
For example:
Code:
User exmpUser = new User();
exmplUser.setSomething(something);
Session session = sessions.openSession();
List results = session.createCriteria(User.class).add(Example.create(exmpUser);
for(Iterator i = results.iterator();i.hasNext();) {
User user = (User)i.next();
System.out.println(user.getUserGroup().getUserGroupName());
}
session.closeSession();
The UserGroup object would be lazily loaded when you access it unless A) The session is already closed (if session.closeSession was before for-loop) or B) if the association was mapped with fetch="join" as I've shown above.
The Example object, in your case the "criteria" object, never gets populated.