<?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>Andy Gibson &#187; JPA</title>
	<atom:link href="http://www.andygibson.net/blog/tag/jpa/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.andygibson.net/blog</link>
	<description>Open Source Projects &#38; Technical Writings</description>
	<lastBuildDate>Thu, 02 Feb 2012 14:33:32 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language></language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Deterring &#8220;ToMany&#8221; Relationships in JPA models</title>
		<link>http://www.andygibson.net/blog/article/deterring-tomany-relationships-in-jpa-models/</link>
		<comments>http://www.andygibson.net/blog/article/deterring-tomany-relationships-in-jpa-models/#comments</comments>
		<pubDate>Mon, 17 Jan 2011 13:50:38 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[Modeling]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1693</guid>
		<description><![CDATA[This article considers the issues of one to many relationships from the JPA model, and looks at an alternative strategy to provide more efficient and fine grained data access, to build more robust and lightweight applications and web services. A fairly typical use is to have one entity &#8216;owned&#8217; by the other in such a [...]]]></description>
			<content:encoded><![CDATA[<p>This article considers the issues of one to many relationships from the JPA model, and looks at an alternative strategy to provide more efficient and fine grained  data access, to build more robust and lightweight applications and web services.<br />
<span id="more-1693"></span><br />
A fairly typical use is to have one entity &#8216;owned&#8217; by the other in such a way that one entity is said to &#8216;have&#8217; many instances of the other one. A typical example would be customer and orders :</p>
<pre class="brush: java;">
class Customer {

  @OneToMany(mappedBy=&quot;customer&quot;)
  private Set&lt;Order&gt; orders;

}

class Order {
  @ManyToOne
  private Customer customer;
}
</pre>
<p>In this trivial example, the order belongs to a customer, and the customer has a set of orders. We don&#8217;t have a problem with the <code>ManyToOne</code> relationship, especially as it is required in order to map the order back to the customer. When we load an order we will at most get a single reference to a customer.</p>
<p>No, our problem is with the value we get from <code>customer.getOrders()</code> as this set of order entities doesn&#8217;t really serve any useful purpose and can cause more problems than it solves for the following reasons :</p>
<ol>
<li><b>Dumb Relationship</b> &#8211; It will contain every order for this particular customer when you usually only want a subset of the orders that match a set of criteria. You either have to read them all and filter the ones you don&#8217;t want manually (which is what SQL is for) or you end up having to make a call to a method to get the specific entities you are interested in.</li>
<li><b>Unbounded dataset</b> &#8211; How many orders a customer has could vary and you could end up with a customer with thousands of orders. Combined with accidental eager fetching and loading a simple list of 10 people could mean loading thousands of entities.
</li>
<li><b>Unsecured Access</b> &#8211; Sometimes we may want to restrict the items visible to the user based on their security rights. By making it available as a property controlled by JPA we lose that ability or have to implement it further down in the application stack.
<li><b>No Pagination</b> &#8211; Similar to the unbounded dataset, you end up throwing the whole list into the pagination components and letting them sort out what to display. In most cases, you need to treat each dataset like it will eventually contain more than 30 records so you really need to consider pagination early.
</li>
<li><b>Overgrown object graph</b> &#8211; When you request an entity, how much of the object graph do you need? How do you know which pieces to initialize so you can avoid LIEs? This is often the case with JPA, but is also more relevant when you take account of the needs to serialize object graphs to XML or JSON. Sometimes you might need the relationships and sometimes you do not depending on the context you will be using the data in.</li>
<li><b>Rife with pitfalls</b> &#8211; Who saves and cascades what and how do you bind one to the other? You create an order, and assign the customer, do you need to then add it to the customers list of orders or not. What happens if you forget to add it to the customer and you save the customer? Whatever strategy you pick for dealing with this will no doubt end up being implemented inconsistently.
</ol>
<p>(<small>Ok, the first four are really different facets of the same problem, that you can&#8217;t control the data you are getting back.</small>)</p>
<p>So what use are they? Well, they make it really tempting just to use <code>customer.orders</code> in the view which is suitable for some sets of data. They also allow the relationship to be used in ejbql statements, although the inverse of the relationship can also be used in most cases. Specifying this relationship can also allow you to cascade updates/deletes from the customer to the order, but then so can your database.</p>
<h1>Going Granular</h1>
<p>The best alternative I&#8217;ve found is to provide additional methods to obtain the relational information separate from the model. This more granular approach gives you plenty of ways of obtaining data from the database without the dangers and temptations of bad practices. For example, the <code>Order</code> object still has the <code>Customer</code> reference on it, which we use to obtain lists of orders from the data access layer which can be constrained by customer, time frame, or other criteria depending on where it is being used. Also, it allows data to be fetched when needed without having to define a single initialization strategy using annotations or mapping files. The code that knows what pieces of data it needs will have access to facilities to fetch the specific data it needs. Alternatively, the  methods to fetch the data can either be exposed as web services directly or DTO objects can be used to build a data payload to be returned from a single web service that consolidates the calls. Regardless, you don&#8217;t need to worry about setting the JPA fetch or XML/JSON serialization policy permanently in the model.</p>
<p>Some examples might be to fetch orders for a customer in different ways.</p>
<pre class="brush: java;">
public List&lt;Order&gt; getOrders(Long customerId) {...}
public List&lt;Order&gt; getOrders(Long customerId,Date startDate,Date endDate) {...}
public List&lt;Order&gt; getOrders(SearchCriteria searchCriteria,int firstResult,int pageSize) {...}
</pre>
<h1>What about <code>@ManyToMany</code></h1>
<p>Good question. In most cases I find that what starts as a many to many relationship can usually be modeled as a separate entity because when you create a many to many relationship, there is usually additional information stored with that relationship. For example, a Users and Groups <code>ManyToMany</code> relationship has many users belonging to many groups and vice versa. The membership however also probably has start and end dates and also maybe a role within that group. This also exhibits one of the earlier problems in that <code>user.getGroupMemberships()</code> would return all group memberships past and present whereas you probably only want the active ones.  Modeling it as a separate entity means it becomes an entity with two <code>OneToMany</code> relationships.</p>
<p>While there are cases where the many to many relationship is literally just a pair of ids (think blog post tags, many tags to many posts), you could benefit at a later date by using an entity if you decide to add additional information into the relationship.</p>
<p>In summary, moving relational fetches out of the data model and into the data layer means you remove some of the temptations of bad practices and create a library of reusable functions for fetching the data that can be used from different code points.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/deterring-tomany-relationships-in-jpa-models/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Conversational CRUD in Java EE 6</title>
		<link>http://www.andygibson.net/blog/tutorial/pattern-for-conversational-crud-in-java-ee-6/</link>
		<comments>http://www.andygibson.net/blog/tutorial/pattern-for-conversational-crud-in-java-ee-6/#comments</comments>
		<pubDate>Mon, 30 Aug 2010 13:07:33 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Journeyman]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[JSF]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1371</guid>
		<description><![CDATA[This tutorial will demonstrate a pattern for creating CRUD applications in JSF and Java EE 6. While this is not the only way of implementing this mechanism, it does promote re-use and can give you essentially zero code CRUD pages requiring just the view code. The goal is to provide a single structure that provides [...]]]></description>
			<content:encoded><![CDATA[<p>This tutorial will demonstrate a pattern for creating CRUD applications in JSF and Java EE 6. While this is not the only way of implementing this mechanism, it does promote re-use and can give you essentially zero code CRUD pages requiring just the view code. The goal is to provide a single structure that provides the particular feature of being both stateless or conversational where we might want a conversational edit page and a stateless view page. This pattern is based on the <code>EntityHome</code> pattern that was used in JBoss Seam and carries over well to Java EE 6 with CDI. This is something I use all the time to make view/edit pages really quickly and unlike most of the automatic scaffolding in other frameworks, doesn&#8217;t need re-writing to go into production.<br />
<span id="more-1371"></span></p>
<div class="sidenote_right">
<h1>Running in a Servlet Container</h1>
<p>If you are running this in a servlet container or embedded Jetty, you will need to make the following changes :</p>
<ul>
<li>Use the <code>jee6-servlet-sandbox</code> archetype which is only available in Knappsack 1.0.5 upwards.</li>
<li>Remove the <code>@Stateless</code> annotations from the <code>EntityManagerDao</code></li>
<li>Add manual transactions to the entity manager method calls</li>
</ul>
<p>The servlet version of the source code for this project can be downloaded from here (<a href='http://www.andygibson.net/blog/wp-content/uploads/2010/08/crudapp.zip'>Crud App Maven Project Zip</a>).  Just unzip and type <code>mvn jetty:run</code>
</div>
<p>CRUD is an initialism for <strong>C</strong>reate,  <strong>R</strong>etrieve,  <strong>U</strong>pdate,  <strong>D</strong>elete and is applied typically to entity objects or pieces of data in our application. CRUD probably accounts for about 80% of functions in most systems where users enter, update, view and sometimes delete data.</p>
<p>An entity object starts out by being created and then saved to the database. At a later date, the user may want to view the data and then modify and update the data. When the entity is no longer needed, the data will be deleted. This is the long term lifecycle of our data. When an entity is saved, it is saved with a key, or some reference value used to refer to that entity uniquely. Typically, this is an ID field that is often a number. The ID is assigned to the entity when it is saved and used to identify the entity when we want to retrieve, update or delete the entity. </p>
<h1>Create our Application</h1>
<p>We&#8217;ll start by creating a new application using the Knappsack Maven Archetypes. We&#8217;ll use the <code>jee6-sandbox-archetype</code> so we have some data to play with.  Because the Knappsack archetypes are fairly new, you might have problems finding them in your IDEs depending on when you updated from Maven Central, so here is the command line to create the project : </p>
<pre class="brush: plain;">
mvn archetype:generate -DarchetypeGroupId=org.fluttercode.knappsack -DarchetypeArtifactId=jee6-sandbox-archetype -DinteractiveMode=false -DarchetypeVersion=1.0.4 -DgroupId=org.fluttercode.demo -DartifactId=crudapp -Dpackage=org.fluttercode.demo.crudapp
</pre>
<p>You can create the app and then import it into your IDE as needed. We are going to start by creating a very simple DAO style bean that will be used to load, save and refresh objects using the JPA entity manager. We will make it a stateless session bean so that it has transactional capabilities. If you are using the servlet container version, see the sidebar above for necessary changes. The downloadable source code uses the servlet container version so you can run it without an application server.</p>
<ol>
<li>Create a new class called <code>EntityManagerDao</code></li>
<li>Put the following code in the bean
<pre class="brush: java;">
package org.fluttercode.demo.crudapp.bean;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import java.io.Serializable;

import org.fluttercode.demo.crudapp.qualifier.DataRepository;

@Stateless
public class EntityManagerDao implements Serializable {

	@Inject
	@DataRepository
	private EntityManager entityManager;

	public Object updateObject(Object object) {
		return entityManager.merge(object);
	}

	public void createObject(Object object) {
		entityManager.persist(object);
	}

	public void refresh(Object object) {
		entityManager.refresh(object);
	}

	public &lt;T&gt; T find(Class&lt;T&gt; clazz, Long id) {
		return entityManager.find(clazz, id);
	}

	public void deleteObject(Object object) {
		entityManager.remove(object);
	}

}
</pre>
<p>We inject a conversational entity manager into the bean and create methods for create, finding, updating, and removing entities. The <code>DataRepository</code> annotation is a Qualifier that is defined by the archetype and used to access the application&#8217;s default data source.<br />
All this bean really does is provide transaction support on our method calls to the entity manager. It is not a part of the key pattern, just  a mechanism we can use to persist objects transactionally. While this Dao will work for any JPA entity, it is common practice to create Dao objects specific to individual types where you can add helper and additional methods specific to that type.
</li>
</ol>
<h1>Our home bean</h1>
<p>Now we have our support code set up, on to the main feature! We will create a generic home bean that will take an Id and when requested, load the entity bean for that Id. If no Id is available, then we assume a new entity is to be created. Once loaded or created, the entity will be accessible from our JSF pages where we can display or edit the information.</p>
<ol>
<li>Create a new class called <code>org.fluttercode.demo.crudapp.bean.HomeBean</code>. This will be our generic home bean that we use to load and hold our entities.
</li>
<li>Add the following code to make the bean generic and give it an id and entity attribute.
<pre class="brush: java;">
package org.fluttercode.demo.crudapp.bean;

import java.io.Serializable;
import javax.inject.Inject;
import org.fluttercode.demo.crudapp.model.BaseEntity;

public class HomeBean&lt;T extends BaseEntity&gt; implements Serializable {

	@Inject
	private EntityManagerDao entityManagerDao;

	private Long id;
	private T instance;
}
</pre>
<p>Our bean will use the injected <code>EntityManagerDao</code> we just created. The <code>BaseEntity</code> class is a base entity class implemented in the archetype and has the common <code>Id</code> attribute.</li>
<li>Now we want to add the getter method for the instance. What we want to do here is lazy load or create the bean when it is needed. The assumption is that you won&#8217;t request the bean until the home bean has been set up i.e. The id is properly set. The second assumption is that if you request the instance without the Id being set, you are actually creating a new instance.</li>
<li>We&#8217;ll implement this in the getter that calls two other methods, one to create and return a new entity and another to load it. We&#8217;ll also add the getters and setters for the Id.
<pre class="brush: java;">
public T getInstance() {
	if (instance == null) {
		if (id != null) {
			instance = loadInstance();
		} else {
			instance = createInstance();
		}
	}
	return instance;
}

public Long getId() {
	return id;
}
public void setId(Long id) {
	this.id = id;
}
</pre>
</li>
<li>The create or load methods are fairly simply but rely on some reflection magic to get the generic parameter type :
<pre class="brush: java;">
public T loadInstance() {
	return entityManagerDao.find(getClassType(), getId());
}

public T createInstance() {
	try {
		return getClassType().newInstance();
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}

private Class&lt;T&gt; getClassType() {
	ParameterizedType parameterizedType = (ParameterizedType) getClass()
			.getGenericSuperclass();
	return (Class&lt;T&gt;) parameterizedType.getActualTypeArguments()[0];
}
</pre>
</li>
<li>When we edit our entity, we will want to either save the changes, or undo them. We will add two methods to do this, save and cancel and a third utility method called <code>isManaged()</code>.
<pre class="brush: java;">
public boolean isManaged() {
  return getInstance().getId() != null;
}
public String save() {
	if (isManaged()) {
		entityManagerDao.updateObject(getInstance());
	} else {
		entityManagerDao.createObject(getInstance());
	}
	conversation.end();
	return &quot;saved&quot;;
}

public String cancel() {
	conversation.end();
	return &quot;cancelled&quot;;
}
</pre>
<p>We end the conversation when we are done with the data which is when we either save or cancel the changes. Once the conversation is ended, it will be destroyed at the end of the request.
</li>
<li>One last method we want to add is called <code>initConversation</code> that checks to see if we are in a long running conversation, and starts one if we are not. In theory we could put this method anywhere, but here is a good a place as any. We also need to add a <code>Conversation</code> attribute into which we will inject the current conversation.
<pre class="brush: java;">
  	@Inject
  	private Conversation conversation;
  	...
  	...
  	...
	public void initConversation() {
		if (conversation.isTransient()) {
			conversation.begin();
		}
	}
</pre>
</li>
</ol>
<p>This wraps up the coding of our <code>HomeBean</code> that we will use as the backing bean for CRUD pages. Now let&#8217;s try out our new bean by implementing it for our <code>Student</code> entity class and create a page to view and edit our students. </p>
<ol>
<li>Start by creating a new class called <code>org.fluttercode.demo.crudapp.view.StudentHome</code>. We add two class level annotations, one to name the bean so JSF can access it through an EL expression and another to give it a scope. </p>
<pre class="brush: java;">
package org.fluttercode.demo.crudapp.view;

import javax.enterprise.context.ConversationScoped;
import javax.inject.Named;

import org.fluttercode.demo.crudapp.bean.HomeBean;
import org.fluttercode.demo.crudapp.model.Student;

@Named
@ConversationScoped
public class StudentHome extends HomeBean&lt;Student&gt;{

}
</pre>
<p>We subclass the <code>HomeBean</code> and give it our <code>Student</code> class type to tell it what kind of entity we want it to handle. We have given this bean a conversation scope for reasons we&#8217;ll see later.</li>
<li>For our view, create a new page called <code>studentView.xhtml</code> with the following content :
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;ui:composition xmlns=&quot;http://www.w3.org/1999/xhtml&quot;
	xmlns:ui=&quot;http://java.sun.com/jsf/facelets&quot;
	xmlns:f=&quot;http://java.sun.com/jsf/core&quot;
	xmlns:h=&quot;http://java.sun.com/jsf/html&quot;
	xmlns:fn=&quot;http://java.sun.com/jsp/jstl/functions&quot;
	template=&quot;/WEB-INF/templates/template.xhtml&quot;&gt;
	&lt;ui:define name=&quot;content&quot;&gt;
		&lt;f:metadata&gt;
			&lt;f:viewParam name=&quot;id&quot; value=&quot;#{studentHome.id}&quot; /&gt;
		&lt;/f:metadata&gt;
		&lt;h:form&gt;
			&lt;h:outputText value=&quot;ID&quot; styleClass=&quot;caption&quot; /&gt;
			&lt;h:outputText value=&quot;#{studentHome.instance.id}&quot; styleClass=&quot;value&quot; /&gt;

			&lt;h:outputText value=&quot;First Name&quot; styleClass=&quot;caption&quot; /&gt;
			&lt;h:outputText value=&quot;#{studentHome.instance.firstName}&quot;
				styleClass=&quot;value&quot; /&gt;

			&lt;h:outputText value=&quot;Last Name&quot; styleClass=&quot;caption&quot; /&gt;
			&lt;h:outputText value=&quot;#{studentHome.instance.lastName}&quot;
				styleClass=&quot;value&quot; /&gt;

			&lt;h:outputText value=&quot;GPA&quot; styleClass=&quot;caption&quot; /&gt;
			&lt;h:outputText value=&quot;#{studentHome.instance.gpa}&quot; styleClass=&quot;value&quot; /&gt;

			&lt;h:link outcome=&quot;studentEdit.jsf&quot; includeViewParams=&quot;true&quot;
				value=&quot;Edit #{studentHome.instance.name}&quot; style=&quot;margin-right : 24px&quot; /&gt;
			&lt;h:link outcome=&quot;studentEdit.jsf&quot; value=&quot;Create Student&quot; /&gt;
		&lt;/h:form&gt;
	&lt;/ui:define&gt;
&lt;/ui:composition&gt;
</pre>
<p>Everything up to the <code>f:metadata</code> tag is boilerplate which includes pulling the template into the page. The <code>f:metadata</code> tag tells JSF to take a parameter called id and put it in the <code>studentHome.id</code> attribute. This is done before the page is rendered as part of our initial setup for the bean so we know which entity to load.</p>
<p>In the view code we bind our text output components to attributes on the instance in the student home bean. We also styled the components so we can alter the display using CSS styles.<br />
At the bottom we have added a couple of links using the new JSF 2.0 <code>h:link</code> component to an as yet unwritten JSF page called <code>studentEdit.xhtml</code>. In the first link, we get JSF to pass in the view parameters automatically which in this case is the student Id value. Our second link is to create a new student which means we call the same <code>studentEdit.xhtml</code> page without passing the id as a parameter which we do by leavinging the <code>includeViewParams</code> attribute set to false.</p>
<p>Note that the <code>h:form</code> tag isn&#8217;t necessary, but will make the next step easier and allow us to add form controls to this form should we want to.
</li>
<li>If you are running JBoss Developer Tools or Netbeans, you should be able to see the <code>Student</code> attributes in the auto-completion (very cool).  If you open this page in a browser with an id (<a href="http://localhost:8080/crudapp/studentView.jsf?id=3">http://localhost:8080/crudapp/studentView.jsf?id=3</a>) you will see the following person displayed :
<div class="contentBox alignCenter">
<a href="http://www.andygibson.net/blog/wp-content/uploads/2010/08/crud_pattern_1.png"><img src="http://www.andygibson.net/blog/wp-content/uploads/2010/08/crud_pattern_1-300x189.png" alt="CRUD Pattern View Screenshot" title="CRUD Pattern View Screenshot" width="300" height="189" /></a>
</div>
<p><small>We did change two of the archetype CSS styles in the file <code>screen.css</code> to the following : </small></p>
<pre class="brush: plain;">
.caption {
	float: left;
	width: 100px;
	padding-top : 2px;
}

.value {
	display : block;
	margin-bottom : 8px;
	margin-right: 8px;
}
</pre>
</li>
</ol>
<p>As you can see, we can display the student details for the given id. The page for editing this person is very similar, so similar in fact that we are going to start by copying the student view page and making 3 line changes and adding a page event.</p>
<ol>
<li>Copy the <code>studentView.xhtml</code> file and paste it in the same folder with the name <code>studentEdit.xhtml</code>. Open it up and make the following changes (highlighted in the source) : </p>
<ul>
<li>Change the <code>outputText</code> components bound to attributes to <code>inputText</code> components. </li>
<li>Add the <code>preRenderView</code> event the the <code>f:metadata</code> tag.</li>
<li>Set the <code>rendered</code> attribute on the ID label and value since new entities don&#8217;t have a value to display</li>
</ul>
<pre class="brush: xml; highlight: [4,5,8,9,12,15,18];">
&lt;ui:define name=&quot;content&quot;&gt;
	&lt;f:metadata&gt;
		&lt;f:viewParam name=&quot;id&quot; value=&quot;#{studentHome.id}&quot; /&gt;
		&lt;f:event type=&quot;preRenderView&quot;
			listener=&quot;#{studentHome.initConversation}&quot; /&gt;
	&lt;/f:metadata&gt;
	&lt;h:form&gt;
		&lt;h:outputText value=&quot;ID&quot; styleClass=&quot;caption&quot; rendered=&quot;#{studentHome.managed}&quot;/&gt;
		&lt;h:outputText value=&quot;#{studentHome.instance.id}&quot; styleClass=&quot;value&quot; rendered=&quot;#{studentHome.managed}&quot;/&gt;

		&lt;h:outputText value=&quot;First Name&quot; styleClass=&quot;caption&quot; /&gt;
		&lt;h:inputText value=&quot;#{studentHome.instance.firstName}&quot; styleClass=&quot;value&quot; /&gt;

		&lt;h:outputText value=&quot;Last Name&quot; styleClass=&quot;caption&quot; /&gt;
		&lt;h:inputText value=&quot;#{studentHome.instance.lastName}&quot; styleClass=&quot;value&quot; /&gt;

		&lt;h:outputText value=&quot;GPA&quot; styleClass=&quot;caption&quot; /&gt;
		&lt;h:inputText value=&quot;#{studentHome.instance.gpa}&quot; styleClass=&quot;value&quot; /&gt;

		&lt;h:commandButton value=&quot;Save&quot; action=&quot;#{studentHome.save}&quot; style=&quot;margin-right : 8px&quot; /&gt;
		&lt;h:commandButton value=&quot;Cancel&quot; action=&quot;#{studentHome.cancel}&quot; immediate=&quot;true&quot; style=&quot;margin-right : 8px&quot; /&gt;
		&lt;/h:form&gt;
	&lt;/ui:define&gt;
</pre>
<p>If you launch this page now (<a href="http://localhost:8080/crudapp/studentEdit.jsf?id=3">http://localhost:8080/crudapp/studentEdit.jsf?id=3</a>), you will see that we have an editor filled with the attribute values that can be changed. </p>
<div class="contentBox alignCenter">
<a href="http://www.andygibson.net/blog/wp-content/uploads/2010/08/crud_pattern_edit.png"><img src="http://www.andygibson.net/blog/wp-content/uploads/2010/08/crud_pattern_edit-300x274.png" alt="CRUD Pattern Edit Screenshot" title="CRUD Pattern Edit Screenshot" width="300" height="274" /></a>
</div>
</li>
</ol>
<p>That was pretty easy! The reason being is that we re-used the <code>StudentHome</code> bean in our edit page because it performs the same role in providing the requested entity based on the bean&#8217;s id value. We don&#8217;t need to tell the home bean that it is being used somewhere else because the page pulls the bean into the page.</p>
<h1>Conversational or Not?</h1>
<p>It&#8217;s important to notice that in the view page we do not call the method to initialize the conversation. Conversational beans that are not in a long running conversation are reduced to request scoped because the conversation context is destroyed at the end of the request if it is not marked as long running. This means that our view page is fairly stateless since the <code>StudentHome</code> bean used in this page is effectively request scoped.  This is actually a good thing since when we press the refresh button, the page is regenerated from scratch instead of using an older version of the data held in the conversation.</p>
<p>On the other hand, the edit page does call the <code>initConverstion</code> method which starts a conversation. This means that the edit page is conversational which is good because it carries the state from one request to the next without relying on our page to support that state or having to reload it each time. Without the conversation we would have to manually propagate the id value from one request to the next, and possibly other values that are a part of the entity but not edited on the page. For example, if we had an <code>addedDate</code> attribute, we might want to display it, but not edit it, but without conversations we have to resort to either putting it in a hidden field in the form, or re-loading the object to get the value on postback. Otherwise how can we have the right value when we save the edited entity to the database?</p>
<p>This dual nature of the conversation scope is a very useful feature of CDI (and Seam before it) because it allows one bean to act in two different scopes depending on whether the conversation is long running or not which is ideal for view and edit pages. </p>
<p>This is a simple design that can be re-used anywhere you need to edit an entity with little or no code changes. </p>
<p>You can download the servlet version of the demo project from here (<a href='http://www.andygibson.net/blog/wp-content/uploads/2010/08/crudapp.zip'>Crud App Maven Project Zip</a>). Just unzip it and run <code>mvn jetty:run</code></p>
<h1>Additional Points</h1>
<p>Here are some addition points that are not a core part of the demonstration but flesh things out a bit more. All these changes are included in the maven project that can be downloaded.</p>
<h2>Do we need an Entity Manager DAO?</h2>
<p>Here we used a simple DAO to wrap calls to the EntityManager. There&#8217;s no reason you couldn&#8217;t make your Entity Home bean an EJB, inject the entity manager and persist the entities directly. With a separate entity manager DAO it makes writing code for servlet containers cleaner since the explicit transactions are bundled in the DAO. Also, it is possible to write one DAO bean for Java EE 6 servers and another for Servlet containers and switch between them using <code>@Alternative</code>.</p>
<h2>Deleting is a part of CRUD</h2>
<p>I left deleting out primarily because it is fairly simple and the focus was really on the retrieve and update pieces which is often trickier. To implement delete, we add a method to the <code>HomeBean</code> to end the conversation and delete the item.</p>
<pre class="brush: java;">
public String delete() {
	entityManagerDao.deleteObject(getInstance());
	conversation.end();
	return &quot;deleted&quot;;
}
</pre>
<p>Now we just need to add a button to call the delete method from the edit page.</p>
<pre class="brush: xml;">
&lt;h:commandButton value=&quot;Delete&quot; action=&quot;#{studentHome.delete}&quot;/&gt;
</pre>
<p>When we click the button, we delete the entity, and return the action value &#8220;deleted&#8221; for which, in the next section, we&#8217;ll add navigation to the home page.</p>
<h2>Finding your way around</h2>
<p>We haven&#8217;t included any navigation here so when you save or cancel changes, you stay on the same page. So far I&#8217;ve left it out because it isn&#8217;t central to the CRUDness of the tutorial. However, we can easily add some navigation in <code>faces-config.xml</code>.</p>
<pre class="brush: xml;">
	&lt;navigation-rule&gt;
		&lt;from-view-id&gt;/studentEdit.xhtml&lt;/from-view-id&gt;
		&lt;navigation-case&gt;
			&lt;from-outcome&gt;saved&lt;/from-outcome&gt;
			&lt;to-view-id&gt;/studentView.xhtml&lt;/to-view-id&gt;
			&lt;redirect include-view-params=&quot;true&quot; /&gt;
		&lt;/navigation-case&gt;

		&lt;navigation-case&gt;
			&lt;from-outcome&gt;cancelled&lt;/from-outcome&gt;
			&lt;if&gt;#{studentHome.managed}&lt;/if&gt;
			&lt;to-view-id&gt;/studentView.xhtml&lt;/to-view-id&gt;
			&lt;redirect include-view-params=&quot;true&quot; /&gt;
		&lt;/navigation-case&gt;

		&lt;navigation-case&gt;
			&lt;from-outcome&gt;cancelled&lt;/from-outcome&gt;
			&lt;if&gt;#{!studentHome.managed}&lt;/if&gt;
			&lt;to-view-id&gt;/home.xhtml&lt;/to-view-id&gt;
			&lt;redirect include-view-params=&quot;true&quot; /&gt;
		&lt;/navigation-case&gt;

		&lt;navigation-case&gt;
			&lt;from-outcome&gt;deleted&lt;/from-outcome&gt;
			&lt;to-view-id&gt;/home.xhtml&lt;/to-view-id&gt;
		&lt;/navigation-case&gt;

	&lt;/navigation-rule&gt;
</pre>
<p>Notice that when we cancel the changes, we go to either the view page or the home page depending on whether the entity exists in the database.</p>
<h2>Better Homes</h2>
<p>Let&#8217;s also add on a better home page so you can see and select different students. Add the following method to the <code>DataFactory.java</code> class that comes with the archetype.</p>
<pre class="brush: java;">
	@Produces
	@Named(&quot;students&quot;)
	public List&lt;Student&gt; getStudents() {
		List&lt;Student&gt; students = entityManager.createQuery(
				&quot;select s from Student s&quot;).setMaxResults(20)
				.getResultList();
		return students;
	}
</pre>
<p>Open up the the <code>home.xhtml</code> page and change the content to :</p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;ui:composition xmlns=&quot;http://www.w3.org/1999/xhtml&quot;
	xmlns:ui=&quot;http://java.sun.com/jsf/facelets&quot;
	xmlns:f=&quot;http://java.sun.com/jsf/core&quot;
	xmlns:h=&quot;http://java.sun.com/jsf/html&quot;
	xmlns:fn=&quot;http://java.sun.com/jsp/jstl/functions&quot;
	template=&quot;/WEB-INF/templates/template.xhtml&quot;&gt;
	&lt;ui:define name=&quot;content&quot;&gt;
		&lt;h1&gt;Courses&lt;/h1&gt;
		&lt;h:form&gt;
			&lt;h:dataTable value=&quot;#{students}&quot; var=&quot;v_student&quot;
				styleClass=&quot;dataTable&quot; rowClasses=&quot;odd,even&quot;&gt;
				&lt;h:column&gt;
					&lt;f:facet name=&quot;header&quot;&gt;Id
				&lt;/f:facet&gt;
				#{v_student.id}
			&lt;/h:column&gt;

				&lt;h:column&gt;
					&lt;f:facet name=&quot;header&quot;&gt;Name
				&lt;/f:facet&gt;
					&lt;h:link outcome=&quot;studentView.jsf?id=#{v_student.id}&quot;
						value=&quot;#{v_student.name}&quot; /&gt;
				&lt;/h:column&gt;

			&lt;/h:dataTable&gt;
		&lt;/h:form&gt;
		&lt;h:link outcome=&quot;studentEdit.jsf&quot; value=&quot;Create Student&quot; /&gt;

	&lt;/ui:define&gt;
&lt;/ui:composition&gt;
</pre>
<p>This will list all the students and let you edit them or add new ones. The project source that can be downloaded (<a href='http://www.andygibson.net/blog/wp-content/uploads/2010/08/crudapp.zip'>Crud App Maven Project Zip</a>) includes these changes plus validation error messages on controls.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/tutorial/pattern-for-conversational-crud-in-java-ee-6/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Demo Application Using JSF, JPA, CDI with Jetty</title>
		<link>http://www.andygibson.net/blog/news/demo-application-using-jsf-jpa-cdi-with-jetty/</link>
		<comments>http://www.andygibson.net/blog/news/demo-application-using-jsf-jpa-cdi-with-jetty/#comments</comments>
		<pubDate>Tue, 24 Aug 2010 13:51:50 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[News]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[Demo]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[Knappsack]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1417</guid>
		<description><![CDATA[The previous version of the Knappsack Maven Archetypes included archetypes for creating projects using JSF, JPA, CDI and Bean Validation that can run in a servlet container such as Jetty or Tomcat. In order to put it through its paces I decided to create a little test social bookmarking application that lets users create accounts, [...]]]></description>
			<content:encoded><![CDATA[<p>The previous version of the <a href="http://www.andygibson.net/blog/projects/knappsack/">Knappsack Maven Archetypes</a> included archetypes for creating projects using JSF, JPA, CDI and Bean Validation that can run in a servlet container such as Jetty or Tomcat. In order to put it through its paces I decided to create a little test social bookmarking application that lets users create accounts, and when logged in, add bookmarks and tag them. Users that are not logged in can view the bookmarks and filter them by user or tag, and the results are paginated.<br />
<span id="more-1417"></span></p>
<p>The demo application is now included in the latest version of the Knappsack archetypes (1.0.5) which are in the central repository. The GAV information is : </p>
<pre class="brush: xml;">
&lt;groupId&gt;org.fluttercode.knappsack&lt;/groupId&gt;
&lt;artifactId&gt;jee6-servlet-demo-archetype&lt;/artifactId&gt;
&lt;version&gt;1.0.5&lt;/version&gt;
</pre>
<p>Or you can just create a new application from the command line with :</p>
<pre class="brush: plain;">
mvn archetype:generate -DarchetypeGroupId=org.fluttercode.knappsack -DarchetypeArtifactId=jee6-servlet-demo-archetype -DinteractiveMode=false -DarchetypeVersion=1.0.5 -DgroupId=org.application -DartifactId=bookmarxrus -Dpackage=org.application
</pre>
<p>This lets you create a new instance of the demo application from the archetype so you can play with it (and break it!). </p>
<p>Alternatively, if you just want to poke around, you can just download the projects maven source from here (<a href='http://www.andygibson.net/blog/wp-content/uploads/2010/08/bookmarxrus.zip'>Bookmarking Java EE 6 Servlet Demo</a>) , unzip it and use <code>mvn jetty:run</code> to start the app with the embedded Jetty instance and go to <a href="http://localhost:8080/bookmarxrus/">http://localhost:8080/bookmarxrus/</a>.</p>
<p>The demo comes with pre-built data and a list of users, tags and URLs to get started with.</p>
<div class="contentBox alignCenter" >
<a href="http://www.andygibson.net/blog/wp-content/uploads/2010/08/bookmarkapp_screenshot1.png"><img src="http://www.andygibson.net/blog/wp-content/uploads/2010/08/bookmarkapp_screenshot1-300x239.png" alt="Bookmark Application Screenshot" title="Bookmark Application Screenshot" width="300" height="239"  /></a>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/news/demo-application-using-jsf-jpa-cdi-with-jetty/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Try Java EE 6 without the commitment</title>
		<link>http://www.andygibson.net/blog/news/try-java-ee-6-without-the-commitment/</link>
		<comments>http://www.andygibson.net/blog/news/try-java-ee-6-without-the-commitment/#comments</comments>
		<pubDate>Thu, 12 Aug 2010 15:24:22 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[News]]></category>
		<category><![CDATA[Archetypes]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[Knappsack]]></category>
		<category><![CDATA[Maven]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1343</guid>
		<description><![CDATA[The latest version of the Knappsack Maven Archetypes now supports creating Java EE 6 applications for servlet containers. These projects includes configuration for core Java EE 6 technologies such as JSF, CDI, JPA and Bean Validation and can be run from the command line using the embedded Jetty and Tomcat servlet containers. Also with this [...]]]></description>
			<content:encoded><![CDATA[<p>The latest version of the Knappsack Maven Archetypes now supports creating Java EE 6 applications for servlet containers. These projects includes configuration for core Java EE 6 technologies such as JSF, CDI, JPA and Bean Validation and can be run from the command line using the embedded Jetty and Tomcat servlet containers.</p>
<p>Also with this latest release, all the archetypes are available in the Central Maven Repository which means you can dive straight in and create a new Maven project using these archetypes :<br />
<span id="more-1343"></span></p>
<ol>
<li>In the command line, or in a script file, issue the following :
<pre class="brush: plain;">
mvn archetype:generate -DarchetypeGroupId=org.fluttercode.knappsack -DarchetypeArtifactId=jee6-servlet-minimal-archetype -DinteractiveMode=false -DarchetypeVersion=1.0.4 -DgroupId=org.application -DartifactId=servletminimal -Dpackage=org.application
</pre>
<p>This will create the new project based on the java ee 6 minimal servlet archetype.
</li>
<li>Go into the directory using <code>cd servletminimal</code></li>
<li>In the project directory, issue the command <code>mvn clean jetty:run</code></li>
<li>Navigate to <a href="http://localhost:8080/servletminimal/">http://localhost:8080/servletminimal/</a> </li>
<li>Tinker away with it</li>
</ol>
<div class="contentBox alignCenter">
<a href="http://www.andygibson.net/blog/wp-content/uploads/2010/08/screenshot.png" target="_blank"><img src="http://www.andygibson.net/blog/wp-content/uploads/2010/08/screenshot-300x188.png" alt="Servlet Minimal Screenshot" title="Servlet Minimal Screenshot" width="300" height="188" class="alignnone size-medium wp-image-1349" /></a><br />
</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/news/try-java-ee-6-without-the-commitment/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Knappsack Archetypes Part 2</title>
		<link>http://www.andygibson.net/blog/article/knappsack-archetypes-part-2/</link>
		<comments>http://www.andygibson.net/blog/article/knappsack-archetypes-part-2/#comments</comments>
		<pubDate>Thu, 12 Aug 2010 15:03:07 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Apprentice]]></category>
		<category><![CDATA[Archetypes]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[Knappsack]]></category>
		<category><![CDATA[Maven]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1097</guid>
		<description><![CDATA[In part 1, we looked at the basic structure and configuration of the project that is common in all the archetypes. This time we&#8217;ll look at the minimal archetype that contains some more functionality and a number of different classes used to implement that functionality. The Java EE 6 Minimal Archetype While there is still [...]]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://www.andygibson.net/blog/article/knappsack-archetypes-part-1/">part 1</a>, we looked at the basic structure and configuration of the project that is common in all the archetypes. This time we&#8217;ll look at the minimal archetype that contains some more functionality and a number of different classes used to implement that functionality. <span id="more-1097"></span></p>
<h1>The Java EE 6 Minimal Archetype</h1>
<p>While there is still only one web page in the project, there are now a few more classes provided. These have been grouped into packages off the main package folder.</p>
<table>
<tr>
<th>Package</th>
<th>Description</th>
</tr>
<tr>
<td><code>bean</code></td>
<td>The <code>bean</code> package contains the <code>EntityManager</code> producer and also a dao object for fetching and persisting <code>Person</code> objects as a stateless EJB (and a local interface).</td>
</tr>
<tr>
<td><code>model</code></td>
<td>Contains the JPA model for ther application which in this case is just one <code>Person</code> class</td>
</tr>
<tr>
<td><code>qualifier</code></td>
<td>Contains the qualifier used to specify injection points for	the <code>EntityManager</code></td>
</tr>
<tr>
<td><code>view</code></td>
<td>Contains the backing beans for the JSF view. These beans provide server side logic for the JSF pages, usually by invoking functions on the service beans in the <code>bean</code> package. The <code>HelloBean</code> accepts a user entered name and returns a message. The <code>PersonBean</code> has a person entity that can be modified by a JSF page and then persisted to the database. There is also a method to return the list of previously saved people from the database.</td>
</tr>
</table>
<div class="sidenote_right">
<h1>Layered code</h1>
<p>We have a fairly clear separation of concerns with the different packages. The EJBs in the <code>bean</code> and <code>qualifier</code> packages don&#8217;t have any dependency on JSF while the beans in the <code>view</code> package are for JSF support only. Such organization means that you could put the contents of the bean and qualifier packages into a separate jar and re-use them with a different view framework. Technically, because they are also POJOs you could use them in a non-EJB environment.</div>
<h2>Producing Entity Managers</h2>
<p>The <code>EntityManager</code> is produced in the <code>DataRepositoryProducer</code> bean by returning the persistence context that was injected into the stateless bean by the container. When an entity manager needs to be injected into an injection point, this method is used to produce one. It is marked as <code>@ConversationScoped</code> so it can participate in CDI conversations. The <code>@DataRepository</code> annotation is a qualifier annotation used to mark what kind of entity manager you are producing and therefore can only be injected into injection points with the same annotation. This is useful if there are multiple databases used to distinguish between different entity managers produced.</p>
<h2>Service Beans</h2>
<p>In the <code>PersonDao</code> we inject the <code>EntityManager</code> that is then used in the other methods to save and fetch objects. In EJB 3.1 the default transaction attribute is <code>Required</code> for EJB methods so we don&#8217;t need to specify any transaction handling on the methods.</p>
<p />
The <code>PersonDao</code> is injected into the <code>view/PersonBean</code> class so as the view needs to fetch or update data, the dao can be used to provide those functions.</p>
<p />
If there was a mechanism that we could use to provide transactions on CDI (non-EJB) beans, then we wouldn&#8217;t really need EJBs, but as it is, we do. Nothing is stopping us from later changing the EJBs to CDI Managed beans with sufficient transaction support.</p>
<p />
<h2>JPA Model</h2>
<p>The only model class we use is the <code>Person</code> class that has properties for first name, last name and an integer Id value. On the name fields, we have specified a number of validators as well as the column size using annotations. These validators check that the field is not empty, or null and does not have a length greater than 25 characters.</p>
<p>Now we&#8217;ve covered the server side code, let&#8217;s take a look at the JSF page that uses these beans in <code>home.xhtml</code>. </p>
<h2>JSF Content</h2>
<p>The single page in this archetype is split into three different sections that test different parts of the environment.</p>
<p>The first part is producing the hello message from the <code>helloBean</code> class. The class is annotated with <code>@Named("helloBean")</code> which lets us reference this bean from the JSF page. The method <code>getHelloMessage()</code> returns a fixed string which is displayed in the page by using the EL expression <code>#{helloBean.helloMessage}</code>. This tells JSF to	get the <code>helloMessage</code> property from the bean called <code>helloBean</code>. The bean name is resolved using an EL expression resolver that looks up	the bean name in the beans registered with CDI using the <code>@Named</code> annotation.</p>
<p />
If you are using JBoss Developer Tools and have enabled CDI for this application (right click on project, click <i>Configure->Add CDI Support</i>, you can go into the JSF page and ctrl+click on the expression (either the bean name or the property name) and the IDE will go to the point in the code that the expression is defined.</p>
<p />
You can interact with the CDI hello bean by entering your name and clicking the submit button which posts your name back to the backing bean and when the page is re-rendered, your name appears in the message below the submit button. Again, the control is bound to the <code>name</code>	property of the <code>helloBean</code> bean which is then used to return the correct message to the user when the page is re-rendered.</p>
<p/>
The final section uses JSF and CDI to edit an instance of a <code>Person</code> object on the CDI backing bean, with JPA persisting the object and Bean Validation providing validation for the JSF page. JPA also returns a list of the people previously saved. The <code>PersonBean</code> class has the <code>@Named</code> annotation which gives it the name <code>personBean</code> and it is marked with a <code>@RequestScoped</code> annotation. The bean has a person instance that is used as the model for the JSF page input boxes. The text boxes are defined for the first and last names and bound to the person entity on the <code>personBean</code> bean. Each input has a <code>h:message</code> JSF tag that reports errors for that input value. This will report errors on the person bean based on the validators we specified on the model.  In the JSF page, the Add button calls the <code>savePerson</code> method on the <code>personBean</code> backing bean which uses the person dao implementation to persist the <code>person</code> entity in the backing bean. JSF automatically includes validation specified on the JPA model and will report errors back to the user for invalid input.</p>
<p/>Underneath the person data entry, there is a list of names that have already been entered. Just enter a new name and click add to see the new name appear.This is fetched from the backing bean using the dao that is injected into it.</p>
<h1>Using the app for yourself</h1>
<p>If you want to create a new application from this archetype, you will probably want to delete the following items.</p>
<pre>
/bean/PersonDao.java
/bean/PersonDaoLocal.java
/model/Person.java
/view/HelloBean.java
/view/PersonBean.java
</pre>
<p>While you may want to re-use the template, or a modified version of it, you won&#8217;t need the content in the <code>home.xhtml</code> file. You can remove the content surrounded by the <code>&lt;ui:define name="content"&gt;</code> tags.  Alternatively, you can just create a new project using the jee6-basic-archetype which has none of this additional code.</p>
<p>In the next section we&#8217;ll start looking at the JPA model and pre-defined data in the sandbox archetype.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/knappsack-archetypes-part-2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Knappsack Archetypes are now in the Maven Central Repository</title>
		<link>http://www.andygibson.net/blog/news/knappsack-archetypes-are-now-in-the-maven-central-repository/</link>
		<comments>http://www.andygibson.net/blog/news/knappsack-archetypes-are-now-in-the-maven-central-repository/#comments</comments>
		<pubDate>Thu, 12 Aug 2010 14:48:20 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[News]]></category>
		<category><![CDATA[Archetypes]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[Weld]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1329</guid>
		<description><![CDATA[I have finally got around to putting the Mavan Java EE 6 Archetypes into the Maven Central Repository. This means you no longer have to manually download and install the Archetypes, they should be available for you to use out of the box. In some cases, depending on how you are creating your projects, you [...]]]></description>
			<content:encoded><![CDATA[<p>I have finally got around to putting the Mavan Java EE 6 Archetypes into the Maven Central Repository. This means you no longer have to manually download and install the Archetypes, they should be available for you to use out of the box. In some cases, depending on how you are creating your projects, you may need to refresh or update your Repository indexes in the IDE before they are visible. </p>
<p>In Eclipse (with m2Eclipse installed), you open the Maven Repositories view, locate the Central Repository in the global repositories, and right click and select update index to make the archetypes available.</p>
<p>To create a new project from the command line, you can copy the following command into a script or batch file and edit it to setup your own group and archetype values.</p>
<pre class="brush: plain;">
mvn archetype:generate -DarchetypeGroupId=org.fluttercode.knappsack -DarchetypeArtifactId=jee6-sandbox-demo-archetype -DinteractiveMode=false -DarchetypeVersion=1.0.4 -DgroupId=org.application -DartifactId=sandboxdemo -Dpackage=org.application
</pre>
<p>The new version includes the archetypes for creating Java EE 6 applications in servlet containers which lets you play around with CDI, JSF, JPA, validation and other JEE 6 technologies using an embedded servlet container from the command line.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/news/knappsack-archetypes-are-now-in-the-maven-central-repository/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Knappsack Archetypes Part 1</title>
		<link>http://www.andygibson.net/blog/article/knappsack-archetypes-part-1/</link>
		<comments>http://www.andygibson.net/blog/article/knappsack-archetypes-part-1/#comments</comments>
		<pubDate>Sun, 01 Aug 2010 16:28:53 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Apprentice]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[EJB]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[Knappsack]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1093</guid>
		<description><![CDATA[This set of articles will document the contents of the Java EE archetypes for Maven. The archetypes come in four flavors, basic,minimal, sandbox and sandbox demo with each one being based on the previous one. In part 1, we&#8217;ll give an overview of the archetypes and the structure and configuration used in all of the [...]]]></description>
			<content:encoded><![CDATA[<p>This set of articles will document the contents of the Java EE archetypes for Maven. The archetypes come in four flavors, basic,minimal, sandbox and sandbox demo with each one being based on the previous one. In part 1, we&#8217;ll give an overview of the archetypes and the structure and configuration used in all of the archetypes.<span id="more-1093"></span></p>
<h1>The Java EE 6 Archetypes</h1>
<p>These Maven archetypes will help developers to get up and running with a new Java EE project quickly by creating the project structure that includes pre-defined configuration files. This lets developers create a project, remove parts they don&#8217;t need, and tweak those they want to keep. The balance is to provide something useful without burdening developers with a bunch of unwanted code and configuration. The basic and minimal archetypes serve this purpose. The basic archetype contains virtually no content, just configuration and a JSF page to confirm that it is working. The minimal archetype contains just a single page of content that demonstrates that JSF, JPA, CDI and validation are working. There are also two additional archetypes for servlet containers that can be used to run core features of Java EE 6 in a servlet contain such as Tomcat or Jetty.</p>
<p>The sandbox archetype takes things a bit further by adding a simple JPA model pre-populated with data. This gives developers a sandbox to play in with everything configured and data to use so they can test out ideas or play around with different pieces of Java EE. I also plan on using it as the foundation project for tutorials and articles on Java EE 6 that developers can follow along with. It removes the need to create and document creating a project with a data model and example data for each tutorial. With a pre-built tutorial project we can dive right in to the meat of the tutorial without the boilerplate.</p>
<p>The sandbox-demo archetype takes the sandbox application and extends it into a full featured application (albeit a contrived one) that demonstrates a number of features of Java EE 6, and gives developers an idea on how to get started developing applications using the Java EE stack. The demo is by no means perfect, it is mostly the bare minimum required to implement the necessary functionality. Again, it provides a good project to launch tutorials from by showing developers how to fix those little problems in the demo application. The demo also fills a gap in demonstrating to new developers how to work with these different technologies and integrate them.</p>
<p>These articles will cover the different archetypes and explain the functionality and features in each. We&#8217;ll start by covering the very basics, which is the creation of the project structure and configuration in the basic archetype which is also shared with all of the archetypes.</p>
<h1>The jee6-basic-archetype</h1>
<p>The basic archetype is a Maven project that is configured and ready to deploy in a Java EE 6 container. It contains the configuration files necessary to start up the Java EE services such as CDI, JPA and JSF as well as the dependencies in the <code>pom.xml</code> file.</p>
<p/>
In the root directory of the new project, we have the <code>pom.xml</code> file and a <code>readme.txt</code> which contains a description of the project and notes on how to deploy it.<br />
The <code>src/main/resources/</code> folder contains resources that the application may need. The <code>META-INF</code> sub folder contains the <code>persistence.xml</code> file which defines the JPA datasource name and sets properties for the JPA provider. If you are deploying to JBoss you are all set to go with the <code>DefaultDS</code> datasource, but for Glassfish, you will need to specify the <code>jdbc/__default</code> datasource instead which is commented out in the file, and remove the <code>DefaultDS</code> definition.</p>
<p/>
The main web content resides in the <code>src\main\webapp</code> folder which is structured as so :</p>
<div class="figure" style="width : 90%">
<h1>Web folder structure and content</h1>
<pre>
src/main/webapp			  Top level webapp folder
 |
 |-META-INF
 |    |-context.xml	 	  Configuration file for tomcat
 |
 |-resources			  Resources folder for JSF resources
 |  |-css			  CSS folder for stylesheets
 |     |
 |     |-screen.css	 	  Default stylesheet
 |
 |-WEB-INF			  Standard WEB-INF folder
 |   |-templates	   	  Templates folder for JSF templates
 |   |    |-template.xhtml     	  Default template file
 |   |
 |   |-beans.xml		  Indicates that this archive file has CDI beans
 |   |-faces-config.xml		  Configuration file for JSF
 |   |-web.xml			  web.xml file containing JSF configuration
 |
 |-home.xhtml			  Default home page using the WEB-INF\template\template.xhtml
 |-index.html			  Default file used to redirect to the home.jsf page
</pre>
</div>
<p>The <code>beans.xml</code>,<code>faces-config.xml</code> and the <code>web.xml</code> files have very little in them. The <code>web.xml</code> file provides the definition and mapping for the the faces servlet. The <code>beans.xml</code> is required to signal the container that this archive contains CDI beans and should be processed by the CDI deployer. This file could have other content if you use alternatives, decorators or interceptors.</p>
<div class="sidenote_right">
<h1>Servlet Schema Version</h1>
<p>The schema version for the <code>web.xml </code> defaults to 2.5 because of problems with Eclipse not recognizing the schema as valid when creating the project. For the most part, everything will work the same, but if it must be version 3.0 or later you can change once the project has been created without any problems.
</div>
<p>Pretty much everything in the <code>webapp</code> folder can be used in a new application, and it isn&#8217;t that difficult to rename and move elements (templates, page file names etc) to get everything how you want it set up. In general, xml files shouldn&#8217;t be moved or renamed, but everything else can be.  </p>
<p/>
If you are starting a new project, your first steps would be to move/rename/edit the template, <code>home.xhtml</code> and <code>screen.css</code> pages to your liking. You would also want to delete the <code>readme.txt</code> file.</p>
<p/>
The bulk of the content is in the  <code>pom.xml</code> file which specifies all the depencies the project uses, most of which have the scope of <code>provided</code> since we anticipate the server providing the dependencies. </p>
<p/>
All of the archetypes also contain some code for producing an <code>EntityManager</code> in the application using a Stateless EJB implementing a Local interface, and a CDI qualifier to specifying injection points for the entity manager produced. </p>
<ul>
<li><b><code>DataRepository.java</code></b> &#8211; Qualifier for the <code>EntityManager</code> instance.</li>
<li><b><code>DataRepositoryProducer.java</code></b> &#8211; Stateless EJB that produces the <code>EntityManager</code></li>
<li><b><code>DataRepositoryProducerLocal.java</code></b> &#8211; Local interface for the stateless EJB</li>
</ul>
<p>Technically, the Local interface shouldn&#8217;t be needed under EJB 3.1 which is part of Java EE 6, however Weld, the reference implementation of CDI has problems with EJBs without a local interface in that it cannot locate them. To see how to use the produced <code>EntityManager</code>, see the next part which covers the minimal archetype that has a small JPA data model.</p>
<p>This about wraps it up for configuration, there is very little added to the core project that you probably won&#8217;t need for a JSF/CDI/JPA application making the basic archetype a good choice for a new project where you don&#8217;t need the smoke tests to see if everything is setup and working.</p>
<p>Next time we&#8217;ll look at the minimal archetype in detail which contains somewhat more code and functionality to test that JSF/CDI/JPA is working as planned.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/knappsack-archetypes-part-1/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>FlutterCode.com released</title>
		<link>http://www.andygibson.net/blog/news/fluttercode-com-released/</link>
		<comments>http://www.andygibson.net/blog/news/fluttercode-com-released/#comments</comments>
		<pubDate>Tue, 29 Jun 2010 02:48:18 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[News]]></category>
		<category><![CDATA[Blog]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[Geek]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[Personal]]></category>
		<category><![CDATA[Podcast]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=919</guid>
		<description><![CDATA[I&#8217;ve been fairly quiet over the last couple of months as I&#8217;ve been working on a few items, working on a new site and working on getting two new Open Source projects final and out the door. I&#8217;ve renamed Spigot to DataValve, and moved it to the new site FlutterCode.com which will also host my [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been fairly quiet over the last couple of months as I&#8217;ve been working on a few items, working on a <a href="http://www.fluttercode.com">new site</a> and working on getting two new Open Source projects final and out the door. </p>
<p>I&#8217;ve renamed Spigot to <a href="http://www.fluttercode.com/projects/datavalve">DataValve</a>, and moved it to the new site FlutterCode.com which will also host my other project called <a href="http://www.fluttercode.com/projects/knappsack">Knappsack</a> which is a set of Maven archetypes for Java EE 6.</p>
<p>The new site will be home to most of my tutorials, articles and other writings, as well as possibly some screencasts and even podcasts. It will in essence be a pure java development site. This blog will go a bit quieter and contain less development stuff, although most opinion will get put out here instead of over there. I&#8217;ll also be copying some of my tutorials over there from this blog.</p>
<p>I&#8217;m aiming to create a fairly cohesive tutorial site, aided in part by the Maven Archetypes which will give me a firm base onto which I can build tutorials without having to start from scratch, but one archetype is a sandbox Java EE 6 app with project configuration, a demo model and some test data. The sandbox app will let developers create a new skeleton java EE 6 application they can play with. Building on that, there is a sandbox-demo application which as an archetype that creates a full working demo CRUD application using Java EE 6 so developers can see how all the different pieces of Java EE 6 go together. It includes features such as conversations, JPA CRUD, page parameters, CDI injection and events.</p>
<p>Again, I have to say it, but  <a href="http://www.andygibson.net/blog/index.php/2009/07/12/open-source-is-hard/">Open Source is Hard</a>. In the past couple of months, I have been working on a whole new site, getting 2 projects ready to roll with documentation and site content to boot as well as working a job, and having some kind of life.</p>
<p>Now it&#8217;s out, I can start to focus a little more on getting some more Java EE 6 tutorials and articles out.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/news/fluttercode-com-released/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>A Guide to Spigot For Seam Developers</title>
		<link>http://www.andygibson.net/blog/article/spigot-for-seam-developers/</link>
		<comments>http://www.andygibson.net/blog/article/spigot-for-seam-developers/#comments</comments>
		<pubDate>Tue, 06 Apr 2010 17:00:57 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[Project Kenai]]></category>
		<category><![CDATA[Seam]]></category>
		<category><![CDATA[Spigot]]></category>
		<category><![CDATA[Weld]]></category>
		<category><![CDATA[Wicket]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=874</guid>
		<description><![CDATA[Note : Spigot has been renamed to DataValve. (Edit : I renamed this post so it doesn&#8217;t seem like Spigot is just for Seam, Spigot can be used with different frameworks or without any at all. However, I wrote this post since Spigot is so familiar to the Seam EntityQuery that it should be easy [...]]]></description>
			<content:encoded><![CDATA[<p><b>Note</b> : Spigot has been renamed to <a href="http://www.fluttercode.com/projects/datavalve/">DataValve</a>.</p>
<p>(<small><b>Edit </b>: I renamed this post so it doesn&#8217;t seem like Spigot is just for Seam, Spigot can be used with different frameworks or without any at all. However, I wrote this post since Spigot is so familiar to the Seam EntityQuery that it should be easy for Seam users to get the idea</small>)</p>
<p>Seam developers should become familiar with <a href="http://kenai.com/projects/spigot/">Spigot</a> concepts fairly quickly since they are very similar to those found in the Seam <code>EntityQuery</code> which was one of the main inspirations for the framework. If you imagine taking the entity query class and splitting it in two, one part to keep hold of state and the other to actually fetch the data. The stateful part is the <code>Paginator</code> that keeps track of what the current ordering of the data is, what is the current page and how big the pages are. The stateless part takes the Ejbql and the pagination information and returns a subset of the data. Now imaging that the data provider has the JPA pieces taken out and replaced with an abstract <code>fetchResults</code> method. This method is implemented in subclasses for specific data providers for text files, sql queries, jpa queries, native jpa queries, xml files, comma delimited or just an in memory dataset.<br />
<span id="more-874"></span><br />
I also abstracted the concepts of parameterization and parameter resolution so you can have parameters on data providers that are no t query based and your parameters can be resolved using different mechanisms such as EL, reflection, a map, or using custom parameter resolution.<br />
So really, for Seam developers, its like a Seam <code>EntityQuery</code> that doesn&#8217;t just use JPA, but uses any kind of data source you want but still returns just a list of objects.</p>
<p>Spigot works nicely with CDI and there is even a demo of it in the distribution that uses JSF and was generated using the Weld maven archetypes. Also, there is a Seam Jpa Dataset Adapter that you can use as a direct replacement for the <code>EntityQuery</code> which will adapt the entity query calls to the underlying data provider calls so you can have a seam-less transition if you want to switch over. This is still a little in-progress, but works. The one area that isn&#8217;t implemented is the sorting, which may not be possible, but I still need to add in the methods to the adapter even if they don&#8217;t do anything. The other issue is of course the configuration of the query from components.xml using the Seam Framework tags. However, you can define the query using regular component xml tags to define the Ejbql, restrictions and page sizes.</p>
<p>Two things to note if you start using Spigot in place of the entity query. All rows are returned by default, and you need to specify both a select statement and a count statement. I separated those two out so you can put join fetch phrases in the select statement without it breaking the count statement. There is an <code>init</code> method that you can use to set both of these statements for a class type.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/spigot-for-seam-developers/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Spigot 0.9.CR1 released</title>
		<link>http://www.andygibson.net/blog/news/spigot-0-9-cr1-released/</link>
		<comments>http://www.andygibson.net/blog/news/spigot-0-9-cr1-released/#comments</comments>
		<pubDate>Tue, 06 Apr 2010 13:07:55 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[News]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[Personal]]></category>
		<category><![CDATA[Seam]]></category>
		<category><![CDATA[Spigot]]></category>
		<category><![CDATA[Weld]]></category>
		<category><![CDATA[Wicket]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=861</guid>
		<description><![CDATA[Note : Spigot has been renamed to DataValve and is hosted over on FlutterCode.com. It&#8217;s been a while since I&#8217;ve posted anything new as I&#8217;ve been busy with a new Open Source software project called Spigot. It&#8217;s a java library that sits between your application code and your data sources (Hibernate, JPA, JDBC or any [...]]]></description>
			<content:encoded><![CDATA[<p><b>Note</b> : Spigot has been renamed to <a href="http://www.fluttercode.com/projects/datavalve/">DataValve</a> and is hosted over on <a href="http://www.fluttercode.com">FlutterCode.com</a>.</p>
<p>It&#8217;s been a while since I&#8217;ve posted anything new as I&#8217;ve been busy with a new Open Source software project called Spigot. It&#8217;s a java library that sits between your application code and your data sources (Hibernate, JPA, JDBC or any arbitrary source of data) and helps with things like pagination and sorting using a common interface so you can switch out data providers and use alternatives. </p>
<p>For query language data providers, Spigot also facilitates excluding restrictions from WHERE clauses when parameters are resolved to null. Parameters are handled using parameter resolvers so there is more than one way to parameterize the query including EL expressions, reflection or a value map on the data provider.</p>
<p>Spigot also provides a few other add-ins like converting any dataset into an in-memory dataset that can itself be paginated and sorted and shared across an application (such as commonly used data in a web application). The <code>IndexedDataProviderCache</code> can give you random access into a dataset with caching and look ahead loading. This lets you hook a dataset with thousands of rows up to a Swing JTable with an instant response and a very small memory footprint since it doesn&#8217;t need to load all the objects at once as the provider will load the records as needed and cache the results. This is demonstrated in the Swing Demo in the download. There are also demos for Wicket and CDI with JSF.</p>
<p>You can ready about why I created Spigot in the <a href="http://spigot.kenai.com/docs/html/pr01.html">documentation</a></p>
<p>Spigot is currently hosted on <a href="http://www.projectkenai.com/projects/spigot/">Project Kenai</a>, where you can download the release, view documentation online or read about <a href="http://kenai.com/projects/spigot/pages/10WaysSpigotHelpsDevelopers">10 ways Spigot helps developers</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/news/spigot-0-9-cr1-released/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

