<?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[jpa - 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/jpa/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[JPA 2 Tutorial - Queries with JPQL]]></title><description><![CDATA[<p>If you are following the tutorials here you must be dying to do some queries using JPA. So, before we go any further into other aspects of JPA, lets query the model! For this task, instead of using SQL we will be using the <strong>Java Persistence Query Language</strong> or also</p>]]></description><link>http://blog.jbaysolutions.com/2014/10/16/jpa-2-tutorial-queries-on-the-model/</link><guid isPermaLink="false">d2a1755a-9d21-4c5c-889b-2ef3b09f19ee</guid><category><![CDATA[java]]></category><category><![CDATA[jpa]]></category><category><![CDATA[eclipselink]]></category><category><![CDATA[mysql]]></category><category><![CDATA[jpql]]></category><dc:creator><![CDATA[Rui Pereira]]></dc:creator><pubDate>Thu, 16 Oct 2014 13:17:09 GMT</pubDate><content:encoded><![CDATA[<p>If you are following the tutorials here you must be dying to do some queries using JPA. So, before we go any further into other aspects of JPA, lets query the model! For this task, instead of using SQL we will be using the <strong>Java Persistence Query Language</strong> or also known as <strong>JPQL</strong>. Exciting, yes?</p>

<h3 id="sampleproject">Sample Project</h3>

<p>About the sample project provided: it is a Maven project, we do not require an App Server at this point and the database used is a MySQL database. Check the <a href="http://blog.jbaysolutions.com/jpa2-tutorials">JPA2 Tutorials</a> page for links of recommended software.</p>

<p>You can get the project at <a href="https://github.com/jbaysolutions/jpa2tut-queries">GitHub</a>.</p>

<h1 id="whatisandwhyusejpql">What is and Why use JPQL?</h1>

<p>Before going into what is <strong>JPQL</strong>, lets talk about <strong>SQL</strong>. SQL is a query language used for managing data in a relational database. It an <strong>ANSI</strong> and <strong>ISO standard</strong>, but if you try running a medium to high complexity SQL query in two different relational databases from two different vendors, you are in for a big surprise. Why is that? Because some vendors create specific dialects of the SQL language.</p>

<p>Now imagine for a second you have a big application that you just developed and deployed, which is using a specific relational database, and for some reason you decide to migrate your data to another relational database from a different vendor. Well, if you wrote your queries in SQL, you are well advised to go and double check all of your queries for correctness against the new dialect. </p>

<p><strong>JPQL</strong> to the rescue. <strong>JPQL</strong> is a query language, much like <strong>SQL</strong> (<em>syntax wise and all that</em>), but instead of querying over a relational database, it queries over the persistent schema of entities and relationships (<em>which is almost the same thing, but not quite!</em>). What this means is that, if the relational model of the new database is still represented by the schema of entities and relationships you have on your project, then your JPQL queries will be portable and will work as expected. Emphasys on <strong>Portability</strong>.</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="selectstatements">Select Statements</h1>

<p>For our tutorial we'll use the model created for the <a href="http://blog.jbaysolutions.com/2011/09/19/jpa-2-relationships-onetomany/">One-To-Many Tutorial</a> but we will extend it a bit more:</p>

<p><img src="http://blog.jbaysolutions.com/content/images/2014/10/overview-2.png" alt="Database model"></p>

<p>You can get the MySQL Workbench file for this from the <em>model</em> folder of the sample project. Along with the Workbench file there is a <strong>SQL script</strong> that creates the model and adds a few entries to it so we can test our queries:</p>

<pre><code>INSERT INTO `jpa2tut-queries`.`company` (`name`, `address`, `created_year`) VALUES ('JBay Solutions', 'Somewhere in Portugal', 2009);
INSERT INTO `jpa2tut-queries`.`company` (`name`, `address`, `created_year`) VALUES ('JetBrains', 'Somewhere in Prague', 2000);
INSERT INTO `jpa2tut-queries`.`company` (`name`, `address`, `created_year`) VALUES ('Google', 'Somewhere in the US', 1998);
INSERT INTO `jpa2tut-queries`.`company` (`name`, `address`, `created_year`) VALUES ('Yahoo', 'Somewhere in the US',1994);
INSERT INTO `jpa2tut-queries`.`company` (`name`, `address`, `created_year`) VALUES ('MySQL', 'Somewhere in an Oracle Office', 1995);
</code></pre>

<p>Also, check the <strong>src/main/java</strong> folder of the project in order to check the Entity Objects we have. An understanding of these objects is core to understanding the <strong>JPQL</strong> code we will write next. </p>

<h2 id="asimpleselect">A Simple Select</h2>

<p>As you can see from the previous <strong>SQL</strong> bits, we have a few entries on the <em>company</em> table. Lets query for the list of those entries:</p>

<pre><code><b>SELECT</b> c <b>FROM</b> CompanyEntity <b>AS</b> c
</code></pre>

<p>At this point you should be going like: <em>Wait a second please... I understand this language!</em>. Like said before, JPQL is very much like the regular SQL, except that we perform queries on the <em>persistent schema of entities and relationships</em>. </p>

<p>Lets run this in Java. Check the files inside the <strong>src/test/java</strong> folder of the sample project. You should be looking for the <strong>QueryTesting.java</strong> file at the method <strong>testSimpleQuery</strong>:</p>

<pre><code>Query query = em.createQuery("<b>SELECT</b> c <b>FROM</b> CompanyEntity <b>AS</b> c");
for ( CompanyEntity ce : (List&lt;CompanyEntity&gt;)query.getResultList()) {
    System.out.println(" -> Company : " + ce.getName() );
}
</code></pre>

<p>We give it a run:  </p>

<pre><code>[...]
[EL Info]: connection: 2014-10-14 16:41:13.476 --ServerSession(1563886825)--file:/home/rui/projects/jpa2tut-queries/target/test-classes/_jpa2tut-test login successful
 -> Company : JBay Solutions
 -> Company : JetBrains
 -> Company : Google
 -> Company : Yahoo
 -> Company : MySQL
</code></pre>

<p>Simple, yes? We create a <strong><em>Query</em></strong> Object with the JPQL query and we call <strong><em>em.getResultList();</em></strong> . We cast the result to <strong><em>List&lt;CompanyEntity&gt;</em></strong> , because we know that <strong><em>getResultList()</em></strong> returns a <em>List</em> (it does) and we also know that the query we created returns objects of <strong><em>CompanyEntity</em></strong> type.</p>

<p>We can also restrict the number of results being returned from the Query, by modifying the JPQL query used. Imagine we want to return all the companies that are called "<strong>JBay Solutions</strong>":</p>

<pre><code>SELECT c FROM CompanyEntity AS c <b>WHERE</b> c.name='JBay Solutions'
</code></pre>

<p>And the code being (<em>testSimpleQueryWhere method</em>) :  </p>

<pre><code>Query query = em.createQuery("SELECT c FROM CompanyEntity AS c <b>WHERE c.name='JBay Solutions'</b>");
for ( CompanyEntity ce : (List&lt;CompanyEntity&gt;)query.getResultList()) {
    System.out.println(" -> Company : " + ce.getName() );
}
</code></pre>

<p>Give it a quick spin:</p>

<pre><code>[EL Info]: connection: 2014-10-14 16:54:56.972--ServerSession(1861307614)--file:/home/rui/projects/jpa2tut-queries/target/test-classes/_jpa2tut-test login successful
 -> Company : JBay Solutions

Process finished with exit code 0
</code></pre>

<p>At this point one should be able to make pretty simple, but very useful queries, but some issues stand out:</p>

<ul>
<li>We must be constantly <strong>casting the results</strong></li>
<li>All our queries until now <strong>allow no input</strong></li>
</ul>

<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="entertypedquery">Enter TypedQuery</h2>

<p>In JPA2 a new type of Query object was introduced. The <strong>TypedQuery</strong>, which allows us to make a Query that is <em>Typed</em>. That is it, <em>TypedQuery extends Query</em>, allowing one to define straight away what is to be returned and avoid continuously Casting every single result. </p>

<p>Looking at our previous examples, we can modify them to use <strong>TypedQuery</strong> instead of <strong>Query</strong> by using an overloaded <strong><em>createQuery method</em></strong> from the <strong>EntityManager</strong> that also takes as a parameter the Type of the query result:</p>

<pre><code><b>TypedQuery&lt;CompanyEntity&gt;</b> query = em.createQuery("SELECT c FROM CompanyEntity AS c"<b>, CompanyEntity.class</b>);

<b>TypedQuery&lt;CompanyEntity&gt;</b> query = em.createQuery("SELECT c FROM CompanyEntity AS c WHERE c.name='JBay Solutions'"<b>, CompanyEntity.class</b>);
</code></pre>

<p>to perform the iteration now we do:  </p>

<pre><code>for (CompanyEntity ce : query.getResultList()) {
    System.out.println(" -> Company : " + ce.getName());
}
</code></pre>

<p>No casting, no nothing. For the complete code check both <em>testSimpleTypedQuery</em> and <em>testSimpleTypedQueryWhere</em> methods of the <em>QueryTesting.java</em> file on the test sources.</p>

<p>We still have the <strong>no input</strong> issue to work on. </p>

<h2 id="passinginputtothequeries">Passing Input to the Queries</h2>

<p>In a way, some examples we shown before could be easily modified in a way to allow inputs to be passed onto them. Check this out: </p>

<pre><code>String <b>inputName</b> = "JBay Solutions"; 
TypedQuery&lt;CompanyEntity&gt; query = em.createQuery("SELECT c FROM CompanyEntity AS c WHERE c.name='" + <b>inputName</b> + "'", CompanyEntity.class);
</code></pre>

<p>Can you spot the problem with this? Well, simple, if you want to perform this query several times with different inputs, then you need to continuously re-create a new Query object. Not counting the <strong>performance impact</strong> it will have, it also <strong>leads to the JPQL not being readable at all</strong>. Imagine a query like the one presented but with several <em>conditional expressions</em> on the <em>WHERE clause</em>. What a nightmare. </p>

<p>To avoid these situations we have in JPQL:</p>

<ul>
<li><strong>Named Parameters</strong></li>
<li><strong>Positional Paramenters</strong></li>
</ul>

<p>Constructing a Query with any of these types of dynamic parameters allows a Query to be reused (and therefore avoid constant instantiation of Query objects) and makes the JPQL query much more readable.</p>

<h3 id="namedparameters">Named Parameters</h3>

<p>Lets look at the following example (from <em>testSimpleTypedQueryWhereInputNamed</em> method):</p>

<pre><code>em.createQuery("SELECT c FROM CompanyEntity AS c WHERE <b>c.name=:nameParam</b>", CompanyEntity.class);
query.setParameter("<b>nameParam</b>", "JBay Solutions");
</code></pre>

<p>So, a named parameter is a parameter that is called out by name. It is defined using the <strong>:&lt; param_name ></strong> notation:</p>

<ul>
<li>They are defined using the "<strong>:</strong>" prefix</li>
<li>They are Case Sensitive</li>
<li><strong>$</strong> and <strong>_</strong> chars are allowed, </li>
<li><strong>?</strong> is not allowed.</li>
<li>They can be used more than once on the Query string</li>
<li>They must be SET to something on execution</li>
<li>There is a list of reserved identifiers that cannot be used. Some of these reserved identifiers are : <strong>SELECT</strong> , <strong>WHERE</strong>, <strong>GROUP</strong>, <strong>TRUE</strong>, and many more, but you get the gist. <strong><em>These reserved identifiers are case insensitive</em></strong>, and non can be used as a named parameter. </li>
</ul>

<p>The named parameters are then set on the Query using the <em>setParameter</em> method of the Query instance:</p>

<pre><code><b>query.setParameter</b>("<b>nameParam</b>", "JBay Solutions");
for (CompanyEntity ce : query.getResultList()) {
    System.out.println(" -> Company : " + ce.getName());
}
<b>query.setParameter</b>("<b>nameParam</b>", "Google");
for (CompanyEntity ce : query.getResultList()) {
    System.out.println(" -> Company : " + ce.getName());
}</code></pre>

<p>What happens if you don't set one of the parameters? You get an IllegalStateException:</p>

<pre><code>[...]
[EL Info]: connection: 2014-10-14 18:30:02.302--ServerSession(822392390)--file:/home/rui/projects/jpa2tut-queries/target/test-classes/_jpa2tut-test login successful

<b>java.lang.IllegalStateException</b>: Query argument nameParam not found in the list of parameters provided during query execution.
    at org.eclipse.persistence.internal.jpa.QueryImpl.processParameters(QueryImpl.java:498)
    [...]
</code></pre>

<h3 id="positionalparameter">Positional Parameter</h3>

<p>Lets look at the following example (from <em>testSimpleTypedQueryWhereInputNumbered</em> method):</p>

<pre><code>em.createQuery("SELECT c FROM CompanyEntity AS c WHERE <b>c.name=?1</b>", CompanyEntity.class);
query.setParameter(<b>1</b>, "JBay Solutions");
</code></pre>

<p>A positional parameter is defined using the <strong>?&lt; int ></strong> notation:</p>

<ul>
<li>The parameters are numbered starting with <b>1</b></li>
<li>Positional parameter can appear more than once in the Query string.</li>
<li>The order by which they are set is irrelevant</li>
</ul>

<p>So:</p>

<pre><code>query.setParameter(1, "JBay Solutions");
query.setParameter(2, "Google");
</code></pre>

<p>will return the same  as:</p>

<pre><code>query.setParameter(2, "Google");
query.setParameter(1, "JBay Solutions");
</code></pre>

<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="usingmultipleentities">Using Multiple Entities</h1>

<p>Right, making JPQL queries that take into account several Entities is the next logical step. For that, take into account the following SQL script (that is part of the <strong><em>create-and-populate.sql</em></strong> file of the sample project):</p>

<pre><code>INSERT INTO `jpa2tut-queries`.`employee` (`name`, `address`, `idcompany`, `birthday`) VALUES ('Rui Pereira', 'Lisbon',1 , '1981-06-27' );
INSERT INTO `jpa2tut-queries`.`employee` (`name`, `address`, `idcompany`, `birthday`) VALUES ('Gustavo Santo', 'Peniche',1, '1979-12-19');
INSERT INTO `jpa2tut-queries`.`employee` (`name`, `address`, `idcompany`, `birthday`) VALUES ('Maxim Shafirov', 'St.Petersburg, Russia',2, '1970-06-01');
INSERT INTO `jpa2tut-queries`.`employee` (`name`, `address`, `idcompany`, `birthday`) VALUES ('Valentin Kipiatkov', 'St.Petersburg, Russia',2, '1975-06-01');
<i>[... many more entries]</i>
</code></pre>

<p>This simply adds a few Employees to the previously created Companies. Now we have <strong>JBay Solutions</strong> with two employees and <strong>JetBrains</strong> with also two employees, and the remaining companies with also two employess (<em>check file for the remaining entries</em>).</p>

<p>Lets create a JPQL query that returns the employees of a particular company:</p>

<pre><code>TypedQuery&lt;EmployeeEntity&gt; query =
    em.createQuery("SELECT employee FROM <b>CompanyEntity AS company</b>, <b>EmployeeEntity as employee</b> " +
    "WHERE <b>company.name=:name</b> " +
    "<b>AND employee.company = company</b>", EmployeeEntity.class);
</code></pre>

<p>Pretty simple, yes? </p>

<ul>
<li>On the <strong>FROM</strong> clause we define <strong>two Entities</strong> with <strong>two Identifiers</strong></li>
<li>we make use of a <strong>named parameter</strong></li>
<li>we make use of the <strong>AND logical operator</strong></li>
</ul>

<p>Remember we said that <em>JPQL perform queries on the persistent schema of entities and relationships</em>. EmployeeEntity has a <strong>ManyToOne Relationship</strong> defined to CompanyEntity, and therefore we can use that relationship in our JPQL queries. The relationship is defined like this:</p>

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

<p>Therefore when we in JPQL do something like <code>employee.company = SOMETHING</code>, we call <code>employee.company</code> a <strong>Path Expression</strong>, and the result for this case should be pretty obvious, because the relationship maps to only one other Entity. We'll talk a bit more about <strong>Path Expressions</strong> in a bit.</p>

<p>Lets give a run at <em>testMultipleEntities1</em> method on the <em>QueryTesting.java</em>, which runs this query like this:</p>

<pre><code>query.setParameter("name", "JBay Solutions");
for (EmployeeEntity client : query.getResultList()) {
    System.out.println(" -&gt; Q1 : " + client.getName());
}

query.setParameter("name", "JetBrains");
for (EmployeeEntity client : query.getResultList()) {
    System.out.println(" -&gt; Q2 : " + client.getName());
}
</code></pre>

<p>And check the results:</p>

<pre><code>[EL Info]: connection: 2014-10-14 20:58:59.383--ServerSession(1268465323)--file:/home/rui/projects/jpa2tut-queries/target/test-classes/_jpa2tut-test login successful
 -&gt; Q1 : Rui Pereira
 -&gt; Q1 : Gustavo Santo
 -&gt; Q2 : Maxim Shafirov
 -&gt; Q2 : Valentin Kipiatkov
</code></pre>

<p>Perfect!</p>

<p>Now, on the other side of the relationship, we'll have a <strong>OneToMany Relationship</strong>, like this:</p>

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

<p>And using that collection there on a JPQL query is also possible, but not as shown before. When we write something like this <code>AND employee.company = company</code> , the <code>employee.company</code> part as we said before is called a <strong>Path Expression</strong>, and one of the rules of <strong>Path Expressions</strong> is that it cannot be created from another <strong>Path Expression</strong> that evaluates to a collection. Lost you all there? In order words, check this next example.</p>

<p>Take this bit of code <code>FROM EmployeeEntity as employee</code> , we could create these <strong>Path Expressions</strong> :</p>

<ul>
<li><strong>employee.name</strong> : <em>Evaluates to a String</em></li>
<li><strong>employee.id</strong> : <em>Evaluates to an int</em></li>
<li><strong>employee.address</strong> : <em>Evaluates to a String</em></li>
<li><strong>employee.company</strong> : <em>Evaluates to a Company object</em></li>
<li><strong>employee.company.id</strong> : <em>Evaluates to an int</em></li>
<li><strong>employee.company.name</strong> : <em>Evaluates to a String</em></li>
<li><strong>employee.company.address</strong> : <em>Evaluates to a String</em></li>
<li><strong>employee.company.employeeCollection</strong> : <em>Evaluates to a Collection</em></li>
</ul>

<p>So you see, we created <strong>Path Expressions</strong> from other path expression in the way that <code>employee.company.id</code> is created from the <code>employee.company</code> <strong>Path Expression</strong>. </p>

<p>Since we have that rule of not being able to create from <strong>Path Expressions</strong> that evaluate to Collections, we can't do the following :</p>

<ul>
<li><strong>employee.company.employeeCollection.id</strong> : <em>Illegal</em></li>
<li><strong>employee.company.employeeCollection.name</strong> : <em>Illegal</em></li>
<li><strong>employee.company.employeeCollection.address</strong> : <em>Illegal</em></li>
<li><strong>employee.company.employeeCollection.company</strong> : <em>Illegal</em></li>
</ul>

<p>But <strong>Path Expressions</strong> that evaluate to Collections can be very useful in other ways. Lets give it another try at writting a JPQL query that makes use of this to achieve that same goal as the previous one:</p>

<pre><code>TypedQuery&lt;EmployeeEntity&gt; query =
    em.createQuery("SELECT employee FROM <b>CompanyEntity AS company</b>, <b>EmployeeEntity as employee</b> " +
    "WHERE <b>company.name</b>=<b>:name</b> " +
    "AND <b>employee MEMBER OF company.employeeCollection</b> ", EmployeeEntity.class);
</code></pre>

<p>See what we did there?</p>

<ul>
<li>we made use of the <strong>MEMBER OF comparison operator</strong></li>
<li>and we have a working knowledge of what is a <strong>Path Expression</strong></li>
</ul>

<p>There are a few more rules regarding <strong>Path Expressions</strong>, but a working knowledge is quite enough. If you feel you must know these right now, please check the JPA 2 Final Spec, which can be found at the bottom of this post in the References section. </p>

<p>About the <strong>MEMBER OF comparison operator</strong>, there are quite a few comparison operators, like <strong>BETWEEN</strong>, <strong>IN</strong> , <strong>EMPTY</strong>, <strong>EXISTS</strong>, <strong>LIKE</strong>, <strong>IS NULL</strong> and your well known <strong>=</strong> , <strong>></strong>, <strong>&lt;</strong>, <strong>&lt;></strong>, <strong>&lt;=</strong>, and <strong>>=</strong> .</p>

<h2 id="thememberofoperator">The MEMBER OF operator</h2>

<p>The <strong>MEMBER OF</strong> operator is used to match or <strong>NOT</strong> the existence of <em>something</em> in a <em>Collection</em>. An example if we may :</p>

<pre><code><i>employee</i> <b>MEMBER OF</b> <i>company.employeeCollection</i>
</code></pre>

<p>The <em>employee</em> section is a <em>path expression</em> that evaluates to an entity. It could evaluate to a simple value (like for example <code>employee.id</code> does) or an object (like <code>employee.company</code>), these are allowed. </p>

<p>The <em>company.employeeCollection</em> section is a <em>path expression</em> that will evaluate to a Collection of Employees. That is it.</p>

<p>To match the inexistence of <em>something</em> inside a <em>Collection</em>, we can use the <strong>NOT MEMBER OF</strong>, like this:</p>

<pre><code><i>employee</i> <b>NOT MEMBER OF</b> <i>company.employeeCollection</i>
</code></pre>

<p>The <strong>NOT</strong> is a constant in the remaing comparison operators, like we will see next. </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="thebetweenoperator">The BETWEEN operator</h2>

<p>Lets shift our focus now to the <em>Company</em> table and <em>CompanyEntity</em> bean. There is a field there that stores the year the Company was created. It is mapped as an Integer and cannot be Null. </p>

<p>For our next task we will write a JPQL query that will return the Companies that were created in 1995 or after and in 2005 or before:</p>

<pre><code>em.createQuery("SELECT company FROM CompanyEntity AS company " +
"WHERE company.<b>createdYear >= 1995</b> " +
"AND company.<b>createdYear <= 2005<="" b=""> ", CompanyEntity.class);
</=></b></code></pre>

<p>Easy, yes? But we could use the <strong>BETWEEN</strong> operator in the following way:</p>

<pre><code>"WHERE company.createdYear <b>BETWEEN</b> 1995 AND 2005 "</code></pre>

<p>Which will return the exact same result. <br>
Expanding on what we already know, we could actually just replace both the <strong>MIN</strong> and <strong>MAX</strong> arguments of the <strong>BETWEEN</strong> operator with named parameters and allow for them to be defined dynamically:</p>

<pre><code>query = em.createQuery("SELECT company FROM CompanyEntity AS company"+
"WHERE <b>company.createdYear BETWEEN :minimum AND :maximum</b> ", CompanyEntity.class);
query.setParameter("minimum", 1995);
query.setParameter("maximum", 2000);</code></pre>

<p>But <strong>BETWEEN</strong> can be used with other types of parameters, like <strong>Dates</strong>. Lets write a JPQL query that returns now all the Employees of any company that were born between 1979-01-01 and today:</p>

<pre><code>TypedQuery<employeeentity> query =
    em.createQuery("SELECT employee FROM EmployeeEntity AS employee"+
    "WHERE <b>employee.birthday BETWEEN :minimum AND :maximum</b> ", EmployeeEntity.class);
query.setParameter(<b>"minimum", "1979-01-01"</b>);
query.setParameter(<b>"maximum", new Date()</b>);
</employeeentity></code></pre>

<p>To get the exclusion of those dates, you use the NOT :</p>

<pre><code>"WHERE employee.birthday <b>NOT BETWEEN</b> :minimum AND :maximum ", EmployeeEntity.class);</code></pre>

<p>Moving on.</p>

<h2 id="thelikeoperator">The LIKE operator</h2>

<p>We know how to compare Strings, we have the regular <strong>=</strong> and <strong>&lt;></strong> comparison operators. Lets try them out in writing a JPQL query that returns all the companies that are named Google:</p>

<pre><code>SELECT company FROM CompanyEntity AS company WHERE  company.name = 'Google'
</code></pre>

<p>But what about if on our database, that company was named "google" and not "Google"? Well, that query would fail, that's what. </p>

<p>And what if we want to return all the Companies that have "oo" (two 'o's) in their name? Well then we have to write a pattern and check which entries match that pattern. </p>

<p>For that we use the <strong>LIKE</strong> operator.</p>

<p>The <strong>LIKE</strong> works like this : on the <strong>left hand side you place a String</strong> or a path expression that evaluates to a String. On the <strong>right hand side you place a String that has a pattern</strong> to be matched. </p>

<p>So, if we do:</p>

<pre><code>WHERE  company.name LIKE 'google'
</code></pre>

<p>We would get a match for companies named:</p>

<ul>
<li>google</li>
<li>Google</li>
<li>GOOGLE</li>
<li>GoOgLe</li>
</ul>

<p>In order words: 5 letter words that have the same letters in that order, but are case insensitive.</p>

<p>Lets write a JPQL that matches all Companies with "oo" in their name, no matter where in their name:</p>

<pre><code>WHERE company.name LIKE '%oo%' 
</code></pre>

<p>Here we go. Now we will match :</p>

<ul>
<li>Google</li>
<li>Yahoo</li>
<li>oo.org</li>
<li>Boo</li>
</ul>

<p>The <strong>%</strong> character is a wildcard character that matches any sequence of characters, including an emply one. The other wildcard charater we have is the underscore <strong>_</strong> which matches exactly one character.</p>

<p>So, if we were to write:</p>

<pre><code>WHERE company.name LIKE '%oo_'
</code></pre>

<p>We would only match companies named like this:</p>

<ul>
<li>Gooa</li>
<li>Goob</li>
<li>oox</li>
<li>ooy</li>
<li>yahooa</li>
</ul>

<p>Why? Because the <strong>_</strong> wildcard must match exactly 1 character, whatever character it is, but it must be 1!</p>

<p>As with the precious operator, if we want to get all the company names that don't match that pattern, we use the <strong>NOT</strong> :</p>

<pre><code>WHERE  company.name NOT LIKE '%oo%' 
</code></pre>

<p>And we get pretty much any company whose name doesn't have exactly two 'o's together. </p>

<h2 id="theemptyoperator">The EMPTY operator</h2>

<p>The <strong>EMPTY</strong> operator simply evaluates if Collection expressed by a <em>path expression</em> is empty, or <strong>NOT EMPTY</strong>. </p>

<p>Lets write a JPQL query that returns all the companies that have no employees:</p>

<pre><code>SELECT company FROM CompanyEntity AS company WHERE <b>company.employeeCollection IS EMPTY</b>
</code></pre>

<p>The <em>company.employeeCollection</em> poins to a Collection of Employees. If we run this query against our test database, we get no returns, because all the companies on our DB have employees. So instead lets have a query that returns all the companies that have employees:</p>

<pre><code>SELECT company FROM CompanyEntity AS company WHERE <b>company.employeeCollection IS NOT EMPTY</b>
</code></pre>

<p>And now if we run that query we get returned all the Companies in our test DB.</p>

<h2 id="thenulloperator">The NULL operator</h2>

<p>Not that any of the operators are difficult to understand, but <strong>NULL</strong> is by far the easiest one. <strong>IS NULL</strong> is used to test if a give <em>path expression</em> or parameter is a NULL value , or <strong>NOT</strong>. </p>

<p>For completeness' sake lets write a JPQL query that returns all Employees that have their address NULL:</p>

<pre><code>SELECT employee FROM EmployeeEntity AS employee WHERE  employee.address IS NULL
</code></pre>

<p>And now, a query that returns all the Employees that don't have their address NULL:</p>

<pre><code>SELECT employee FROM EmployeeEntity AS employee WHERE  employee.address IS NOT NULL
</code></pre>

<p>In case you are wondering, a <em>path expression</em> that evaluates to a <strong>Collection cannot be NULL</strong>. It can however be <strong>EMPTY</strong> or <strong>NOT EMPTY</strong>. So, if you try something like this:</p>

<pre><code>SELECT company FROM CompanyEntity AS company WHERE  company.employeeCollection IS NULL
</code></pre>

<p>Well... that just isn't going to work.</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="butthereismore">But there is more!</h1>

<p>What about Subqueries? Any more comparision operators? And Update and Delete statements? What about the Criteria API? </p>

<p>We'll take a break here, because this post is getting big and we'll continue on the next post! We'll update this one with a link as soon as the next post comes out.</p>

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

<p><a href="http://download.oracle.com/otndocs/jcp/persistence-2.0-fr-oth-JSpec/">JPA 2 Final Spec</a></p>]]></content:encoded></item><item><title><![CDATA[JPA 2 Tutorial – Many To Many with Self]]></title><description><![CDATA[<p><a href="http://syshex.files.wordpress.com/2013/06/self.png"><img src="http://syshex.files.wordpress.com/2013/06/self.png" alt="self" title=""></a>
We have just covered the subject of Many-To-Many relationships, which is a fun topic for the hole family! Now there are some particular cases on the Many-to-many front which are not particularly hard, but can lead to a bit of confusion. One of those particular cases is the M2M with</p>]]></description><link>http://blog.jbaysolutions.com/2013/06/06/jpa-2-tutorial-many-to-many-with-self-2/</link><guid isPermaLink="false">3cdd1429-e2bd-4ec3-b88f-7a47248a1aff</guid><category><![CDATA[java]]></category><category><![CDATA[jpa]]></category><category><![CDATA[eclipselink]]></category><category><![CDATA[mysql]]></category><dc:creator><![CDATA[Rui Pereira]]></dc:creator><pubDate>Thu, 06 Jun 2013 15:40:42 GMT</pubDate><content:encoded><![CDATA[<p><a href="http://syshex.files.wordpress.com/2013/06/self.png"><img src="http://syshex.files.wordpress.com/2013/06/self.png" alt="self" title=""></a>
We have just covered the subject of Many-To-Many relationships, which is a fun topic for the hole family! Now there are some particular cases on the Many-to-many front which are not particularly hard, but can lead to a bit of confusion. One of those particular cases is the M2M with same table.      </p>

<p>A reader asked : "How would one create manyToMany relationship with the same entity. Entity user can have friends (user), and can be friend to other users. With note that junction table has to have some additional columns besides user keys. How can that be achieved?"  (Thanks Felix for the feedback and question!)</p>

<p>So, to start of let us be clear that to follow this Tutorial you should :</p>

<ol>
<li><p>Have a basic understanding of JPA2 , enough to create a few entities etc</p></li>
<li><p>Know how to create a Many to many relationship between two related Entities</p></li>
</ol>

<p>If you have been following the Tutorials till now, then you can go right ahead and start this one. If you haven't been following but know the stuff that is fine as well. If you want to go and check them out : <a href="http://blog.jbaysolutions.com/tag/jpa">JPA2 Tutorials</a> .</p>

<p>You'll need EclipseLink, JUnit and MySQL, 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>Source Code for all of this can be found at <a href="https://sourceforge.net/projects/syshex/files/?source=navbar">Sourceforge</a></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="letsgetstarted">Lets get started</h1>

<p>In the previous tutorial we have discussed about the<em>* Join Table</em>*, which is a table that has one only purpose, which is to allow the creation of a many to many relationship between two tables. This is not entirely correct, as it was pointed out by simply reading the question that was posed. The two tables can in fact be the same table, and in that case the Join Table is mapping a many to many relationship between elements of the same type.  The following diagram exemplifies:</p>

<p><a href="http://syshex.files.wordpress.com/2013/06/m2m_self2.png"><img src="http://syshex.files.wordpress.com/2013/06/m2m_self2.png" alt="m2m_self" title=""></a></p>

<p>Let us start by creating a database with these two tables. The SQL should look something like this :</p>

<pre><code> CREATE TABLE IF NOT EXISTS `jpatutorial3u1`.`person` (
  `idperson` INT NOT NULL AUTO_INCREMENT ,
  `name` VARCHAR(45) NOT NULL ,
  `phonenumber` VARCHAR(45) NULL ,
  PRIMARY KEY (`idperson`) )
 ENGINE = InnoDB;
 CREATE TABLE IF NOT EXISTS `jpatutorial3u1`.`business` (
  `seller` INT NOT NULL ,
  `buyer` INT NOT NULL ,
  PRIMARY KEY (`seller`, `buyer`) ,
  INDEX `fk_person_has_person_person1_idx` (`buyer` ASC) ,
  INDEX `fk_person_has_person_person_idx` (`seller` ASC) ,
  CONSTRAINT `fk_person_has_person_person`
  FOREIGN KEY (`seller` )
  REFERENCES `jpatutorial3u1`.`person` (`idperson` )
  ON DELETE NO ACTION
  ON UPDATE NO ACTION,
  CONSTRAINT `fk_person_has_person_person1`
  FOREIGN KEY (`buyer` )
  REFERENCES `jpatutorial3u1`.`person` (`idperson` )
  ON DELETE NO ACTION
  ON UPDATE NO ACTION)
 ENGINE = InnoDB;  
</code></pre>

<p>As for the Entity Bean, let us create one Entity called <strong>PersonEntity</strong>, and add the existing columns to it, just the columns for now. The main bits of the <strong>PersonEntity</strong> class should look somewhat like this:</p>

<pre><code>@Entity
@Table(name = "person", catalog = "jpatutorial3u1", schema = "")
public class PersonEntity implements Serializable {
 private static final long serialVersionUID = 1L;
 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 @Column(name = "idperson", nullable = false)
 private Integer idperson;

 @Basic(optional = false)
 @Column(name = "name", nullable = false, length = 45)
 private String name;

 @Basic(optional = true)
 @Column(name = "phonenumber", length = 45)
 private String phonenumber;
</code></pre>

<p>Create now the Getters and Setters for these fields. While we are at it, lets go and take a look at the <strong>Test Packages</strong> folder and check the <strong>MemSelfTest</strong> JUnit class. For those not following the source code, the relevant bit is :</p>

<pre><code>@Test
public void testMemSelf(){
        // Start a transaction
        em.getTransaction().begin();
        // ------------
       PersonEntity c = new PersonEntity();
        c.setName("Rui");
        em.persist(c);
        em.flush();

        Object result = em.find(PersonEntity.class, c.getIdperson());
        assertEquals(c, result);

        em.remove(c);
        em.flush();

        // Commit the Transaction
        em.getTransaction().commit();
}
</code></pre>

<p>It doesn't really do much except for creating a Person, searching for it, and removing it.... just to make sure everything is working fine and we can proceed.</p>

<p>The basic stuff is now done, lets move on to the mapping of the relationship</p>

<h1 id="whosoldtowho">Who Sold To Who?</h1>

<p>Lets start with editing the <strong>PersonEntity</strong> class by adding the following bit:</p>

<pre><code> @JoinTable(name = "business", joinColumns = {
 @JoinColumn(name = "seller", referencedColumnName = "idperson", nullable = false)}, inverseJoinColumns = {
 @JoinColumn(name = "buyer", referencedColumnName = "idperson", nullable = false)})
 @ManyToMany
 private Collection&lt;PersonEntity&gt;soldToCollection;
</code></pre>

<p>and, as per usual, add the Setters and Getters for <strong>soldToCollection</strong>.</p>

<p>If you are a bit lost right now with the notation used and the way it was used, then you should probably give a read to  <a href="http://blog.jbaysolutions.com/2012/12/17/jpa-2-relationships-many-to-many/">JPA 2 Tutorial – Relationships – Many To Many</a> , but I'll recap a bit here.</p>

<p>The <strong>@JoinTable</strong> annoration is used on the Owning Entity side of the relationship, which is in fact the PersonEntity class (both the owning and the inverse to be honest, but it will depend on the context it is being used).  The <strong>Join Table</strong> is specify as "<strong>friend</strong>" , which is the name of the Join Table and then we do the <strong>JoinColumns</strong> bit, in which we specify the Fields used to map the relationship. Please do give a read at <a href="http://blog.jbaysolutions.com/2012/12/17/jpa-2-relationships-many-to-many/">JPA 2 Tutorial – Relationships – Many To Many</a> if nothing seems to make sense at this point!</p>

<p>Let us modify the <strong>M2mSelfTest</strong> JUnit class now. First let us create another few users :</p>

<pre><code>PersonEntity c = new PersonEntity();
c.setName("Rui");
PersonEntity f1 = new PersonEntity();
f1.setName("Felix");
PersonEntity f2 = new PersonEntity();
f2.setName("Gusy");
em.persist(c);
em.persist(f1);
em.persist(f2);
em.flush();
</code></pre>

<p>Now we got a few <strong>PersonEntity</strong> objects to play about with. After the <strong><em>assertEquals</em></strong> that we have created previously, add the following bit as well:</p>

<pre>
    assertEquals(c.getSoldToCollection().size(),0);
    <strong>c.getSolfToCollection().add(f1);
    em.merge(c);
    em.flush();</strong>
    assertEquals(c.getSoldToCollection().size(),1);
    System.out.println(c.getName() + " sold stuff to :");
    for (PersonEntity tempP : c.getSoldToCollection() )
          System.out.println(" - " + tempP.getName() );
</pre>

<p>and to finish it off , lets delete every object we have created and clean the DB :</p>

<pre><code>em.remove(c);
em.remove(f1);
em.remove(f2);
em.flush();
// Commit the Transaction
em.getTransaction().commit();
</code></pre>

<p>Run it and, if it was done right, everything should have work fine:</p>

<pre>    
    [EL Info]: 2013-06-06 16:07:42.49--ServerSession(805125680)--EclipseLink, version: Eclipse Persistence Services - 2.3.2.v20111125-r10461
    [EL Info]: 2013-06-06 16:07:42.753--ServerSession(805125680)--file:/home/rui/projects/syshex-code/JPATutorial3.1/trunk/build/classes/_JPATutorial3.1PU login successful
    <strong>Rui sold stuff to :
     - Felix</strong>
</pre>

<p>But you know what would be really cool too? For a us to know who he Bought stuff from, yeah?</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="whodidheboughtfrom">Who did He Bought From?</h1>

<p>First, lets modify the <strong>PersonEntity</strong> again and add the following:</p>

<pre>    
    @ManyToMany(mappedBy = "<strong>soldToCollection</strong>")
    private Collection&lt;PersonEntity&gt;<strong> boughtFromCollection</strong>;
</pre>

<p>Feeling a bit lost? Check out  <a href="http://blog.jbaysolutions.com/2012/12/17/jpa-2-relationships-many-to-many/">JPA 2 Tutorial – Relationships – Many To Many</a> where it is explained everything about <strong>@ManyToMany</strong> and the <em><strong>mappedBy</strong></em> property.</p>

<p>Go ahead and create the Setter and Getter for this new collection, and afterward , lets go to the <strong>MemSelfTest</strong> JUnit test and modify like so:</p>

<pre>    
    System.out.println(c.getName() + " sold stuff to :");
    for (PersonEntity tempP : c.getSoldToCollection() )
         System.out.println(" - " + tempP.getName() );

    System.out.println(c.getName() + " Bought stuff from :");
    for (PersonEntity tempP : c.getBoughtFromCollection())
         System.out.println(" - " + tempP.getName() );

    <strong>em.refresh(f1)</strong>;

    System.out.println(f1.getName() + " sold stuff to :");
    for (PersonEntity tempP : f1.getSoldToCollection() )
        System.out.println(" - " + tempP.getName() );

    System.out.println(f1.getName() + " Bought stuff from :");
    for (PersonEntity tempP : f1.getBoughtFromCollection())
         System.out.println(" - " + tempP.getName() );

</pre>

<p>Lets run it !</p>

<pre><code>[EL Info]: 2013-06-06 16:18:04.464--ServerSession(745084087)--EclipseLink, version: Eclipse Persistence Services - 2.3.2.v20111125-r10461
[EL Info]: 2013-06-06 16:18:04.73--ServerSession(745084087)--file:/home/rui/projects/syshex-code/JPATutorial3.1/trunk/build/classes/_JPATutorial3.1PU login successful
Rui sold stuff to :
- Felix
Rui Bought stuff from :
Felix sold stuff to :
Felix Bought stuff from :
- Rui
</code></pre>

<p>Wicked stuff really.</p>

<p>But, what if.... we need to store some information regarding the relationship?</p>

<h1 id="storinginfoaboutrelationship">Storing Info about Relationship</h1>

<p>Well, then we would have something like this :</p>

<p><a href="http://syshex.files.wordpress.com/2013/06/m2m_self_not_really.png"><img src="http://syshex.files.wordpress.com/2013/06/m2m_self_not_really.png" alt="m2m<em>self</em>not_really" title=""></a></p>

<p>Now, as it was said in the last Tutorial :</p>

<p>The table that you see serving as a connection between the Company table and the Client table is what is called a “<strong>Join Table</strong>” ,  and its sole purpose in life is to keep track of the relations that exist between Company and Client Entities.</p>

<p>And storing information regarding <strong>Money</strong> in it will make it have<em>* more the a "sole" purpose<strong>. Not that it is wrong to do this, if you need to have information regarding the relationship, but since it has information, it should be an Entity. It could be called  *</strong></em>BusinessEntity, in which <strong>money</strong> , seller and buyer are in fact information that regard the Business.</p>

<p>In looking at this <strong>Business</strong> <strong>table</strong> and an <strong>Entity</strong> and not as a simple <strong>JoinTable</strong>, we can deduce that there are One-To-Many relationships to be used instead of the<em>* Many-To-Many</em>*.</p>

<p>So, wrapping it up, in this situation you should see this in a totally different light than a M2M</p>

<p>Hope his helped, and as per usual, leave a comment if you find errors, problems, or for a kind word. And again, thanks for checking out our blog.</p>

<p>Also, check the next tutorial on this series: <a href="http://blog.jbaysolutions.com/2014/10/16/jpa-2-tutorial-queries-on-the-model/">JPA 2 Tutorial - Queries with JPQL</a></p>]]></content:encoded></item><item><title><![CDATA[JPA 2 Tutorial – Relationships – Many To Many]]></title><description><![CDATA[<p><a href="http://syshex.files.wordpress.com/2012/03/relationships.png"><img src="http://syshex.files.wordpress.com/2012/03/relationships.png" alt="" title=""></a>
So, we have already dabbled into Relationships in JPA, in particular One-To-Many and Many-To-One. It is now time to give a look into Many-To-Many, which is very similar to One-To-Many Relationships. So at this point you should have read the previous two tutorials on JPA 2, but if for some</p>]]></description><link>http://blog.jbaysolutions.com/2012/12/17/jpa-2-relationships-many-to-many/</link><guid isPermaLink="false">0422a90f-e34d-4a34-a316-1f662a0ef4a8</guid><category><![CDATA[java]]></category><category><![CDATA[jpa]]></category><category><![CDATA[eclipselink]]></category><category><![CDATA[mysql]]></category><dc:creator><![CDATA[Rui Pereira]]></dc:creator><pubDate>Mon, 17 Dec 2012 20:23:46 GMT</pubDate><content:encoded><![CDATA[<p><a href="http://syshex.files.wordpress.com/2012/03/relationships.png"><img src="http://syshex.files.wordpress.com/2012/03/relationships.png" alt="" title=""></a>
So, we have already dabbled into Relationships in JPA, in particular One-To-Many and Many-To-One. It is now time to give a look into Many-To-Many, which is very similar to One-To-Many Relationships. So at this point you should have read the previous two tutorials on JPA 2, but if for some reason you don't know what I'm talking about, give a look at these two links, they will help quite a bit:</p>

<ul>
<li><p><strong><a href="http://blog.jbaysolutions.com/2011/09/10/jpa_getting_started_part1/">Getting Started with JPA 2 Tutorial</a></strong></p></li>
<li><p><strong><a href="http://blog.jbaysolutions.com/2011/09/19/jpa-2-relationships-onetomany/">JPA 2 – Relationships – One To Many</a></strong>   </p></li>
</ul>

<p>For this tutorial it is assumed that you have basic knowledge of SQL and relational databases, in particular MySQL. It is also useful to have a MySQL database installed so that you can actually try out the examples that we will be going through in this tutorial.  Unit Testing with JUnit is also a bit part for this tutorial aswell, You'll need to understand what it is, and how it is used. Check the previous Tutorial regarding JPA, they should provide enough information to get you started. An IDE like IntelliJ or Netbeans is also recommended is case you want to try out the source code provided. You don't need special powers, if you know basic SQL, JUnit and you have read and understood the previous tutorials you should be fine. The source code used for this tutorial can be found here : <a href="https://github.com/jbaysolutions/jpa2tut-many2many">https://github.com/jbaysolutions/jpa2tut-many2many</a> .</p>

<h3 id="manytomanyletsstart">Many-To-Many, lets start!</h3>

<p>Of the 4 types of relationships that exist, we have already talked about the One-to-Many and Many-to-One and most of the background information regarding how a relationship works, and the difference between Unidirectional and Bidirectional relationship. The Many-to-Many relationship isn't much different to the One-To-Many relationship, except for the fact that now we have an extra middle table around there....</p>

<h3 id="thejointable">The Join Table</h3>

<p>Expanding on the example given on the previous tutorial, we had two Entities : <strong>Company</strong> and <strong>Employee</strong>. We now delete the <strong>Employee</strong> table and create a new Entity which is called <strong>Client</strong> and we say:</p>

<ul>
<li><p>a Company can have several Clients and</p></li>
<li><p>a Client can have various Companies</p></li>
</ul>

<p>When we say this we have a Many to Many relationship between Companies and Clients, and can be represented on a data model like so:</p>

<p><a href="http://syshex.wordpress.com/2012/12/17/jpa-2-relationships-many-to-many/go-3/"><img src="http://syshex.files.wordpress.com/2012/12/go2.png" alt="go" title=""></a></p>

<p>The SQL to create this is like so:</p>

<pre><code>CREATE TABLE IF NOT EXISTS `jpatutorial3`.`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 `jpatutorial3`.`client` (
 `idclient` INT NOT NULL AUTO_INCREMENT ,
 `name` VARCHAR(45) NOT NULL ,
 `address` VARCHAR(45) NULL ,
 PRIMARY KEY (`idclient`) )
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `jpatutorial3`.`company_client` (
 `company_idcompany` INT NOT NULL ,
 `client_idclient` INT NOT NULL ,
 PRIMARY KEY (`company_idcompany`, `client_idclient`) ,
 INDEX `fk_company_has_client_client1` (`client_idclient` ASC) ,
 INDEX `fk_company_has_client_company1` (`company_idcompany` ASC) ,
 CONSTRAINT `fk_company_has_client_company1`
 FOREIGN KEY (`company_idcompany` )
 REFERENCES `jpatutorial3`.`company` (`idcompany` )
 ON DELETE NO ACTION
 ON UPDATE NO ACTION,
 CONSTRAINT `fk_company_has_client_client1`
 FOREIGN KEY (`client_idclient` )
 REFERENCES `jpatutorial3`.`client` (`idclient` )
 ON DELETE NO ACTION
 ON UPDATE NO ACTION)
ENGINE = InnoDB;
</code></pre>

<p>The table that you see serving as a connection between the Company table and the Client table is what is called a "<strong>Join Table</strong>" ,  and its sole purpose in life is to keep track of the relations that exist between Company and Client Entities.</p>

<p>The normal notation for a Join Table is to use a single underscore between the name of the two tables that are part of the relation. In our example the expected name of the Join Table would have been <strong>company<em>client</em></strong> . The Entity that is the Owner of the relationship (you remember what the Owner is, yes?) is placed on the left side of the "".</p>

<p>From this point onwards, when we talk about the Join Table, you know exactly what it is.</p>

<h3 id="puttingittowork">Putting it to work</h3>

<p>Continuing as we were, expanding from the previous tutorial, we have a <em>CompanyEntity</em> bean that already has a relation with <em>EmployeeEntity</em>, this is a OneToMany relation. We'll leave that as it is for now and proceed to create the <em>ClientEntity</em> bean that is missing, because it was not present on the previous tutorial.  If you follow the previous tutorial, it should be pretty easy to get the ClientEntity bean done, but here is a snippet of what you should be aiming for at this moment:</p>

<pre><code>@Entity
@Table(name = "client")
public class ClientEntity implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "idclient")
    private Integer idclient;

    @Column(name = "name")
    private String name;

    @Column(name = "address")
    private String address;
</code></pre>

<p>And now, we define the new relation that we created by adding the following lines to the <em>CompanyEntity</em> bean:</p>

<pre><code>@ManyToMany
private Collection&lt;ClientEntity&gt; client;
</code></pre>

<p>And while we are at it, lets go to the <em>ClientEntity</em> bean and add the following:</p>

<pre><code>@ManyToMany(mappedBy = "clientCollection")
private Collection&lt;CompanyEntity&gt; company;
</code></pre>

<p>Create in both beans the respective <em>Getters</em> and _Setters _for the collections.</p>

<p>So, what is new so far on these Entities that we haven't seen before on the other tutorials?</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="manytomany">@ManyToMany</h3>

<p>The ManyToMany annotation works pretty much like the other annotations we have see thus far, the only different is a couple of assumptions that are made because of the Join Table that was created to support the relationship. But lets start from the beginning: Every many to many relationship has obviously two sides: a Owning side and the Inverse side (which is... non-owning).</p>

<p>As you can see, on one of the <em><strong>@ManyToMany</strong></em> annotations that we wrote a minute ago we have a <strong><em>mappedBy</em></strong> element. This <em><strong>mappedBy</strong></em> element is mandatory and must be placed on the Inverse side of the relationship in case we are mapping a Bidirectional. If we are mapping a Unidirectional relationship then the Inverse side would have no<strong>_ @ManyToMany<em></em></strong> annotation and therefore no _<strong>mappedBy</strong> element. In a second I'll get back to this!</p>

<p>The other possible elements of the @ManyToMany annotation are <em><strong>targetEntity</strong></em>, <em><strong>cascade</strong></em> and <em><strong>fetch</strong></em>, which we have already seen on the previous tutorials. I'll just give a kick overview of the <em><strong>targetEntity</strong></em> element to say that it is optional if the collection is defined using generics, otherwise you have to put it in, example:</p>

<pre><code>@ManyToMany(targetEntity=ClientEntity.class) 
private Collection client;
</code></pre>

<p>So returning to the <em><strong>mappedBy</strong></em> element, it points out the field (that must exist on the Target Entity, which is known either through the use of generics or through the use of the <em><strong>targetEntity</strong></em> element) that owns the relationship.</p>

<p>Now that we have a better understanding of what was inserted on the Entity bean, lets see how it works.</p>

<h3 id="workingit">Working it</h3>

<p>In the source code provided with this tutorial there is a Class called <em><strong>ManyToManyTesting</strong></em>, in it we have this method called <em><strong>testCompanyWithClient1</strong></em> which is annotated with <em><strong>@Test</strong></em>, in it, we have the following:</p>

<pre><code>CompanyEntity c = createTestCompany();
ClientEntity client = createTestClient();
em.persist(c);
em.persist(client);
em.flush();
c.getClientCollection().add(client);
em.merge(c);
em.flush();
</code></pre>

<p>Both methods <em><strong>createTestCompany</strong></em> and <em><strong>createTestClient</strong></em> simply create its corresponding Entity Bean with some test data inserted. Nothing is set in relation to relationships on those methods.... they just save us some work when writing the test cases.</p>

<p>So, running this test case we get a successful execution, right? Perfect.</p>

<p>The reason why this was a successful and easy bit of code is because we based all of our previous code on the expected JPA defaults, and because of that all worked wonderfully. Now, in real life:</p>

<ul>
<li><p>you might not have a change to decide on the names of the tables and all of that.</p></li>
<li><p>you might not want to have the name of the field in a particular way, just to be inline with the defaults</p></li>
</ul>

<p>In fact.... this was the first time ever that I personally had a <strong>ManyToMany</strong> relationship that works based on the defaults.... So, imagine this scenario, instead of having a<em>* Join Table</em>* named <strong>company<em>client</em></strong> , our Join Table is now called <strong>companyhas_client</strong>:</p>

<p><img src="http://syshex.files.wordpress.com/2012/12/go21.png" alt="go2"></p>

<p>The SQL for this new version of the join table is like so:</p>

<pre><code>CREATE TABLE IF NOT EXISTS `jpatutorial3`.`company_has_client` (
 `company_idcompany` INT NOT NULL ,
 `client_idclient` INT NOT NULL ,
 PRIMARY KEY (`company_idcompany`, `client_idclient`) ,
 INDEX `fk_company_has_client_client1` (`client_idclient` ASC) ,
 INDEX `fk_company_has_client_company1` (`company_idcompany` ASC) ,
 CONSTRAINT `fk_company_has_client_company1`
 FOREIGN KEY (`company_idcompany` )
 REFERENCES `jpatutorial3`.`company` (`idcompany` )
 ON DELETE NO ACTION
 ON UPDATE NO ACTION,
 CONSTRAINT `fk_company_has_client_client1`
 FOREIGN KEY (`client_idclient` )
 REFERENCES `jpatutorial3`.`client` (`idclient` )
 ON DELETE NO ACTION
 ON UPDATE NO ACTION)
ENGINE = InnoDB;
</code></pre>

<p>Lets try to run the same test case again and see what happens:</p>

<pre><code>Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'jpatutorial3.company_client' doesn't exist
Error Code: 1146
Call: INSERT INTO company_client (client_idclient, company_idcompany) VALUES (?, ?)
</code></pre>

<p>So, our <strong>Join Table</strong> is actually "<em><strong>company</strong></em>has<em>client</em>" and not "<em><strong>company</strong></em>client<em>" as the persistency manager was expecting. The reason why this is looking for the "</em><strong>company<em>client</em></strong>" table comes down to the defaults.</p>

<h3 id="defaultjointable">Default Join Table</h3>

<p>If we were to have the Join Table called "<em><strong>company</strong></em>client<em>" instead of "</em><strong>company<em>has</em>client</strong><em>" this would have worked fine, as you have seen, but now it just isn't working and the persistence manager cannot figure out how to work with these Entities. Because we have only placed the minimum amount of data onto the _<strong>ManyToMany</strong></em> annotation, and in fact have only used that annotation to represent the existing relationship on the database, we heavily depend on the defaults of JPA to figure out what the names of the columns and tables are. For the two Entities we have: <em>CompanyEntity</em> and <em>ClientEntity</em>, we have annotated them with<em>** @Table<strong></strong></em> and the name of the table they represent. A Join Table between these two entities, by default, is expected to be the name of the table on the annotation <em>@Table<strong></strong></em> of the Owning side Entity, underscore, name of the table on the annotation <em>@Table**</em> of the Inverse side Entity. Some readers might be lost now, so look at the following example:</p>

<pre><code>@Table(name = "store")
public class StoreEntity
</code></pre>

<p>and</p>

<pre><code>@Table(name = "product")
public class ProductEntity
</code></pre>

<p>The default expected Join Table, if <em><strong>StoreEntity</strong></em> was the Owning side and <em><strong>ProductEntity</strong></em> the Inverse side,  would be : <strong>store_product</strong> To use the a non default, unexpected join table there is this other annotation, which is very conveniently called: <strong>@JoinTable</strong></p>

<h3 id="jointable">@JoinTable</h3>

<p>The <strong>@JoinTable</strong> annoration is used on the Owning Entity side of the relationship and is used to describe to the entity manager where to look for the Join Table and what to expect once it needs to use it. Lets jump on it and modify now our owning entity <em>CompanyEntity</em> like so:</p>

<pre><code>@JoinTable(name="company_has_client")
@ManyToMany
private Collection&lt;ClientEntity&gt; client;
</code></pre>

<p>Now, lets run again the unit test and Bang: Success again! Simple, yes? But wait.... There is more! As per usual, an explanation of this new annotation and a description of all possible elements will follow, but lets go for it while we perform some more changes, ok? Let us now change the name of the field of our Owning side Entity <em>CompanyEntity</em> like this:</p>

<pre><code>@JoinTable(name="company_has_client")
@ManyToMany
private Collection&lt;ClientEntity&lt;strong&gt;clientCollection&lt;/strong&gt;;
</code></pre>

<p>Modify the <em>getters</em> and <em>setters</em> accordingly please. Also go to <em>ClientEntity</em> and modify it like so:</p>

<pre>    
    @ManyToMany(mappedBy = "<strong>clientCollection</strong>")
    private Collection&lt;CompanyEntity&gt; company;
</pre>

<p>So that it is referencing an existing field on the Owning side Entity. Lets run the unit test one more time:</p>

<pre>  
    Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
    Unknown column '<strong>clientCollection_idclient</strong>' in 'field list'
    Error Code: 1054
    Call: INSERT INTO company_has_client (<strong>clientCollection_idclient</strong>, company_idcompany) VALUES (?, ?)
     bind =[2 parameters bound]
</pre>

<p>We get an exception and I've also made a particular point of putting in Bold the interesting bit about this exception. Basically, you can see that the generated SQL is referencing a column that does not exist, it is called <strong>client<em>idclient</em></strong> and not** clientCollectionidclient<strong>. The reason it is looking for a column in the</strong> Join Table** that is called <strong>clientCollection_idclient</strong> is once again due to the defaults. The name of the column that is in bold was created by using the name of the field on the Entity bean : "<strong>clientCollection</strong>" , underscore, and the column name of the _<strong>@Id</strong> _field on the specified target entity:</p>

<pre>
    @<strong>Id</strong>
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "<strong>idclient</strong>")
    private Integer <strong>idclient</strong>;
</pre>

<p>So, we have to expand our example now to take into account that we are using names of columns that are not what the manager is not expecting. To do this we look a bit further into the <strong>@JoinTable</strong> annotation.</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="jointableexpanded">@JoinTable expanded</h3>

<p>As you have seen before the @JoinTable is used to map associations through the use of a Join Table, and by specifying the particularities of such table. We have seen how to specify a Join Table that does not follow the expected naming convention that is used by the persistency manager, but this is not all that can be done with it. For the JoinTable annotation one can specify the name of the join table by using the <strong>name</strong> element. the name of the schema that table belongs to through the use of the <strong>schema</strong> element, and the name of the catalog through the use of the <strong>catalog</strong> element. This is the easy bit, and almost self explanatory. The new'ish bit is specifying the join columns through the use of the following elements:</p>

<ul>
<li><p><strong>joinColumns</strong> : The mapping of the join columns  whose field is defined on the Inverse Entity.</p></li>
<li><p><strong>inverseJoinColumns</strong> : the mapping of the join columns whose field if defined on the Owning Entity.</p></li>
</ul>

<p>Both these elements are <strong>JoinColumn</strong> arrays. For our example we have modified the name of the field <strong>client</strong> to <strong>clientCollection</strong>. This field is specified on the Owning side Entity but is referent to the Inverse side Entity. Yes? Recapping:</p>

<pre>
    @JoinTable(name="company_has_client")
    @ManyToMany
    private Collection&lt;ClientEntity&gt;  <strong>clientCollection</strong>;
</pre>

<p>This bit exists on the Owning side (<strong><em>CompanyEntity</em></strong>) and the field <em><strong>clientCollection</strong></em> references the Inverse side (<em><strong>ClientEntity</strong></em>), correct? Because of this, we use the <em><strong>inverseJoinColumns</strong></em> element to define the join columns whose name does not match the default generated as explained before. Modify the <em><strong>CompanyEntity</strong></em> bit that was written before this this version now:</p>

<pre>    
    @JoinTable (name = "company_has_client", 
        <strong>inverseJoinColumns</strong> { 
            @JoinColumn(name = "<strong>client_idclient</strong>", referencedColumnName = "<strong>idclient</strong>")
            }
     )

    @ManyToMany
    private Collection&lt;ClientEntity&gt; clientCollection;
</pre>

<p>Run the test again and as you can see everything works fine now! The <em><strong>inverseJoinColumns</strong></em> element is an array of <em><strong>@JoinColumn</strong></em> annotations, which we have already seen in a previous tutorial, but still, it should be pretty self explanatory as for the elements used in our scenario. But lets go ahead and modify our example a little bit more and modify now the <em><strong>ClientEntity</strong></em> class with the following:</p>

<pre><code>@ManyToMany(mappedBy = "clientCollection")
private Collection&lt;CompanyEntity&gt; companyCollection;
</code></pre>

<p>So, we are changing the name of the field on the Inverse side that references the Owning side. Please modify the Getters and Setter methods and <em>Getters</em> and <em>Setter</em> methods and run the unit test again.</p>

<pre>
    Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
    Unknown column '<strong>companyCollection_idcompany</strong>' in 'field list'
    Error Code: 1054
    Call: INSERT INTO company_has_client (client_idclient, <strong>companyCollection_idcompany</strong>) VALUES (?, ?)
     bind =[2 parameters bound]
</pre>

<p>As expected, the same problem as before, and to fix it we now use the <em><strong>joinColumns</strong></em> element because this field is specified on the Inverse side but references the Owning Entity. Modify the<em>** @JoinTable**</em> annotation to look like so:</p>

<pre>
    @JoinTable(name = "company_has_client", 
            <strong>joinColumns</strong> { 
                   @JoinColumn(name = "<strong>company_idcompany</strong>", referencedColumnName = "<strong>idcompany</strong>")
            }, 
            inverseJoinColumns = { 
                   @JoinColumn(name = "client_idclient", referencedColumnName = "idclient")
            }
     )
     @ManyToMany
     private Collection&lt;ClientEntity&gt; clientCollection;
</pre>

<p>Run the unit test again and get a fully successful running test unit! And, to close  off this tutorial, I'll just mention the remaing element of the<em>** @JoinTable<strong></strong></em> annotation, which is the <em>uniqueConstraints<strong></strong></em> element. The <em>uniqueConstraints<strong></strong></em> element is an array of <em>@UniqueConstrain**</em> and is used to specify the constraints that are to be placed on the table, but just if table generation is being used, which is not the case here.</p>

<h3 id="finishingoff">Finishing off....</h3>

<p>Hope you enjoyed and this tutorial was of use to you. As per usual, if you find that this article is incorrect in anyway or if you have any comment to give, either good or bad, drop a comment over here.</p>

<h1 id="followup">Follow Up</h1>

<p><strong><a href="http://blog.jbaysolutions.com/2013/06/06/jpa-2-tutorial-many-to-many-with-self-2/">JPA 2 Tutorial – Many To Many with Self</a></strong></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>]]></content:encoded></item><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>