<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[j2ee - JBay Solutions - The Dev Blog]]></title><description><![CDATA[JBay Solutions Development Blog on Java, Android, Play2 and others]]></description><link>http://blog.jbaysolutions.com/</link><generator>Ghost 0.7</generator><lastBuildDate>Wed, 16 Oct 2024 01:15:05 GMT</lastBuildDate><atom:link href="http://blog.jbaysolutions.com/tag/j2ee/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[JPA 2 Tutorial - Relationships - One To Many]]></title><description><![CDATA[<p><a href="http://syshex.files.wordpress.com/2011/09/one_to_many.png"><img src="http://syshex.files.wordpress.com/2011/09/one_to_many.png?w=150" alt="" title=""></a>Following from the previous tutorial we now dive into move interesting and complex parts of JPA 2: Relationships! In this tutorial we'll be focusing on One-to-Many relationships (mainly Bidirectional), looking into their particularities (specially related to the Cascading of operations), we'll create a JUnit Test class for testing the Relationship,</p>]]></description><link>http://blog.jbaysolutions.com/2011/09/19/jpa-2-relationships-onetomany/</link><guid isPermaLink="false">44301afb-dddd-4dbd-b015-7f9182911d93</guid><category><![CDATA[java]]></category><category><![CDATA[jpa]]></category><category><![CDATA[glassfish]]></category><category><![CDATA[j2ee]]></category><category><![CDATA[junit]]></category><category><![CDATA[relationships]]></category><category><![CDATA[eclipselink]]></category><category><![CDATA[mysql]]></category><dc:creator><![CDATA[Rui Pereira]]></dc:creator><pubDate>Mon, 19 Sep 2011 21:20:38 GMT</pubDate><content:encoded><![CDATA[<p><a href="http://syshex.files.wordpress.com/2011/09/one_to_many.png"><img src="http://syshex.files.wordpress.com/2011/09/one_to_many.png?w=150" alt="" title=""></a>Following from the previous tutorial we now dive into move interesting and complex parts of JPA 2: Relationships! In this tutorial we'll be focusing on One-to-Many relationships (mainly Bidirectional), looking into their particularities (specially related to the Cascading of operations), we'll create a JUnit Test class for testing the Relationship, look at what actual SQL queries that are performed, learn by example and also some more interesting theory that is related to all of this. So, if at this point you haven't read the first tutorial on JPA 2, you might want to do it now.  As always a few assumptions are made, like basic knowledge of SQL and relational databases, what an EJB is and where does it run, Unit Testing, an IDE is setup (like NetBeans) , a MySQL database is setup and basic knowledge on how to use it and , as stated before : All the things that were explained on the first JPA Tutorial:  <strong><a href="http://blog.jbaysolutions.com/2011/09/10/jpa_getting_started_part1/">Getting Started with JPA 2 Tutorial</a></strong></p>

<p>Also, the source code used for the demonstration later on this tutorial can be found here : <a href="http://sourceforge.net/projects/syshex/">http://sourceforge.net/projects/syshex/</a> . It is simply a NetBeans project with the basic classes that we'll modify later on the Tutorial to check stuff.</p>

<p>Right, lets get down to business. In a relational database  tables can bear associations between each other, in JPA these associations are can be mapped onto the Entity Beans in order to represent the database schema. This is done by annotating reference attributes to other Entity Beans. There are 4 types of relationships :</p>

<ul>
<li>One to Many</li>
<li>Many to One</li>
<li>Many to Many    </li>
<li>One to One</li>
</ul>

<h3 id="bidirectionalandunidirectional">Bidirectional and Unidirectional</h3>

<p>These relationship types can be either Bidirectional or Unidirectional. The basic difference between Bidirectional and Unidirectional is that in a Bidirectional relationship, both Entities contain annotated reference attributes between each other and in a Unidirectional relationship only one of the Entity Beans references the other.</p>

<h3 id="owningside">Owning Side</h3>

<p>Any relationship has an owning side. This is what determines the updates to the relationship in a database. In the case of a Bidirectional relationship, one of the Entity Beans is always the owning side and the other side is called the inverse side. In a Unidirectional relationship, because only one of the Entity Beans in the relationship bears reference to the other, that Entity is the owning side of the relationship and there is no inverse. In One-to-Many and Many-to-One relationships, the Many part of the relationship is always the Owning side.</p>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br></p>

<h3 id="onetomany">One To Many</h3>

<p>So, for our example lets take two tables, one called Company and the other called Employee. The MySQL Workbench model file can be found with the sources of this tutorial, still it looks like this: </p>

<p><a href="http://syshex.files.wordpress.com/2011/09/diagram.png"><img src="http://syshex.files.wordpress.com/2011/09/diagram.png" alt="" title=""></a></p>

<p>This is the SQL that generates this schema :</p>

<pre><code> CREATE  TABLE IF NOT EXISTS `jpatutorial2`.`company` (
   `idcompany` INT NOT NULL AUTO_INCREMENT ,
   `name` VARCHAR(45) NOT NULL ,
   `address` VARCHAR(45) NOT NULL ,
   PRIMARY KEY (`idcompany`) )
 ENGINE = InnoDB;

 CREATE  TABLE IF NOT EXISTS `jpatutorial2`.`employee` (
   `idemployee` INT NOT NULL AUTO_INCREMENT ,
   `company` INT NOT NULL ,
   `name` VARCHAR(45) NOT NULL ,
   `phone` VARCHAR(45) NOT NULL ,
   PRIMARY KEY (`idemployee`) ,
   INDEX `fk_employee_company` (`company` ASC) ,
   CONSTRAINT `fk_employee_company`
     FOREIGN KEY (`company` )
     REFERENCES `jpatutorial2`.`company` (`idcompany` )
     ON DELETE NO ACTION
     ON UPDATE NO ACTION)
 ENGINE = InnoDB;
</code></pre>

<p>Notice that in our little example the Foreign Key in the employee table is Not Null. So, because Employee is the Many part of this One-To-Many relationship, the EmployeeEntity class will be the owner of the relationship. This means that EmployeeEntity references only one CompanyEntity and that that reference field is annotated with the @ManyToOne annotation. The CompanyEntity class is the inverse of this One-To-Many relationship which means that it references many EmployeesEntities (a collection or list of EmployeeEntity), and that collection is annotated with the @OneToMany annotation. The following bit of code can be found on the EmployeeEntity class and exemplifies what has been said:</p>

<pre><code>  @ManyToOne(optional = false)
  @JoinColumn(name = "company", referencedColumnName = "idcompany")
  private CompanyEntity company;
</code></pre>

<p>And this bit on the CompanyEntity class explains the inverse bit:</p>

<pre><code>  @OneToMany(cascade = CascadeType.ALL, mappedBy = "company")
  private Collection&lt;EmployeeEntity&gt; employeeCollection;
</code></pre>

<p>These two bits of code make this a One-to-Many / Many-to-One bidirectional relationship because both sides of the relationship have references to the other side.</p>

<h2 id="manytoone">@ManyToOne</h2>

<p>The ManyToOne annotation is used to define a single value association with another entity bean. Because the reference field is defined as a CompanyEntity object called company there is no need to specify further on this annotation which class type is the entity target, this is because it can be inferred. If this was not the case, as if for example the reference field was of type Object:</p>

<pre><code> private Object company;
</code></pre>

<p>In this case the annotation element <strong><em>targetEntity</em></strong> should be used in order to let the Entity Manager know which type of object this Entity has a relation to:</p>

<pre><code> @ManyToOne(optional = false, targetEntity=CompanyEntity.class)
</code></pre>

<p>Other more important and more regularly used elements of the ManyToOne annotation are both <strong><em>cascade</em></strong>, <strong><em>fetch</em></strong>, and <strong><em>optional</em></strong>. The <em><strong>optional</strong></em> element is used to indicate whether this reference can be null or not. The default value is <em><strong>true</strong></em>, and if it is defined as <em><strong>false</strong></em> then the relationship in the database schema must be defined as not-null. The <em><strong>fetch</strong></em> element is used to indicate how the Entity Manager should retrieve the referenced object of this relationship. The two possible values are <em><strong>FetchType.EAGER</strong></em> and <em><strong>FetchType.LAZY</strong></em>, with eager being the default. This element is of particular importance due to its usefulness when dealing with performance and small amounts of memory because it can avoid the initialization of unneeded large objects (imagine a relationship to an Object containing a large byte[] corresponding to a file), and avoid the extra database queries and data transference. It is usually used more on the OneToMany annotation due to the large amount of Object that can get created from retrieving the One side of the relationship. The <em><strong>cascade</strong></em> element of this annotation is used to specify the operations that must be cascaded to the elements of the association. The possible options are as defined in the <em><strong>CascadeType</strong></em>enum with the default being that no operations are cascaded by omition of the cascade element:</p>

<pre><code> public enum CascadeType { ALL, PERSIST, MERGE, REMOVE, REFRESH, DETACH};
</code></pre>

<p>The <em><strong>All</strong></em>option means the combination of all the remaining options available. We will discuss more on this later on this tutorial. This element is also of particular importance on the OneToMany annotation because it will allow persistence of data from the inverse side of the relationship.</p>

<h2 id="joincolumn">@JoinColumn</h2>

<p>The <em><strong>@JoinColumn</strong></em>annotation is used to specify a column on the database table for the relationship. So, in our example, in the EmployeeEntity bean we got the following:</p>

<pre><code> @JoinColumn(name = "company", referencedColumnName = "idcompany")
</code></pre>

<p>And in the SQL to generate the Employee table we got:</p>

<pre><code> INDEX `fk_employee_company` (`company` ASC) ,
   CONSTRAINT `fk_employee_company`
     FOREIGN KEY (`company` )
     REFERENCES `jpatutorial2`.`company` (`idcompany` )
     ON DELETE NO ACTION
     ON UPDATE NO ACTION)
</code></pre>

<p>The <em><strong>name</strong></em> element of the <em>@JoinColumn</em> annotation defines the name of the Foreign Key (FK) column. In this case, the name of the FK column is "company" as defined in the constraint.</p>

<p>The <em><strong>referencedColumnName</strong></em> element of the <em>@JoinColumn</em> annotation is used to define the column in the referenced table for the relationship, which is our case is "idcompany", which is the Primary Key (PK) of the referenced table. This means that it can be omitted here because the default value of <em><strong>referencedColumnName</strong></em> is the PK of the referenced table, which is discovered by looking at the table of the target Entity.</p>

<p>There are many other element options available for this annotation and one particularity about them is that they are all concerning the <em><strong>name</strong></em> element of the <em><strong>@JoinColumn</strong></em>. Other elements are <em><strong>nullable **</strong></em>(if the FK column is nullable) , <em>insertable<strong></strong></em> (if the FK column is to be insertable or generated), <em>unique<strong></strong></em> (if the FK column is unique, defaults to false, but it the FK column is the PK of the referenced table it is not necessary to set as true), <em>table<strong></strong></em> (the name of the table of the reference that contains the column), <em>columnDefinition**</em> (for generating the DLL of the column).</p>

<h2 id="onetomany">@OneToMany</h2>

<p>On the CompanyEntity class we use the @OneToMany annotation in the following way:</p>

<pre><code> @OneToMany(cascade = CascadeType.ALL, mappedBy = "company")
 private Collection&lt;EmployeeEntity&gt; employeeCollection;
</code></pre>

<p>The <em><strong>@OneToMany</strong></em> annotation is used to define a multi-value association to a Collection of Entities.  Because the relationship we are creating is bidirectional (because references exist on both sides of the relationship) the annotation element <em><strong>mappedBy</strong></em> MUST be used to specify the field that exists on the referenced entity which is the owner of the relationship.</p>

<p>The other possible annotation elements that can be used are <em><strong>cascade</strong></em>, <em><strong>fetch</strong></em> and <em><strong>targetEntity</strong></em>, which work exactly as explained for the <em>ManyToOne</em> annotation and the element <em><strong>orphanRemoval</strong></em> which is defaulted to false. The <em><strong>orphanRemoval</strong></em> functionality is intended for entities that are privately owned by the parent entity and will cause a remove operation to be propagated to those child entities without the need to use the <em>cascade type remove</em> to make it so.</p>

<p>Bear in mind that having this side of the relationship with the element <em><strong>cascade</strong></em> as <em><strong>ALL</strong></em> has several implications with the working of the code itself and the management of the entity beans. This will be shown in a bit.</p>

<p>And that is it! This is basically most of what is needed to know about a Bidirectional  One-To-Many Relationship but for more details, specially with concerns about default behaviors and other not so common characteristics please do check the JPA 2 Spec (JSR-317) which is in the references at the end of this tutorial.</p>

<p>Obviously this wouldn't be complete without some testing and demonstration of the topics just discussed here! So lets jump right into that:</p>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br></p>

<h2 id="seeingitworking">Seeing it working</h2>

<p>So for starters, all the code for this project can be found at : <a href="http://sourceforge.net/projects/syshex/">http://sourceforge.net/projects/syshex/</a> . If you haven't download it yet, go there, download it (the distribution file should be called _ JPATutorial2-src-v.X.Y.zip_ or <em>tar.bz2</em> or checkout the source from SVN) and open it with NetBeans (I use NetBeans 6.7 for this). Also, there should be a database configured on your test box, the Schema MySQL Workbench file can be found inside the distribution in a folder called <em>model</em>.</p>

<p>Apply the model to your database, open the NetBeans project and just dive right into the  <strong>persistence.xml</strong> file. Add the following property line there:</p>

<pre><code> &lt;property name="eclipselink.jdbc.driver" value="com.mysql.jdbc.Driver"/&gt;
 &lt;property name="eclipselink.jdbc.url" value="jdbc:mysql://localhost:3306/jpatutorial2"/&gt;
 &lt;property name="eclipselink.logging.level" value="FINE" /&gt;
 &lt;/properties&gt;
</code></pre>

<p>This property will help us view what is actually being done at the database level. You could configure the database to log all SQL queries if you would like, I rather do it this way cause I'll also get verbose output from the Entity Manager that actually help solve loads of problems.</p>

<p>Also, adjust the remaining properties of the persistence.xml file to fit the MySQL configuration in use at your box.</p>

<p>Now go for the Test Packages and open the only JUnit file there: <em><strong>OneToManyTesting.java</strong></em> . This file has two tests configured in it but I'm not actually using any asserts there to validate the correctness of the Tests, but instead just looking to see if the operations return exceptions (a Fail) or if all operations on the method execute without exception. While on the IDE with this file focused, to execute the JUnit tests you should press <strong>Ctrl-F6</strong> which should open the <strong>Test Results</strong> tab and the <strong>Output</strong> tab.</p>

<p>OK lets do it then, run the JUnit tests. Because we have just set the logging level to FINE the <strong>Output</strong> tab will be filled with logging stuff.  So all went well hopefully.</p>

<p>Lets go ahead and delete <em>testCreateCompany()</em> test method (or just comment the @Test annotation) and run it again. The output of the log should show something like this (I trimmed a bit of the beginning of each line of the log) :</p>

<pre><code> // ------------------- FIRST BIT -------------------------
 Thread(Thread[main,5,main])--INSERT INTO jpatutorial2.company (address, name) VALUES (?, ?)        bind = [Av. 5 October, Lisbon, JBay Solutions]
 Thread(Thread[main,5,main])--SELECT LAST_INSERT_ID()
 Thread(Thread[main,5,main])--INSERT INTO jpatutorial2.employee (name, phone, company) VALUES (?, ?, ?)
         bind = [Rui Pereira, 23456789, 3]
 Thread(Thread[main,5,main])--SELECT LAST_INSERT_ID()
 // ------------------- SECOND BIT -------------------------
 Thread(Thread[main,5,main])--DELETE FROM jpatutorial2.employee WHERE (idemployee = ?)
         bind = [2]
 Thread(Thread[main,5,main])--DELETE FROM jpatutorial2.company WHERE (idcompany = ?)
         bind = [3]
</code></pre>

<p>In the code that we are using the first bit of the log corresponds to :</p>

<pre><code> em.persist(c);
 em.flush();
</code></pre>

<p>While the second bit of the log corresponds to :</p>

<pre><code> em.remove(c);
 em.getTransaction().commit();
</code></pre>

<p>Notice that in relation to the first bit of the log we just persisted one object, a <em><strong>CompanyEntity</strong></em> object that was new (check previous tutorial for Entity Lifecycle). There is another entity bean on the code, an <em><strong>EmployeeEntity</strong></em> object created but never persisted. The reason why in the first bit of logging, corresponding to the em.persist(c) statement, the two entities were persisted on the database is not magic, <strong>DOES NOT HAPPEN BY DEFAULT</strong>, and is in every way related the following:</p>

<ol>
<li><p>both objects were made to reference each other (therefore creating a valid relationship).</p></li>
<li><p>and to the way these two Entities are annotated (cascading)</p></li>
</ol>

<h3 id="creatingavalidrelationship">Creating a valid relationship</h3>

<p>Concerning the first bullet point: <em>both objects were made to reference each other (therefore creating a valid relationship) :</em></p>

<pre><code> // part 1
 e1.setCompany(c);
 // part 2
 c.getEmployeeCollection().add(e1);
</code></pre>

<p>So, in part one we set <em>CompanyEntity</em> <em><strong>c</strong></em> as the company of <em>EmployeeEntity** e1**</em>.</p>

<p>In part two we set a newly created Collection (a Vector) called <em><strong>a</strong></em>, which contains <em>EmployeeEntity</em> <em><strong>e1</strong></em>, as the Employee Collection of <em>Company</em> <em><strong>c</strong></em>.</p>

<p>One could ask: Is it necessary for both the Entity Objects to reference each other, could we not just make one reference the other and be done with it? Well.... you shouldn't. JPA 2 Spec states in page 42 the following:</p>

<p>Note that it is the application that bears responsibility for maintaining the consistency of run-time relationships- for example, for insuring that the “one” and the “many” sides of a bidirectional relationship are consistent with one another when the application updates the relationship at runtime. </p>

<p>Basically, the application should maintain consistency of run-time relationships, not the Entity Manager, and there is good reason for that: If only one side of the bidirectional relationship has a reference to the other side of the relationship then at run-time both Entities tell a different story about their relationship and ... the Entity Manager can't quite figure out what is it supposed to do: believe in one or the other Entity? Well, it believes the one that it is trying to persist which leads to the other entity to be inconsistent and require a <em>refresh()</em>. More on this later.</p>

<p>If for example we were to comment the following line :</p>

<pre>   
     <em>//e1.setCompany(c);</em>
 </pre>

<p>The log would tell a different story altogether:</p>

<pre><code> Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.0.v20110604-r9504): org.eclipse.persistence.exceptions.DatabaseException
 Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'company' cannot be null
 Error Code: 1048
 Call: INSERT INTO jpatutorial2.employee (name, phone, company) VALUES (?, ?, ?)
         bind = [Rui Pereira, 23456789, null]
</code></pre>

<p>So, exception because the field cannot be Null.</p>

<p>Now, if we leave <em>e1.setCompany(c);</em> uncommented (so, undo last change to the code) and now comment the following:</p>

<pre><code> //c.getEmployeeCollection().add(e1);
</code></pre>

<p>And now execute the JUnit test what happens is that only the <em>CompanyEntity</em> <em><strong>c</strong></em> gets created. The Entity Manager <em><strong>em</strong></em> is called to persist <em><strong>c</strong></em> and has no knowledge of <em><strong>e1</strong></em> being related (because it is only looking at <em><strong>c</strong></em> since it was the object that was requested to be persisted) and does not persist <em><strong>e1</strong></em> and only persist <em><strong>c</strong></em>.</p>

<p>Now for the interesting bit: What about if we leave everything unchanged (so uncomment <em>c.getEmployeeCollection().add(e1);</em> ) and instead of persisting <em>CompanyEntity <strong>c</strong></em> we go all creative and persist <em>EmployeeEntity</em> <em><strong>e1</strong></em> instead? Well... that leads us to the second point stated above: <em>the way these two Entities are annotated (cascading)</em></p>

<p>But first let us test it anyway by doing the following changes:</p>

<pre><code> //em.persist(c);
 em.persist(e1);
 em.flush();
</code></pre>

<p>When we run it we get :</p>

<pre><code> Testcase: testCreateCompanyWithEmployee(com.syshex.tutorials.jpa2.tut2.OneToManyTesting):        Caused an ERROR
 During synchronization a new object was found through a relationship that was not marked cascade PERSIST: com.syshex.tutorials.jpa2.tut2.entity.CompanyEntity@1c286e2.
</code></pre>

<p>An Error.</p>

<h3 id="relationshipcascading">Relationship Cascading</h3>

<p>So, as expected, the way the Entities were designed influences a lot of the behavior that we'll get when using them! This is of no surprise I expect. One particular detail of this relationship makes persisting <em><strong>c</strong></em> generate an automatic persistence of <em><strong>e1</strong></em> and makes persisting <em><strong>e1</strong></em> fail, that detail the way the Cascades were defined for each side of the relationship:</p>

<p>On the <em>CompanyEntity</em> class we apply <em><strong>CascadeType.ALL</strong></em> to the relationship :</p>

<pre><code> @OneToMany(cascade = CascadeType.ALL, mappedBy = "company")
 private Collection&lt;EmployeeEntity employeeCollection;
</code></pre>

<p>On the <em>EmployeeEntity</em> class we do not define the type of cascade to apply and therefore we default to <em><strong>no cascading</strong></em>:</p>

<pre><code> @ManyToOne(optional = false)
 @JoinColumn(name = "company", referencedColumnName = "idcompany")
 private CompanyEntity company;
</code></pre>

<p>But to validate that our train of though is correct, let us modify the <em>EmployeeEntity</em> class and define, for example, the cascading as <em><strong>CascadeType.PERSIST</strong></em> just like so:</p>

<pre><code> @ManyToOne(optional = false, cascade=CascadeType.PERSIST)
 @JoinColumn(name = "company", referencedColumnName = "idcompany")
 private CompanyEntity company;
</code></pre>

<p>and now we execute again the JUnit test class. What we get is the persistence of both e1 and c on the database, just like expected:</p>

<pre><code> Thread(Thread[main,5,main])--INSERT INTO jpatutorial2.company (address, name) VALUES (?, ?)
         bind = [Av. 5 October, Lisbon, JBay Solutions]
 Thread(Thread[main,5,main])--SELECT LAST_INSERT_ID()
 Thread(Thread[main,5,main])--INSERT INTO jpatutorial2.employee (name, phone, company) VALUES (?, ?, ?)
         bind = [Rui Pereira, 23456789, 10]
 Thread(Thread[main,5,main])--SELECT LAST_INSERT_ID()
 Thread(Thread[main,5,main])--DELETE FROM jpatutorial2.employee WHERE (idemployee = ?)
         bind = [3]
 Thread(Thread[main,5,main])--DELETE FROM jpatutorial2.company WHERE (idcompany = ?)
         bind = [10]
</code></pre>

<p>Now lets get creative and if we set both sides of the relationship with <em><strong>CascadeType.ALL</strong></em> and now do the following :</p>

<pre><code> /* c.getEmployeeCollection().add(e1); */

 //em.persist(c);
 em.persist(e1);
 em.flush();
</code></pre>

<p>So, we only keep the e1.setCompany(c) association because it cannot be null and we persist now from the inverse. Basically we do not keep both sides of the relationship consistent. We execute and we get :</p>

<pre><code> Thread(Thread[main,5,main])--INSERT INTO jpatutorial2.company (address, name) VALUES (?, ?)
         bind = [Av. 5 October, Lisbon, JBay Solutions]
 Thread(Thread[main,5,main])--SELECT LAST_INSERT_ID()
 Thread(Thread[main,5,main])--INSERT INTO jpatutorial2.employee (name, phone, company) VALUES (?, ?, ?)
         bind = [Rui Pereira, 23456789, 16]
 Thread(Thread[main,5,main])--SELECT LAST_INSERT_ID()
 Thread(Thread[main,5,main])--DELETE FROM jpatutorial2.company WHERE (idcompany = ?)
         bind = [16]
 Thread(Thread[main,5,main])--SELECT 1
 Thread(Thread[main,5,main])--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.0.v20110604-r9504): org.eclipse.persistence.exceptions.DatabaseException
 Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`jpatutorial2/employee`, CONSTRAINT `fk_employee_company` FOREIGN KEY (`company`) REFERENCES `company` (`idcompany`) ON DELETE NO ACTION ON UPDATE NO ACTION)
 Error Code: 1451
 Call: DELETE FROM jpatutorial2.company WHERE (idcompany = ?)
         bind = [16]
 Query: DeleteObjectQuery(com.syshex.tutorials.jpa2.tut2.entity.CompanyEntity@3f96ee)
</code></pre>

<p>What happens is: both entries get inserted on the database but now <em>CompanyEntity</em> <strong><em>c</em></strong> is detached and outdated and requires being refreshed so that <em>em.remove(c)</em> can be executed:</p>

<pre><code> //em.persist(c);
 em.persist(e1);
 em.flush();
 em.refresh(c);
</code></pre>

<p>By refreshing the Entity object and making it managed it can now be used on the Entity Manager and the logs produce no errors.</p>

<p>Hope this shared some light on how things work underneath all the code of the One-To-Many/Many-To-One relationships and helps anyone.</p>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br></p>

<h1 id="references">References</h1>

<p><a href="http://download.oracle.com/auth/otn-pub/jcp/persistence-2.0-fr-eval-oth-JSpec/persistence-2_0-final-spec.pdf">Java Persistence Api 2 Specification</a></p>

<p><a href="http://www.eclipse.org/eclipselink/documentation/2.4/jpa/extensions/persistenceproperties_ref.htm">EclipseLink Properties</a></p>]]></content:encoded></item><item><title><![CDATA[Getting Started with JPA 2 Tutorial]]></title><description><![CDATA[<p>So, one of the most common comments I get to hear while at work almost every week regarding JPA is : "Oh I Just hate JPA!" . I never really had much of a problem with it, obviously sometimes with JPA something just doesn't want to work for some strange reason and</p>]]></description><link>http://blog.jbaysolutions.com/2011/09/10/jpa_getting_started_part1/</link><guid isPermaLink="false">dfc5994c-f350-448b-b8b9-a3ce1bc1ec25</guid><category><![CDATA[java]]></category><category><![CDATA[jpa]]></category><category><![CDATA[glassfish]]></category><category><![CDATA[j2ee]]></category><category><![CDATA[jdbc]]></category><category><![CDATA[eclipselink]]></category><category><![CDATA[mysql]]></category><dc:creator><![CDATA[Rui Pereira]]></dc:creator><pubDate>Sat, 10 Sep 2011 00:57:00 GMT</pubDate><content:encoded><![CDATA[<p>So, one of the most common comments I get to hear while at work almost every week regarding JPA is : "Oh I Just hate JPA!" . I never really had much of a problem with it, obviously sometimes with JPA something just doesn't want to work for some strange reason and the Logs don't really help finding the problem but most of the days everything works fine.</p>

<p>At some point I decided that I would write a few tutorials on JPA. Some time has passed since and now I'm actually doing it. Use the comments section for corrections if you find any problems or errors, or if you would just like to leave a kind word!</p>

<p>This is the first tutorial of (what I hope) a series of tutorials that focus on different parts of JPA, Entity Beans and related stuff. A few assumptions are made, like basic knowledge of SQL and relational databases, what an EJB is and where does it run, Unit Testing, an IDE is setup (like NetBeans) , a MySQL database is setup and basic knowledge on how to use it, and stuff like that.</p>

<p>This tutorial will serve as the setup for the following tutorials. It will provide background knowledge of what JPA is, what it does, how to create a basic Entity Beans to interact with the database, how to test these Beans, etc.</p>

<p><strong>Simply understanding some basic stuff that is explained here, such as Entity Lifecycle and Entity Manager contexts, will save a developer a lot of work when trying to write something more advanced!</strong></p>

<p>On the following tutorials more advanced topics such as relationships will be covered.</p>

<p>For this tutorial EclipseLink, JUnit and MySQL are needed, so if you are missing any of these this is the time to go and get them:</p>

<ul>
<li><p><a href="http://www.eclipse.org/eclipselink/downloads/">EclipseLink</a></p></li>
<li><p><a href="http://dev.mysql.com/downloads/mysql/"> MySQL</a></p></li>
<li><p><a href="https://github.com/KentBeck/junit/downloads">JUnit</a></p></li>
</ul>

<p>I'll also be using MySQL WorkBench to visually create the database structure, the IDE used is irrelevant since the tutorial will be more focused on the source code and basic knowledge side of things.</p>

<p>I also created a NetBeans Project with all the source code used on this Tutorial. You can <a href="http://www.2shared.com/file/aq-W_NM_/JPATutorialtar.html">Download it Here</a> but to properly use it you'll need to place the  EclipseLink Jars and MySQL connector Jar and Persistence Jar inside the correct Lib folder inside the project. You'll also have to add these libraries to the Testing Libraries of the project.</p>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br></p>

<h2 id="thedatabase">The Database</h2>

<p>So, lets start the show! The name of the schema to be used in MySQL is "mydb", but if you decide to use a different one just remember to change any reference to mydb in this tutorial to the name of your Schema. First let us start by creating the following table in MySQL:</p>

<p><a href="http://syshex.files.wordpress.com/2011/08/db011.png"><img src="http://syshex.files.wordpress.com/2011/08/db011.png?w=126" alt="" title=""></a></p>

<p>The SQL for that table is like so :</p>

<pre><code>CREATE TABLE IF NOT EXISTS `mydb`.`company` (
`idcompany` INT NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(45) NOT NULL ,
`country` VARCHAR(45) NOT NULL ,
`privat` TINYINT(1) NOT NULL DEFAULT 0 ,
`ownername` VARCHAR(45) NULL ,
`numberemployees` INT NOT NULL DEFAULT 0 ,
`income` DOUBLE NOT NULL DEFAULT 0.0 ,
PRIMARY KEY (`idcompany`) )
ENGINE = InnoDB;`&lt;/blockquote&gt;
</code></pre>

<p>This table has and ID column, which is auto incremental, a  few columns that are basic text, a column called privat that is a boolean and some ints and doubles.</p>

<h2 id="thepersistenceunit">The Persistence Unit</h2>

<p>Now inside the IDE configure a new project to use J2EE Persistence (JPA) and Enterprise JavaBeans. Inside the META-INF folder there should be a file called persistence.xml, if there is none then create one. It should look like this:</p>

<pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0"&gt;
    &lt;persistence-unit name="testPU" transaction-type="RESOURCE_LOCAL"&gt;
        &lt;provider&gt;org.eclipse.persistence.jpa.PersistenceProvider&lt;/provider&gt;
        &lt;exclude-unlisted-classes&gt;false&lt;/exclude-unlisted-classes&gt;
        &lt;properties&gt;
            &lt;property name="j**avax.persistence.jdbc.driver**" value="com.mysql.jdbc.Driver"/&gt;
            &lt;property name="**javax.persistence.jdbc.url**" value="jdbc:mysql://localhost:3306/mydb"/&gt;
            &lt;property name="**javax.persistence.jdbc.user**" value="root"/&gt;
            &lt;property name="**javax.persistence.jdbc.password**" value="root"/&gt;
        &lt;/properties&gt;
    &lt;/persistence-unit&gt;
&lt;/persistence&gt;
</code></pre>

<p>The persistence.xml file indicates that there is only one Persistence Unit, which we called testPU, the transaction type for this PU is RESOURCE_LOCAL. There are two valid types of transaction:</p>

<ul>
<li><p>JTA</p></li>
<li><p>RESOURCE_LOCAL</p></li>
</ul>

<p>What these options mean is: If one selects <strong>RESOURCE<em>LOCAL</em></strong> then the transactions will be managed by the JPA Provider Implementation in use. If <strong>JTA</strong> is specified then the transactions will be managed by the Application Server the application will run in. Another way of looking at this is that if one only wants to have JPA transactions then <strong>RESOURCELOCA</strong>L is a good choice. If one would like the transactions to contain other resources other than <strong>JPA</strong>, like EJBs, JCA or JMS then JTA is the correct choice.</p>

<p>When defining a Persistence Unit a list of Entity Beans to be managed can also be included, or one can simply do : <strong><exclude-unlisted-classes>false</exclude-unlisted-classes></strong>, which will make all Entity Beans in the archive managed by the PU.</p>

<p>The remaing properties in the PU are pretty straight forward to understand. Make them the configurations of your MySQL database and Schema. Other properties for EclipseLink can be found here: <a href="http://www.eclipse.org/eclipselink/documentation/2.4/jpa/extensions/persistenceproperties_ref.htm">Properties JPA2</a></p>

<h2 id="theentitybean">The Entity Bean</h2>

<p>An Entity Bean is a "lightweight persistent domain object" (JPA Sepc) , what this means is that an Entity object represents a set of attributes of an entry on the database.  It allows a developer to create, access and modify entries on a Database in an Object Oriented fashion like if they were simple POJOs.</p>

<p>The Entity Bean is therefore a Java Object that simply has to follow a few rules that are not that difficult. Our Entity Bean will be called CompanyEntity.Java , and it was created inside the package : com.jbaysolutions.testing.entity . Feel free to change it to a different package.</p>

<p>I've split the file in several sections here so that I can go through and explain what is going in each section. The complete file can be found <a href="http://blog.jbaysolutions.com/jpa-tutorial-1-entity-bean">here</a>.</p>

<p>The first part of the file goes like so :</p>

<pre><code> package com.jbaysolutions.testing.entity;
 import javax.persistence.*;
 import java.io.Serializable;

 @Entity
 @Table(name = "company")
 public class CompanyEntity implements Serializable {
</code></pre>

<h3 id="entity">@Entity</h3>

<p>A Java object, to be considered an Entity Bean must have the Entity annotation ( @Entity ) on the class or be denoted on the ejb-jar.xml file. In our example we use the @Entity annotation.  This annotation and the remaining ones that characterise an Entity Bean can be found inside the javax.persistence package.</p>

<p>Also, an Entity Bean must be a top level class, it must not be final, nor the persistent elements that it contains.</p>

<h3 id="table">@Table</h3>

<p>The @Table annotation is used to specify which table, from which catalogue and which schema this Entity Bean is representing. In this case we simply use the name attribute to define the table name.</p>

<p>The Entity Bean can also be Serializable, which is very handy when there is the need to pass this object somewhere else, like for example as the return of a web service method or EJB.</p>

<p>The next bit of the class looks like this :</p>

<pre><code>     @Id
     @GeneratedValue(strategy = GenerationType.IDENTITY)
     @Column(name = "idcompany")
     private Integer idcompany;
</code></pre>

<h3 id="id">@Id</h3>

<p>In this section an attribute called idcompany is defined as an Integer object which is the Primary Key of the created table. We use the @Id annotation to identify this attribute as the ID of the Entity Bean. An Entity Bean MUST have an Id, which can be a single attribute or several attributes ( composite primary key). The Id of the Entity Bea MUST be serializable.</p>

<p>So this ID will be used by Entity Manager to uniquely identify the entity in its persistence context. It is also a part of the JPA spec that an Application MUST NOT modify the value of the Primary Key or any of the values of a Composite Primary Key. It states that the behaviour is undefined if this occurs, which basically means that it might work but if the JPA provider is changed then the behaviour might not be the same across all Providers and therefore the application behaviour might change. In other words: Don't do it!</p>

<p>Composite Primary Keys will be explained in a later tutorial.</p>

<h3 id="generatedvalue">@GeneratedValue</h3>

<p>This annotation provides the strategy to be used for the generation of the Id attributes of the Entity Bean. It is implementation specific and its behaviour is not defined on the specification. There are 4 possible choices :</p>

<ul>
<li><p>auto</p></li>
<li><p>identity</p></li>
<li><p>table</p></li>
<li><p>sequence</p></li>
</ul>

<p>For this example we are using IDENTITY due to the fact that MySQL supports identity columns. If we were using Oracle which supports Sequence objects, we would be using the SEQUENCE choice and would define which sequence was to be used for the generation of the Ids. The TABLE option can be used in any kind of database and means that JPA will use another table for the Ids to be used, the new table will have a column of the same type the Id has and each row will correspond to a specific Id on the original table.</p>

<p>Option AUTO will make JPA decide itself what is the best strategy to use, in case of EclipseLink the default choice will be TABLE.</p>

<h3 id="column">@Column</h3>

<p>The @Column annotation informs JPA which column this attribute corresponds to and other constraints of the attribute such has length and precision. If the name of the column is the same as the name of the attribute then there is no need to specify the "name" property of the annotation.</p>

<p>The next section of code is the definition of the remaining columns:</p>

<pre><code>     @Column(name = "name")
     @Basic(optional = false)
     private String name;

     @Column(name = "country")
     @Basic(optional = false)
     private String country;

     @Column(name = "privat")
     @Basic(optional = false)
     private Boolean privat = false;

     @Column(name = "ownername")
     @Basic(optional = true)
     private String ownerName;

     @Column(name = "numberemployees")
     @Basic(optional = false)
     private int numberEmployees = 0;

     @Column(name = "income")
     @Basic(optional = false)
     private double income = 0.0;
</code></pre>

<h3 id="basic">@Basic</h3>

<p>The Basic annotation can be applied to any persistent attribute of the Entity Bean as long as it is a primitive, a primitive wrapper or Serializable object. It is optional and cannot be used for Id attributes. Through the use of @Basic annotation we can specify the type of fetch to be used and whether the attribute is optional or not.</p>

<p>The next section of code is concerning the Constructors of the Entity Bean:</p>

<pre><code>     public CompanyEntity() {
     }

     public CompanyEntity(String name,
                          String country,
                          Boolean privat,
                          String ownerName,
                          int numberEmployees,
                          double income) {
         this.name = name;
         this.country = country;
         this.privat = privat;
         this.ownerName = ownerName;
         this.numberEmployees = numberEmployees;
         this.income = income;
     }
</code></pre>

<h3 id="entitybeanconstructors">Entity Bean Constructors</h3>

<p>According to the JPA Specification the Entity Bean must have a no-args constructor defined. It can have many other constructors, but the no-args must be defined and must be either Public or Protected. In our example we have two, for no particular reason.</p>

<p>The remaining definition of the Entity Bean is basically following the Javabeans conventions for the getter and setter methods for the attributes.</p>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br></p>

<h1 id="testingtheentitybean">Testing the Entity Bean</h1>

<p>Usually all operations regarding the Entity Beans would be performed inside some EJB that would take care of all the business logic and persistence related parts. That will be covered in the next tutorial. In this one we'll be using JUnit testing, which is a good practice, specially for later once this exercise gets expanded to make use of EJBs.</p>

<p>So by using a JUnit test class all operations can be simulated with the Entity Bean that was just created. The JUnit class that we'll use can be found <a href="http://blog.jbaysolutions.com/jpa-tutorial-1-junit-class">here</a> and I'll go through it section by section and explain what is happening.</p>

<pre><code> public class CompanyEntityTest {

     private static EntityManager em = null;

     @BeforeClass
     public static void setUpClass() throws Exception {
         if (em == null) {
             em = (EntityManager) Persistence.
                       createEntityManagerFactory("testPU").
                       createEntityManager();
         }
     }
</code></pre>

<p>This first section of the JUnit basically performs the setup of the Entity Manager that will be used for the remaining parts of the Class.  The @BeforeClass annotation basically means that this method will be run once before any of the test methods of the Class. The test methods will be marked with the @Test annotation, as you will see next. More information regarding @BeforeClass can be found <a href="http://junit.sourceforge.net/javadoc/org/junit/BeforeClass.html">Here</a> and it is beyond the scope of this tutorial.</p>

<p>Inside this method the Entity Manager object is created using a Factory. This factory takes as an argument the name of the Persistence Unit that is to be used. Since we only have one created on the persistence.xml file, we'll use that one.</p>

<pre><code> @Test
 public void testAllOps(){
     // Start a transaction
     em.getTransaction().begin();

     // ------------  Create a Company C1 ---------
     CompanyEntity c1 = new CompanyEntity();
     c1.setCountry("Portugal");
     c1.setIncome(1000000.00);
     c1.setName("JBay");
     c1.setNumberEmployees(200);
     c1.setOwnerName("The Dude");
     c1.setPrivat(true);
     // At this Point the Entity does not have a
     // Persistent Identity and is not associated
     // with a persistent Context
     em.persist(c1); // Persist the Entity
     em.flush();
     // At this point the Entity has a Persistent
     // Identity and is associated with a Persistent
     // context.

     // ------------  Create a Company C2 ---------
     CompanyEntity c2 = new CompanyEntity();
     c2.setCountry("US");
     c2.setIncome(1000000000.00);
     c2.setName("Oracle");
     c2.setNumberEmployees(9000);
     c2.setOwnerName("Who?");
     c2.setPrivat(true);
     em.persist(c2);
     em.flush();

     System.out.println("Company 1 Id : " + c1.getIdcompany());
     System.out.println("Company 2 Id : " + c2.getIdcompany());
</code></pre>

<p>The method testAllOps is the one that will be used to test all the operations. It is marked with @<strong>Test</strong> which means that it will get executed after @<strong>BeforeClass</strong> which then means that the EntityManager object "em" is already instantiated and ready for usage. Because the Persistence Unit that we are using is using transaction type <strong>RESOURCE_LOCAL</strong> we begin a transaction first of all, if it was of the type <strong>JTA</strong> it would throw an exception if we tried to manage the transaction like that.</p>

<p>At this point we should look at the Entity Bean Lifecycle.</p>

<h2 id="entitylifecyclenewentity">Entity Lifecycle - New Entity</h2>

<p>We then create a new Instance of the Entity Bean CompanyEntity which we call "c1".  Because when we create this new object c1 it does not contain an identity this Entity Bean is said to be "<strong>new</strong>".  Object c1 is then given a set of values for its attributes except for the Primary Key attribute.</p>

<h2 id="entitylifecyclemanagedentity">Entity Lifecycle - Managed Entity</h2>

<p>The Entity Manager "em" is then used to persist this object on the database. The method to be used is <strong>persist</strong>(T). If the method <strong>merge</strong>(T) would be used it would be incorrect because this method is used for update operations and not create operations. Calling the persist() method makes this Entity Bean c1 "<strong>managed</strong>" and associated with this persistence context.</p>

<p>The method <em>* flush()</em>* is called simply to synchronise the data of the Entity Bean with the database system. According to the JPA Spec the persistence provider is allowed to sync to the database system at other times other than when <strong>flush()</strong> is called but calling it ensures that the synchronisation happened at this point.</p>

<h2 id="entitylifecycleremovedentity">Entity Lifecycle - Removed Entity</h2>

<p>The Entity Manager has a method called remove(T), this method is used to remove the entry related to the Id of that entity from the underlining database system. At this point, after the remove method was called on a Managed Entity Bean, that Entity Bean is said to be "<strong>removed</strong>".</p>

<p>The state of the object itself is exactly the same as before the remove method was called, with the difference that that entity no longer is associated with the persistence context of the Entity Manager and does not represent any entry on the database.</p>

<h2 id="entitylifecycledetachedentity">Entity Lifecycle - Detached Entity</h2>

<p>A Detached Entity is an Entity that is not associated with a persistence context. It is a necessary thing for several operations and can happen in several ways, the most common ones being from detaching the entity from the persistence context and from serializing an entity or otherwise passing an entity by value.</p>

<p>To detach an Entity from a persistence context the method  <strong>detach()</strong> can be used on that Entity. Before doing so one must <strong>flush()</strong> the entity to ensure that changes are persisted. Associated Entities with the detached Entity are also detached is the relationship is marked with Cascade=DETACH or Cascade=ALL. The Cascade attribute will be addressed on a later tutorial when relationships between entities are covered.</p>

<p>If an Entity is new or already detached invoking <strong>detach()</strong> with produce no result.</p>

<p>There are several other nuances with Detached entities, specially regarding merging of a detached entity onto an existing persistence context. These are addressed on a later tutorial.</p>

<p>The next section of the JUnit file shows two searchs being performed on the persistence context:</p>

<pre><code> Query query = em.createQuery("Select c from CompanyEntity c where c.idcompany=:companyid");
 query.setParameter("companyid", c1.getIdcompany());
 CompanyEntity retrieved1 = (CompanyEntity) query.getSingleResult();
 assertSame(c1, retrieved1);

 query.setParameter("companyid", c2.getIdcompany());
 CompanyEntity retrieved2 = (CompanyEntity) query.getSingleResult();
 assertSame(c2,retrieved2);

 assertNotSame(c1,c2);
 assertNotSame(retrieved1,retrieved2);
</code></pre>

<p>The Query object on the above example is created using JPQL. There are other ways to create queries such as using a named query, which is a query that is defined on an Entity Bean and also queries can be created using native SQL language. In the example we use JPQL which stands for JPA Query Language, which is considered to be an Object oriented version on SQL. The example query has a Parameter called  :companyid which is set using the <strong>setParameter()</strong> method of the Query object.</p>

<p>The <strong>getSingleResult()</strong> method returns the unique object that matches the query. If no result is found a <strong>NoResultException</strong> is thrown. This exception does not mark the transaction for rollback. If more than one result matches the query then a <strong>NonUniqueResultException</strong> is thrown. This exception also does not mark the transaction for rollback.</p>

<p>Using the <strong>assertSame()</strong> method of the JUnit framework we verify that C1 and Retrieved1 are the same and also that C2 and Retrieved2 are the same. <strong>It is of crucial importance to understand this!</strong> According to the JPA2 Spec:</p>

<blockquote>
  <p><strong>An EntityManager instance is associated with a persistence context. A persistence context is a set of entity instances in which for any persistent entity identity there is a unique entity instance</strong></p>
</blockquote>

<p>What this means is that there is only one copy of an Entity Bean object for each Identity inside a persistence context. So, inside a persistence context if we were to call the getSingleResult() method several times and assign its result to different variables, these would all be references to the exact same object and not different copies of similar objects.</p>

<p>One could test this by simply modifying the CompanyEntity object with :</p>

<pre><code> @Transient
 int random = new Random().nextInt();

 public int getRandom() {
     return random;
 }
</code></pre>

<p>This will generate a random integer for each Entity Object that gets created. Now, performing getSingleResult() for the same query with the same parameters on the JUnit test class assigning the result to different variables and calling getRandom() on all of those references will return the same int value, which shows that the Object is the same or that we got extremely lucky (not likely... but try it a few time to be sure).  This test could also be done by calling the <strong>hashCode()</strong> method of each object obviously and verifying that they all have the same hashcode but that would prevent the introduction of the <strong>@Transient</strong> annotation.</p>

<h2 id="transient">@Transient</h2>

<p>The @Transient annotation is similar to the transient keyword in Java, in the sense that transient keyword means that an attribute of a class is not to be serializable, the @Transient annotation in JPA means that the Attribute is not to be persisted. Attributes annotated with @Transient are ignored by the Entity Manager and are not persisted on the Database system.</p>

<p>The remaining of the JUnit test class demonstrates the remaining operations already mentioned on this tutorial, such as updating of entries:</p>

<pre><code> c2.setOwnerName("No One");
 c2.setPrivat(false);
 em.merge(c2);
 em.flush();

 System.out.println("Company 2 Id : " + c2.getIdcompany());
 System.out.println("Company 2 Name : " + c2.getName());
 System.out.println("Company 2 Owner : " + c2.getOwnerName());
 System.out.println("Company 2 Private : " + retrieved2.getPrivat());
</code></pre>

<p>And also deleting of entries:</p>

<pre><code> em.remove(c1);
 em.remove(c2);
 // Both c1 c2 (and obviously retrieved1 and retrieved2) are removed,
 // which will happen upon commit of the Transaction
 em.getTransaction().commit();
</code></pre>

<h1 id="references">References</h1>

<p><a href="http://download.oracle.com/auth/otn-pub/jcp/persistence-2.0-fr-eval-oth-JSpec/persistence-2_0-final-spec.pdf">Java Persistence Api 2 Specification </a></p>

<p><a href="http://www.eclipse.org/eclipselink/documentation/2.4/jpa/extensions/persistenceproperties_ref.htm">EclipseLink Properties</a></p>

<script type="text/javascript">  
    google_ad_client = "ca-pub-1311169549359552";
    google_ad_slot = "4687300627";
    google_ad_width = 728;
    google_ad_height = 90;
</script>  

<!-- Test Add Unit -->  

<script type="text/javascript" src="//pagead2.googlesyndication.com/pagead/show_ads.js">  
</script>]]></content:encoded></item></channel></rss>