users@glassfish.java.net

JPA question

From: Pawel R. <odwrotnie_at_gmail.com>
Date: Sun, 23 Dec 2007 20:39:15 +0100

Hi,

assume we have:

@Entity
public class Template {
...
        @OneToOne(mappedBy="template", cascade = ALL)
        private Document document;
        public Document getDocument() {
                return document;
        }
        public void setDocument(Document document) {
                this.document = document;
        }
...

}

and

@Entity
public class Document {
...
        @OneToOne(cascade = ALL)
        private Template template;
        public Template getTemplate() {
                return template;
        }
        public void setTemplate(Template template) {
                this.template = template;
        }
...

}

Now we write the code

Document d = new Document();
Template t = new Template();
d.setTemplate(t);

Before persisting:
d.getTemplate() gives t
but
t.getDocument() gives null.

This is quite OK.

After persisting and then fetching (fd is fetched Document):
fd.getTemplate() gives t
but
fd.getTemplate().getDocument() gives null :/.

Is it a good idea to change the above method to
public void setTemplate(Template template) {
        this.template = template;
        template.setDocument(this);
}

public void setDocument(Document document) {
        this.document = document;
        document.setTemplate(this);

}

?

Pozdrawiam,
Paweł R.