[jboss-user] [Persistence, JBoss/CMP, Hibernate, Database] - Two-way association problem
li.ni@helmet.fr
do-not-reply at jboss.com
Fri Jun 6 05:12:10 EDT 2008
Hi,
I have met a problem using EntityHome with Seam, I have found a solution by modifying a setter but I want to be sure it is the proper way to do it.
In order to implement a function âPost a topic in a forumâ, I have created 2 EntityBeans : Subject and Message. There is a oneToMany (two-way association) relation between Subjet and Message.
public class Subject implements Serializable {
...
private List associatedMessages = new LinkedList();
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "ownerSubject")
@OrderBy(value = "messageId ASC")
public List getAssociatedMessages()
{
return associatedMessages;
}
public void setAssociatedMessages(List associatedMessages)
{
this.associatedMessages = associatedMessages;
}
...
}
public class Message implements Serializable {
...
private Subject ownerSubject;
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "OWNER_SUBJECT_ID")
public Subject getOwnerSubject()
{
return ownerSubject;
}
public void setOwnerSubject(Subject ownerSubject)
{
this.ownerSubject = ownerSubject;
}
}
When a Subject instance is created, at the same time a 1st Message instance is created too and added to the List the subject, as shown in createSubject2() of the SessionBean SubjectHome
@Name("subjectHome")
public class SubjectHome extends EntityHome
{
...
@In(required=false)
MessageHome messageHome;
public void createSubject2()
{
this.messageHome.getInstance().setOwnerSubject(this.getInstance());
this.messageHome.persist();
this.logger.info("NUMBER OF ASSOCIATED MESSAGES : " + this.instance.getAssociatedMessages().size());
}
...
}
I've checked: 2 instances were successfully persisted, so in the datebase, 2 new rows were inserted in Subject table and Message table with no problem.
However in the console :
INFO [SubjectHome] NUMBER OF ASSOCIATED MESSAGES : 0
And when I navigate to the webpage which is used to show something of corresponding message of a Subject i met such error:
CODE:
#{subject.associatedMessages.get(0).submitTime}
ERROR:
/subjectList.xhtml: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
So I add a line in the Setter in my Message EntityBean :
public void setOwnerSubject(Subject ownerSubject) {
this.ownerSubject = ownerSubject;
this.ownerSubject.getAssociatedMessages().add(this);
}
This solves our problem, the new message is well in the subject List attribute without having to open a new session.
I just want to verify if it's ok to add additional line in Setter of EntityBean, just like what I did ? Thank you!
Regards
Li
View the original post : http://www.jboss.com/index.html?module=bb&op=viewtopic&p=4156236#4156236
Reply to the post : http://www.jboss.com/index.html?module=bb&op=posting&mode=reply&p=4156236
More information about the jboss-user
mailing list