<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>techbits.de &#187; ejb3</title>
	<atom:link href="http://www.techbits.de/tag/ejb3/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.techbits.de</link>
	<description>thoughts on hardware, software, development and tech news</description>
	<lastBuildDate>Fri, 02 Dec 2011 22:51:07 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>EJB3 persistence with hibernate</title>
		<link>http://www.techbits.de/2006/04/17/ejb3-persistence-with-hibernate/</link>
		<comments>http://www.techbits.de/2006/04/17/ejb3-persistence-with-hibernate/#comments</comments>
		<pubDate>Mon, 17 Apr 2006 12:30:07 +0000</pubDate>
		<dc:creator>Florian</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[ejb3]]></category>
		<category><![CDATA[example]]></category>
		<category><![CDATA[hibernate]]></category>
		<category><![CDATA[persistence]]></category>

		<guid isPermaLink="false">http://www.techbits.de/2006/04/17/ejb3-persistence-with-hibernate/</guid>
		<description><![CDATA[Since my trip to java posting I looked into EJB3 persistence (JSR-220) with hibernate as promised. It&#8217;s shocking how much the EJB3 specification resembles hibernate &#8211; Gavin King apparently got most if his hibernate semantics in there. I believe it&#8217;s &#8230; <a href="http://www.techbits.de/2006/04/17/ejb3-persistence-with-hibernate/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Since my <a href="http://www.techbits.de/2006/03/19/a-trip-to-java/">trip to java</a> posting I looked into EJB3 persistence (<a href="http://www.jcp.org/en/jsr/detail?id=220">JSR-220</a>) with <a href="http://www.hibernate.org/">hibernate</a> as promised. It&#8217;s shocking how much the EJB3 specification resembles hibernate &#8211; Gavin King apparently got most if his hibernate semantics in there. I believe it&#8217;s a good thing though. Former hibernate developers can adapt the new sepecification with little effort and on the other hand the definition of persitience classes has been cleaned up nicely with properly defined annotations.<br />
So far I&#8217;ve been able to create a simple example application with the hibernate entitymanager/annotations engine. It simply creates two objects, stores them in the database an reads them again with a query. The rest of this post shows how this example app is set up.<br />
<span id="more-31"></span><br />
</p>
<h3>Configuration</h3>
<p>First of all a configuration file for the database and the persistent classes is needed. The xml file <b>META-INF/persitence.xml</b> is used for that purpose. In my example application I used a local <a href="http://www.hsqldb.org/">hsqldb</a> database. In addition to the database each persistent class has to be specified in a class-element, in this case <b>example.pojo.Cat</b>.</p>
<p><code lang="xml"><br />
<?xml version="1.0" encoding="UTF-8"?></p>
<persistence>
<persistence-unit name="manager1"<br />
      transaction-type="RESOURCE_LOCAL"><br />
    <class>example.pojo.Cat</class></p>
<properties>
<property name="hibernate.dialect"<br />
        value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.connection.driver_class"<br />
        value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.url"<br />
        value="jdbc:hsqldb:file:database/ejb3test"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.max_fetch_depth" value="3"/>
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.connection.shutdown">true</property>
    </properties>
  </persistence-unit>
</persistence>
</code></p>
<h3>Data classes with annotations</h3>
<p>As seen above only one persistent class is used in this application. It defines a cat, which has an id, a name and a birth date. In addition to that it also has a parent child relationship as a self reference (attributes mother and kittens). You can also see the annotations which define how all these attributes are persisted. This is the bare minimum of annotations that is required for EJB3 persistence to work. In a more complex application where you want a detailed control over relations, database tables, datatypes and query characteristics the annotations will also look a lot more complex.<br />
<code lang="java5"><br />
package example.pojo;</p>
<p>import java.util.ArrayList;<br />
import java.util.Date;<br />
import java.util.List;<br />
import javax.persistence.CascadeType;<br />
import javax.persistence.Entity;<br />
import javax.persistence.GeneratedValue;<br />
import javax.persistence.GenerationType;<br />
import javax.persistence.Id;<br />
import javax.persistence.ManyToOne;<br />
import javax.persistence.OneToMany;</p>
<p>@Entity<br />
public class Cat {</p>
<p>	private String name;<br />
	private Date birthDate;<br />
	private int id;<br />
	private Cat mother;<br />
	private List<Cat> kittens;</p>
<p>	public Cat() {<br />
		super();<br />
		setKittens(new ArrayList<Cat>());<br />
	}</p>
<p>	public void addKitten(Cat kitten) {<br />
		this.getKittens().add(kitten);<br />
		kitten.setMother(this);<br />
	}</p>
<p>	// -- GETTERs and SETTERs --</p>
<p>	@OneToMany(cascade = CascadeType.ALL, mappedBy="mother")<br />
	public List<Cat> getKittens() {<br />
		return kittens;<br />
	}<br />
	public void setKittens(List<Cat> kittens) {<br />
		this.kittens = kittens;<br />
	}</p>
<p>	@ManyToOne(optional=true)<br />
	public Cat getMother() {<br />
		return mother;<br />
	}<br />
	public void setMother(Cat parent) {<br />
		this.mother = parent;<br />
	}</p>
<p>	@Id	@GeneratedValue(strategy=GenerationType.AUTO)<br />
	public int getId() {<br />
		return id;<br />
	}<br />
	public void setId(int id) {<br />
		this.id = id;<br />
	}</p>
<p>	public String getName() {<br />
		return name;<br />
	}<br />
	public void setName(String name) {<br />
		this.name = name;<br />
	}</p>
<p>	public Date getBirthDate() {<br />
		return birthDate;<br />
	}<br />
	public void setBirthDate(Date birthDate) {<br />
		this.birthDate = birthDate;<br />
	}<br />
}<br />
</code></p>
<h3>The entity manager</h3>
<p>The EJB3 entity manager is what used to the session in hibernate. It provides all functionality to store, update and query objects from the database. In the example code below it is created from a EntityManagerFactory which makes use of the persistence.xml configuration file &#8211; you can see the reference to the persistence-unit <em>manager1</em> here.<br />
Using the entity manager a transaction is started, 2 cats are created, linked as mother and kitten and finally persited with a call to persist() of the entity manager. This step is as simple as with a good old hibernate. Same is true for the query part which follows after that &#8211; a parameterized query returns all cats that where born before 1.1.2003.<br />
<code lang="java5"><br />
package example;</p>
<p>import java.text.ParseException;<br />
import java.text.SimpleDateFormat;<br />
import java.util.Iterator;<br />
import java.util.List;</p>
<p>import javax.persistence.EntityManager;<br />
import javax.persistence.EntityManagerFactory;<br />
import javax.persistence.EntityTransaction;<br />
import javax.persistence.Persistence;</p>
<p>import example.pojo.Cat;</p>
<p>public class Test {</p>
<p>	public static void main(String[] args) throws ParseException {</p>
<p>		// Read configuration from META-INF/persistence.xml<br />
		EntityManagerFactory emf = Persistence.createEntityManagerFactory("manager1");</p>
<p>		EntityManager em = emf.createEntityManager();</p>
<p>		// --------- CREATE CATS -----------</p>
<p>		EntityTransaction t = em.getTransaction();<br />
		t.begin();</p>
<p>		// Create two cats<br />
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");<br />
		Cat mimi = new Cat();<br />
		mimi.setName("Mimi");<br />
		mimi.setBirthDate(df.parse("2001-03-01"));<br />
		em.persist(mimi);</p>
<p>		Cat max = new Cat();<br />
		max.setName("Max");<br />
		max.setBirthDate(df.parse("2003-05-18"));<br />
		em.persist(max);</p>
<p>		// Mimi is the mother of max<br />
		mimi.addKitten(max);</p>
<p>		// Commit transaction to store the cats in the database<br />
		t.commit();</p>
<p>		// --------- QUERY CATS -----------</p>
<p>		// Get all cats that where born before 1.1.2003<br />
		List catList = em.createQuery(<br />
	    	"select cat from Cat as cat where cat.birthDate < ?1")<br />
	    	.setParameter(1, df.parse("2003-01-01"))<br />
	    	.getResultList();</p>
<p>		// Print the list of cats with the number of their children<br />
		Iterator catIterator = catList.iterator();<br />
		while (catIterator.hasNext()) {<br />
			Cat mycat = (Cat) catIterator.next();</p>
<p>			System.out.println(mycat.getName() + " children:"+<br />
					mycat.getKittens().size());<br />
		}</p>
<p>		// Close the Entity Manager<br />
		em.close();<br />
		emf.close();<br />
	}</p>
<p>}<br />
</code></p>
<h3>Preliminary conclusion</h3>
<ol>
<li>I realize, this simple example doesn't say much about the feature set of EJB3 compared to the hibernate features (caches, optimized queries, relations, etc..). It is a good starting point for further experiments though which is why I provide the <b>example eclipse project as a download</b> including all required libraries. This means this should run in any 3.1 eclipse out of the box.
<li>Did you notice that none of the import statements reference a hibernate specific package? The application only uses the javax.persistence interface so theoretically you should be able to switch from hibernate to any other ejb3 persistence solution without changing a single line of code.
<li>Getting rid of the hibernate mapping files which had to be edited separately from the code or be generated with xdoclet is a big plus in my opinion. I would move my last project from xdoclet tags to annotations in an instant if there wasn't the requirement to use java 1.4.
</ol>
<h3>Download the example</h3>
<p>If you like to experiment yourself, download the <a href="/wp-content/uploads/2006/04/Ejb3PersistenceTest.zip">Ejb3PersistenceTest.zip (5MB)</a> eclipse project. It contains all hibernate libraries (core, entity manager, annotations) to get you started.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.techbits.de/2006/04/17/ejb3-persistence-with-hibernate/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A trip to java</title>
		<link>http://www.techbits.de/2006/03/19/a-trip-to-java/</link>
		<comments>http://www.techbits.de/2006/03/19/a-trip-to-java/#comments</comments>
		<pubDate>Sun, 19 Mar 2006 22:09:39 +0000</pubDate>
		<dc:creator>Florian</dc:creator>
				<category><![CDATA[general]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[software]]></category>
		<category><![CDATA[beanshell]]></category>
		<category><![CDATA[ejb3]]></category>
		<category><![CDATA[generics]]></category>
		<category><![CDATA[j2se]]></category>
		<category><![CDATA[mda]]></category>
		<category><![CDATA[uml]]></category>

		<guid isPermaLink="false">http://www.techbits.de/2006/03/19/a-trip-to-java/</guid>
		<description><![CDATA[Once again a long time has passed where I couldn&#8217;t find the time or motivation to write a post. I was mainly occupied with the specification of a java application which gave me the opportunity to get to know Sparx &#8230; <a href="http://www.techbits.de/2006/03/19/a-trip-to-java/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Once again a long time has passed where I couldn&#8217;t find the time or motivation to write a post. I was mainly occupied with the specification of a java application which gave me the opportunity to get to know <a href="http://sparxsystems.com/">Sparx System&#8217;s Enterprise Architect</a>. I only used the common uml diagram types and the code generation features for this project and they work pretty well. I&#8217;d love to make use of the more advanced features though and look into the whole <a href="http://en.wikipedia.org/wiki/Model-driven_architecture">MDA</a> approach a bit more. There is a fundamental difference in just drawing some class diagrams and really developing model driven from the ground up. Projects like <a href="http://www.andromda.org/">AndroMDA</a> to generate complete applications look promising and certainly could reduce the expenses for software development but I doubt I&#8217;ll find time to check it out properly any time soon. As for the modelling language I don&#8217;t think everything should be done with UML though &#8211; the approach to model every aspect in UML and using stereotypes to define &#8220;what it means&#8221; makes the modeling too confusing and complex imho. Some interesting views on MDA and Software Factories can be found in the podcast <a href="http://channel9.msdn.com/ShowPost.aspx?PostID=156291#156291">MDA vs. Software Factories</a> and some older episodes.</p>
<p>At the moment I&#8217;m working on a prototype for another java application and got used to the new java 1.5 features like <a href="http://java.sun.com/developer/technicalArticles/J2SE/generics/">generics </a> and the new for each loops. The generics are definately the way to go for typesafe collections and I&#8217;ll try to use them from here on out. I found the wildcard <code>&lt;? extends&gt;</code> and some other constructions confusing at first but I do understand that there are <a href="http://www.fh-wedel.de/~si/seminare/ws05/Ausarbeitung/5.generics/genjava3.htm">several restrictions (german link)</a> when using generics. Someone should publish some design patterns for typical cases that require generics.</p>
<p>For that project I also experimented with <a href="http://www.beanshell.org/">BeanShell</a> which is basically a java scripting interpreter. I&#8217;ll probably use it for custom formulas which are evaluated dynamically within the java application. Easy to use and powerful. </p>
<p>The next component I&#8217;ll look into is <a href="http://www.hibernate.org/299.html">EJB3 persistence using Hibernate</a>. I have worked with the hibernate tools and reverse enginered some database tables but since I already have the POJO classes and don&#8217;t want to create all the old hibernate xml mapping files I might as well check out how to create EJB3 persistence by using annotations. More on that soon.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.techbits.de/2006/03/19/a-trip-to-java/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

