<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
		>
<channel>
	<title>Comments on: JPA implementation patterns: Bidirectional assocations</title>
	<atom:link href="http://blog.xebia.com/2009/03/16/jpa-implementation-patterns-bidirectional-assocations/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.xebia.com/2009/03/16/jpa-implementation-patterns-bidirectional-assocations/</link>
	<description></description>
	<lastBuildDate>Thu, 11 Mar 2010 16:23:01 +0100</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
		<item>
		<title>By: Vincent Partington</title>
		<link>http://blog.xebia.com/2009/03/16/jpa-implementation-patterns-bidirectional-assocations/comment-page-1/#comment-94171</link>
		<dc:creator>Vincent Partington</dc:creator>
		<pubDate>Fri, 19 Feb 2010 14:17:20 +0000</pubDate>
		<guid isPermaLink="false">http://blog.xebia.com/?p=904#comment-94171</guid>
		<description>&lt;strong&gt;@Niko Will:&lt;/strong&gt; Glad to hear you that you were able to solve the problem. And thanks for letting me know. It should now be obvious to all readers of this blog that testing JPA code is &lt;strong&gt;very&lt;/strong&gt; hard. ;-)</description>
		<content:encoded><![CDATA[<p><strong>@Niko Will:</strong> Glad to hear you that you were able to solve the problem. And thanks for letting me know. It should now be obvious to all readers of this blog that testing JPA code is <strong>very</strong> hard. <img src='http://blog.xebia.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Niko Will</title>
		<link>http://blog.xebia.com/2009/03/16/jpa-implementation-patterns-bidirectional-assocations/comment-page-1/#comment-94165</link>
		<dc:creator>Niko Will</dc:creator>
		<pubDate>Thu, 18 Feb 2010 09:49:00 +0000</pubDate>
		<guid isPermaLink="false">http://blog.xebia.com/?p=904#comment-94165</guid>
		<description>@Vincent Partington: Mea culpa... I found the problem. In the unit tests I have to use a UserTransaction and commit it before trying to read the saved entity. Thank you very much for your help. King regards</description>
		<content:encoded><![CDATA[<p>@Vincent Partington: Mea culpa&#8230; I found the problem. In the unit tests I have to use a UserTransaction and commit it before trying to read the saved entity. Thank you very much for your help. King regards</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Niko Will</title>
		<link>http://blog.xebia.com/2009/03/16/jpa-implementation-patterns-bidirectional-assocations/comment-page-1/#comment-94130</link>
		<dc:creator>Niko Will</dc:creator>
		<pubDate>Tue, 16 Feb 2010 06:32:40 +0000</pubDate>
		<guid isPermaLink="false">http://blog.xebia.com/?p=904#comment-94130</guid>
		<description>@Vincent Partington: Thats not true. After I call the create methode of the netbeans automatic created facade for the vehicle, which is calling the persist method of the entitymanager, the vehicle entity has an id. Actually the unit test has more entries to check all other attributes but for readability I just post the important ones to show my problem. If I compare the size of both, the original vehicle list and the one from the db I get an assertion failure that expected  but it is . If the id wasn&#039;t correct set, the test should fail on the vehicleFromDb.getOwner().

I also tried to expose a method which gives me the entitytransaction and manually flush and commit the transaction and to retrieve the vehicleFromDb in a new one. This results in the same failure.

If I have more time I will read on your blog about testing. If you have another approach to get around my problem, please let me know.</description>
		<content:encoded><![CDATA[<p>@Vincent Partington: Thats not true. After I call the create methode of the netbeans automatic created facade for the vehicle, which is calling the persist method of the entitymanager, the vehicle entity has an id. Actually the unit test has more entries to check all other attributes but for readability I just post the important ones to show my problem. If I compare the size of both, the original vehicle list and the one from the db I get an assertion failure that expected  but it is . If the id wasn&#8217;t correct set, the test should fail on the vehicleFromDb.getOwner().</p>
<p>I also tried to expose a method which gives me the entitytransaction and manually flush and commit the transaction and to retrieve the vehicleFromDb in a new one. This results in the same failure.</p>
<p>If I have more time I will read on your blog about testing. If you have another approach to get around my problem, please let me know.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Vincent Partington</title>
		<link>http://blog.xebia.com/2009/03/16/jpa-implementation-patterns-bidirectional-assocations/comment-page-1/#comment-94127</link>
		<dc:creator>Vincent Partington</dc:creator>
		<pubDate>Mon, 15 Feb 2010 20:03:12 +0000</pubDate>
		<guid isPermaLink="false">http://blog.xebia.com/?p=904#comment-94127</guid>
		<description>&lt;strong&gt;@Niko Will:&lt;/strong&gt; I think the problem in your test is that the invocation of &lt;tt&gt;vehicle.getId()&lt;/tt&gt; returns 0. Only when the entity context is saved (which by defaults happens when you invoke EntityManager.find or commit the transaction) does the ID get a value.

As for the other questions: the persistence context usually lives exactly as long as the transaction. When you commit the transaction, the persistence context also gets flushed. The only exception to this is that the persistence context is also flushed (but the transaction not committed) when you invoke &lt;tt&gt;EntityManager.find&lt;/tt&gt; and the flush mode is set to &lt;tt&gt;AUTO&lt;/tt&gt; (the default).

Unless you find a way to revive the persistence context on a new servlet request (there are ways but I have not tried them), you will always get a new one. So then it is up to the JPA provider to make sure the relations are set up correctly.

That is exactly what makes unit testing JPA code so hard. You need multiple transactions within one test to simulate this. Which makes testing within one transaction so you can easily roll back impossible. But that is something I discuss in my JPA implementation patterns blog on &lt;a href=&quot;http://blog.xebia.com/2009/07/11/jpa-implementation-patterns-testing/&quot; rel=&quot;nofollow&quot;&gt;testing&lt;/a&gt;.</description>
		<content:encoded><![CDATA[<p><strong>@Niko Will:</strong> I think the problem in your test is that the invocation of <tt>vehicle.getId()</tt> returns 0. Only when the entity context is saved (which by defaults happens when you invoke EntityManager.find or commit the transaction) does the ID get a value.</p>
<p>As for the other questions: the persistence context usually lives exactly as long as the transaction. When you commit the transaction, the persistence context also gets flushed. The only exception to this is that the persistence context is also flushed (but the transaction not committed) when you invoke <tt>EntityManager.find</tt> and the flush mode is set to <tt>AUTO</tt> (the default).</p>
<p>Unless you find a way to revive the persistence context on a new servlet request (there are ways but I have not tried them), you will always get a new one. So then it is up to the JPA provider to make sure the relations are set up correctly.</p>
<p>That is exactly what makes unit testing JPA code so hard. You need multiple transactions within one test to simulate this. Which makes testing within one transaction so you can easily roll back impossible. But that is something I discuss in my JPA implementation patterns blog on <a href="http://blog.xebia.com/2009/07/11/jpa-implementation-patterns-testing/" rel="nofollow">testing</a>.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Niko Will</title>
		<link>http://blog.xebia.com/2009/03/16/jpa-implementation-patterns-bidirectional-assocations/comment-page-1/#comment-94118</link>
		<dc:creator>Niko Will</dc:creator>
		<pubDate>Sun, 14 Feb 2010 09:53:05 +0000</pubDate>
		<guid isPermaLink="false">http://blog.xebia.com/?p=904#comment-94118</guid>
		<description>@Vincent Partington: I have a question on the mentioned point:

&quot;Adding an OrderLine to an Order does not automatically persist it. You&#039;ll need to also invoke the persist method on its DAO (or the EntityManager) to do that. Or you can set the cascade property of the @OneToMany annotation on the Order.orderLines property to CascadeType.PERSIST (at least) to achieve that. More on this when we discuss the EntityManager.persist method.&quot;

I have a simple car configuration tool which saves all cars of a user. My entities look like the following:

&lt;pre lang=&quot;java&quot;&gt;
@Entity
public class Vehicle implements Serializable {
...
    @ManyToOne
    private User owner;

    public Vehicle(User owner) {
        this.owner = owner;
        this.owner.addVehicle(this);
    }

    @PreRemove
    protected void preRemove() {
        this.owner.removeVehicle(this);
    }
...
    public User getOwner() {
        return owner;
    }
}
&lt;/pre&gt;
&lt;pre lang=&quot;java&quot;&gt;
@Entity
public class User implements Serializable {
...
    @OneToMany(mappedBy=&quot;owner&quot;, cascade={CascadeType.PERSIST, CascadeType.REMOVE})
    private List vehicles;

    protected User() {
        vehicles = new ArrayList();
    }
...
    public List getVehicles() {
        return Collections.unmodifiableList(vehicles);
    }

    void addVehicle(Vehicle vehicle) {
        vehicles.add(vehicle);
    }

    void removeVehicle(Vehicle vehicle) {
        vehicles.remove(vehicle);
    }
}
&lt;/pre&gt;

My Unit Test looks as follows:

&lt;pre lang=&quot;java&quot;&gt;
    @Test
    public void CreateVehicleEntity() {
        User owner = new User(&quot;vehicle_jack1&quot;,&quot;jack&quot;);
        bs.getUserFacade().create(owner);

        Vehicle vehicle = new Vehicle(owner);
        bs.getVehicleFacade().create(vehicle);

        Vehicle vehicleFromDb = f.find(vehicle.getId());
        assertTrue(vehicle.getOwner().getVehicles().contains(vehicle));
        assertTrue(vehicleFromDb.getOwner().getVehicles().contains(vehicleFromDb));
    }
&lt;/pre&gt;

This test fails on the last assert statement because the relaiton from owner to vehicle is not persisted. How can I achieve that this happens. If I call the merge operation on the User entity it works, but I don&#039;t want the caller to know that he has to call this explicitly. If I put a cascade.PERSIST on the ManyToOne it doesn&#039;t work either because when persisting the vehicle the user is already persisted. This makes sense because the user might want to add another car later.

If I get you right the User Entity is in a managed context and will be saved to database on commit or end of the transaction. Is that true? Can I execute a commit within the Unit test? And when does the commit usually occurs? It is a web application and the user entity will be loaded to set the values on the GUI. If the user adds another car and the callback arrives in the servlet, I save the new car like the code describes, will the relation be there when the next callback to the servlet arrives?

Thanks in advanced and by the way, I love your series on JPA patterns. Greetings from Germany, Niko</description>
		<content:encoded><![CDATA[<p>@Vincent Partington: I have a question on the mentioned point:</p>
<p>&#8220;Adding an OrderLine to an Order does not automatically persist it. You&#8217;ll need to also invoke the persist method on its DAO (or the EntityManager) to do that. Or you can set the cascade property of the @OneToMany annotation on the Order.orderLines property to CascadeType.PERSIST (at least) to achieve that. More on this when we discuss the EntityManager.persist method.&#8221;</p>
<p>I have a simple car configuration tool which saves all cars of a user. My entities look like the following:</p>
<pre lang="java">
@Entity
public class Vehicle implements Serializable {
...
    @ManyToOne
    private User owner;

    public Vehicle(User owner) {
        this.owner = owner;
        this.owner.addVehicle(this);
    }

    @PreRemove
    protected void preRemove() {
        this.owner.removeVehicle(this);
    }
...
    public User getOwner() {
        return owner;
    }
}
</pre>
<pre lang="java">
@Entity
public class User implements Serializable {
...
    @OneToMany(mappedBy="owner", cascade={CascadeType.PERSIST, CascadeType.REMOVE})
    private List vehicles;

    protected User() {
        vehicles = new ArrayList();
    }
...
    public List getVehicles() {
        return Collections.unmodifiableList(vehicles);
    }

    void addVehicle(Vehicle vehicle) {
        vehicles.add(vehicle);
    }

    void removeVehicle(Vehicle vehicle) {
        vehicles.remove(vehicle);
    }
}
</pre>
<p>My Unit Test looks as follows:</p>
<pre lang="java">
    @Test
    public void CreateVehicleEntity() {
        User owner = new User("vehicle_jack1","jack");
        bs.getUserFacade().create(owner);

        Vehicle vehicle = new Vehicle(owner);
        bs.getVehicleFacade().create(vehicle);

        Vehicle vehicleFromDb = f.find(vehicle.getId());
        assertTrue(vehicle.getOwner().getVehicles().contains(vehicle));
        assertTrue(vehicleFromDb.getOwner().getVehicles().contains(vehicleFromDb));
    }
</pre>
<p>This test fails on the last assert statement because the relaiton from owner to vehicle is not persisted. How can I achieve that this happens. If I call the merge operation on the User entity it works, but I don&#8217;t want the caller to know that he has to call this explicitly. If I put a cascade.PERSIST on the ManyToOne it doesn&#8217;t work either because when persisting the vehicle the user is already persisted. This makes sense because the user might want to add another car later.</p>
<p>If I get you right the User Entity is in a managed context and will be saved to database on commit or end of the transaction. Is that true? Can I execute a commit within the Unit test? And when does the commit usually occurs? It is a web application and the user entity will be loaded to set the values on the GUI. If the user adds another car and the callback arrives in the servlet, I save the new car like the code describes, will the relation be there when the next callback to the servlet arrives?</p>
<p>Thanks in advanced and by the way, I love your series on JPA patterns. Greetings from Germany, Niko</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Fabrice Leray</title>
		<link>http://blog.xebia.com/2009/03/16/jpa-implementation-patterns-bidirectional-assocations/comment-page-1/#comment-94080</link>
		<dc:creator>Fabrice Leray</dc:creator>
		<pubDate>Wed, 10 Feb 2010 22:52:24 +0000</pubDate>
		<guid isPermaLink="false">http://blog.xebia.com/?p=904#comment-94080</guid>
		<description>@Vincent Partington : you&#039;re true I misunderstood this part of the pattern (read too quickly I presume :)).

Finally, for my project, I used the mentioned pattern http://notesonjava.wordpress.com/2008/11/03/managing-the-bidirectional-relationship/ and it did it pretty well. You can even make bi-directionnal may-to-many implementation (the only difference is that you have to manage 2 lists).

Thanks again for this nice article.</description>
		<content:encoded><![CDATA[<p>@Vincent Partington : you&#8217;re true I misunderstood this part of the pattern (read too quickly I presume <img src='http://blog.xebia.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ).</p>
<p>Finally, for my project, I used the mentioned pattern <a href="http://notesonjava.wordpress.com/2008/11/03/managing-the-bidirectional-relationship/" rel="nofollow">http://notesonjava.wordpress.com/2008/11/03/managing-the-bidirectional-relationship/</a> and it did it pretty well. You can even make bi-directionnal may-to-many implementation (the only difference is that you have to manage 2 lists).</p>
<p>Thanks again for this nice article.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: JPA Implementation Patterns &#124; Upthrust</title>
		<link>http://blog.xebia.com/2009/03/16/jpa-implementation-patterns-bidirectional-assocations/comment-page-1/#comment-94039</link>
		<dc:creator>JPA Implementation Patterns &#124; Upthrust</dc:creator>
		<pubDate>Tue, 02 Feb 2010 16:42:38 +0000</pubDate>
		<guid isPermaLink="false">http://blog.xebia.com/?p=904#comment-94039</guid>
		<description>[...] Bidirectional Associations [...]</description>
		<content:encoded><![CDATA[<p>[...] Bidirectional Associations [...]</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Jason Marston</title>
		<link>http://blog.xebia.com/2009/03/16/jpa-implementation-patterns-bidirectional-assocations/comment-page-1/#comment-93512</link>
		<dc:creator>Jason Marston</dc:creator>
		<pubDate>Tue, 15 Dec 2009 20:59:05 +0000</pubDate>
		<guid isPermaLink="false">http://blog.xebia.com/?p=904#comment-93512</guid>
		<description>I forgot to mention.  I do not allow anyone to call a method such as getOrderLines in most cases.

I have found that in most situations exposing the details of relationships like that is simply not needed and is an example of a violation of the Principle of Least Knowledge.

It is like reaching into someones back pocket to get some cash instead of asking them to give you some cash.

reaching in, you have to know where it is and how to open the wallet, if you ask, all that is done for you and you just get the cash you asked for.</description>
		<content:encoded><![CDATA[<p>I forgot to mention.  I do not allow anyone to call a method such as getOrderLines in most cases.</p>
<p>I have found that in most situations exposing the details of relationships like that is simply not needed and is an example of a violation of the Principle of Least Knowledge.</p>
<p>It is like reaching into someones back pocket to get some cash instead of asking them to give you some cash.</p>
<p>reaching in, you have to know where it is and how to open the wallet, if you ask, all that is done for you and you just get the cash you asked for.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Jason Marston</title>
		<link>http://blog.xebia.com/2009/03/16/jpa-implementation-patterns-bidirectional-assocations/comment-page-1/#comment-93511</link>
		<dc:creator>Jason Marston</dc:creator>
		<pubDate>Tue, 15 Dec 2009 20:53:01 +0000</pubDate>
		<guid isPermaLink="false">http://blog.xebia.com/?p=904#comment-93511</guid>
		<description>In this case where an order line MUST belong to exactly 1 order.  It seems to me a better solution to add a createOrderLine method to the Order object and pass the order into the constructor of the line

&lt;pre lang=&quot;java&quot;&gt;
public createLine(... various details of the line...) {
  final line = new OrderLine(this, ......);
  orderLines.add(line);
}
&lt;/pre&gt;

In this way the Order Line must always belong to the Order and cannot be moved.  However, exposing a moveToOrder method can handle the switching if needed and ensure it always belongs to an order.

I tend to use createXXX where ownership is needed and addXXX when only a relationship is needed if we then use Alex Snaps example then we can totally ignore the persistence aspects and instead treat the whole thing as pure objects.

To take care of an Order being deleted and wanting to clean up lines, you can of course cascade removes in this association.</description>
		<content:encoded><![CDATA[<p>In this case where an order line MUST belong to exactly 1 order.  It seems to me a better solution to add a createOrderLine method to the Order object and pass the order into the constructor of the line</p>
<pre lang="java">
public createLine(... various details of the line...) {
  final line = new OrderLine(this, ......);
  orderLines.add(line);
}
</pre>
<p>In this way the Order Line must always belong to the Order and cannot be moved.  However, exposing a moveToOrder method can handle the switching if needed and ensure it always belongs to an order.</p>
<p>I tend to use createXXX where ownership is needed and addXXX when only a relationship is needed if we then use Alex Snaps example then we can totally ignore the persistence aspects and instead treat the whole thing as pure objects.</p>
<p>To take care of an Order being deleted and wanting to clean up lines, you can of course cascade removes in this association.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Vincent Partington</title>
		<link>http://blog.xebia.com/2009/03/16/jpa-implementation-patterns-bidirectional-assocations/comment-page-1/#comment-93016</link>
		<dc:creator>Vincent Partington</dc:creator>
		<pubDate>Wed, 04 Nov 2009 12:39:39 +0000</pubDate>
		<guid isPermaLink="false">http://blog.xebia.com/?p=904#comment-93016</guid>
		<description>&lt;strong&gt;@Fabrice&lt;/strong&gt;: Aha, I see where you misunderstand the pattern. The first if-statement in &lt;tt&gt;setOrder&lt;/tt&gt; checks the &lt;tt&gt;order&lt;/tt&gt; field (&lt;tt&gt;this.order&lt;/tt&gt;) instead of the &lt;tt&gt;order&lt;/tt&gt; parameter. That means that it &lt;strong&gt;will&lt;/strong&gt; invoke internalRemoveOrderLine on the order the orderLine was associated with.

In other words, the call becomes like this:
&lt;pre lang=&quot;java&quot;&gt;
public void setOrder(NULL) {
	this.order.internalRemoveOrderLine(this);
	this.order = NULL;
}
&lt;/pre&gt;

Which is want you want. I have used this pattern in existing code *and* tried the example above before posting it, so I am pretty sure it works. ;-)

Hmmm, maybe the pattern explains itself better when the parameter name is something like &lt;tt&gt;newOrder&lt;/tt&gt;.
</description>
		<content:encoded><![CDATA[<p><strong>@Fabrice</strong>: Aha, I see where you misunderstand the pattern. The first if-statement in <tt>setOrder</tt> checks the <tt>order</tt> field (<tt>this.order</tt>) instead of the <tt>order</tt> parameter. That means that it <strong>will</strong> invoke internalRemoveOrderLine on the order the orderLine was associated with.</p>
<p>In other words, the call becomes like this:</p>
<pre lang="java">
public void setOrder(NULL) {
	this.order.internalRemoveOrderLine(this);
	this.order = NULL;
}
</pre>
<p>Which is want you want. I have used this pattern in existing code *and* tried the example above before posting it, so I am pretty sure it works. <img src='http://blog.xebia.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p>Hmmm, maybe the pattern explains itself better when the parameter name is something like <tt>newOrder</tt>.</p>
]]></content:encoded>
	</item>
</channel>
</rss>
