| Title: Tutorial Delete |
| |
| |
| |
| <P>Before we discuss the API for object deletion, lets go back to CayenneModeler and set up some <A href="delete-rules.html" title="Delete Rules">delete rules</A>. Doing this is optional but will simplify correct handling of the objects related to deleted objects.</P> |
| |
| <UL> |
| <LI>In the Modeler go to "Artist" ObjEntity, "Relationships" tab and select "Cascade" for the "paintings" relationship delete rule:</LI> |
| </UL> |
| |
| |
| <P><SPAN class="image-wrap" style=""><IMG src="tutorial-delete.data/delete-rule.jpg" style="border: 0px solid black"></SPAN></P> |
| |
| <UL> |
| <LI>Repeat this step for Gallery (set "paintings" relationship to be "Cascade")</LI> |
| <LI>Repeat this step for Painting (set both relationships rules to "Nullify").</LI> |
| <LI>Save the mapping, and refresh the porject in Eclispe.</LI> |
| </UL> |
| |
| |
| <UL> |
| <LI>To delete an object we first need to get a hold of this object. Let's use utility class DataObjectUtils to find an artist:</LI> |
| </UL> |
| |
| |
| <DIV class="code panel" style="border-width: 1px;"><DIV class="codeHeader panelHeader" style="border-bottom-width: 1px;"><B>Main.java</B></DIV><DIV class="codeContent panelContent"> |
| <PRE class="code-java">Expression qualifier = ExpressionFactory.matchExp(Artist.NAME_PROPERTY, <SPAN class="code-quote">"Pablo Picasso"</SPAN>); |
| SelectQuery select = <SPAN class="code-keyword">new</SPAN> SelectQuery(Artist.class, qualifier); |
| |
| Artist picasso = (Artist) DataObjectUtils.objectForQuery(context, select);</PRE> |
| </DIV></DIV> |
| |
| <P>Now let's delete the artist:</P> |
| <DIV class="code panel" style="border-width: 1px;"><DIV class="codeHeader panelHeader" style="border-bottom-width: 1px;"><B>Main.java</B></DIV><DIV class="codeContent panelContent"> |
| <PRE class="code-java"><SPAN class="code-keyword">if</SPAN> (picasso != <SPAN class="code-keyword">null</SPAN>) { |
| context.deleteObject(picasso); |
| context.commitChanges(); |
| }</PRE> |
| </DIV></DIV> |
| |
| <P>Since we set up "Cascade" delete rule for the Artist.paintings relationships, Cayenne will automatically delete all paintings of this artist. So when your run the app you'll see this output:</P> |
| |
| <DIV class="preformatted panel" style="border-width: 1px;"><DIV class="preformattedContent panelContent"> |
| <PRE>INFO QueryLogger: --- will run 2 queries. |
| INFO QueryLogger: --- transaction started. |
| INFO QueryLogger: DELETE FROM PAINTING WHERE ID = ? |
| INFO QueryLogger: [bind: 361] |
| INFO QueryLogger: === updated 1 row. |
| INFO QueryLogger: [bind: 360] |
| INFO QueryLogger: === updated 1 row. |
| INFO QueryLogger: DELETE FROM ARTIST WHERE ID = ? |
| INFO QueryLogger: [bind: 360] |
| INFO QueryLogger: === updated 1 row. |
| INFO QueryLogger: +++ transaction committed.</PRE> |
| </DIV></DIV> |
| |
| <HR> |
| <P><B>Next Step: <A href="tutorial-webapp.html" title="Tutorial Webapp">Tutorial Webapp</A></B></P> |
| <HR> |