<?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/"
	xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd"
>

<channel>
	<title>Smooks Data Integration &#187; Scribe</title>
	<atom:link href="http://blog.smooks.org/category/scribe/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.smooks.org</link>
	<description>The official blog</description>
	<lastBuildDate>Mon, 28 Jun 2010 13:10:25 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<!-- podcast_generator="Blubrry PowerPress/1.0.7" mode="simple" entry="normal" -->
	<itunes:summary>The official blog</itunes:summary>
	<itunes:author>Smooks Data Integration</itunes:author>
	<itunes:explicit>no</itunes:explicit>
	<itunes:image href="http://blog.smooks.org/wp-content/plugins/powerpress/itunes_default.jpg" />
	<itunes:owner>
		<itunes:name>Smooks Data Integration</itunes:name>
		<itunes:email>tom.fennelly@gmail.com</itunes:email>
	</itunes:owner>
	<managingEditor>tom.fennelly@gmail.com (Smooks Data Integration)</managingEditor>
	<itunes:subtitle>The official blog</itunes:subtitle>
	<image>
		<title>Smooks Data Integration &#187; Scribe</title>
		<url>http://blog.smooks.org/wp-content/plugins/powerpress/rss_default.jpg</url>
		<link>http://blog.smooks.org/category/scribe/</link>
	</image>
		<item>
		<title>Smooks Persistence part 2: How to use Hibernate/JPA</title>
		<link>http://blog.smooks.org/2009/03/25/smooks-persistence-part-2-how-to-use-hibernatejpa/</link>
		<comments>http://blog.smooks.org/2009/03/25/smooks-persistence-part-2-how-to-use-hibernatejpa/#comments</comments>
		<pubDate>Wed, 25 Mar 2009 11:20:09 +0000</pubDate>
		<dc:creator>Maurice</dc:creator>
				<category><![CDATA[Java Binding]]></category>
		<category><![CDATA[Persistence]]></category>
		<category><![CDATA[Scribe]]></category>
		<category><![CDATA[Smooks]]></category>

		<guid isPermaLink="false">http://blog.smooks.org/?p=113</guid>
		<description><![CDATA[<p>With the new Smooks Persistence cartridge in Smooks 1.2 you can directly use several entity persistence frameworks from within Smooks. In this post I will show you how this works with Hibernate and any other JPA compatible framework.</p>
<p><span id="more-113"></span></p>
<p>This post is part of a multi post article. You can find the previous post here: <a title="Smooks Persistence part 1: The Introduction" href="/2009/02/26/smooks-persistence-part-1-the-introduction/">Smooks Persistence part 1: The Introduction</a></p>
<p>In this post we will look at an example of how to persist Hibernate Entities. This example is based on the example of the previous post.</p>
<p>First, lets take a look at the data we are going to process. In this example we are processing XML data.  It should be noted however, that the input data could also be <strong>CSV</strong>, <strong>JSON</strong>, <strong>EDI</strong>, <strong>Java</strong> or any other structured/hierarchical data format.  The same principals apply, no matter what the data format is!</p>
<pre class="brush: xml;">&lt;order&gt;
    &lt;ordernumber&gt;1&lt;/ordernumber&gt;
    &lt;customer&gt;123456&lt;/customer&gt;
    &lt;order-items&gt;
        &lt;order-item&gt;
            &lt;product&gt;11&lt;/product&gt;
            &lt;quantity&gt;2&lt;/quantity&gt;
        &lt;/order-item&gt;
        &lt;order-item&gt;
            &lt;product&gt;22&lt;/product&gt;
            &lt;quantity&gt;7&lt;/quantity&gt;
        &lt;/order-item&gt;
    &lt;/order-items&gt;
&lt;/order&gt;</pre>
<p>These are the Hibernate entities we are going to use:</p>
<pre class="brush: java;">@Entity
@Table(name="orders")
public class Order {

	@Id
	private Integer ordernumber;

	@Basic
	private String customerId;

	@OneToMany(mappedBy = "order", cascade = CascadeType.ALL)
	private List orderItems = new ArrayList();

	public void addOrderLine(OrderLine orderLine) {
		orderItems.add(orderLine);
	}

       // Getters and Setters....
}</pre>
<pre class="brush: java;">@Entity
@Table(name="orderlines")
public class OrderLine {

	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	private Integer id;

	@ManyToOne
	@JoinColumn(name="orderid")
	private Order order;

	@Basic
	private Integer quantity;

	@ManyToOne
	@JoinColumn(name="productid")
	private Product product;

       // Getters and Setters....
}</pre>
<pre class="brush: java;">@Entity
@Table(name = "products")
@NamedQuery(name="product.byId", query="from Product p where p.id = :id")
public class Product {

	@Id
	private Integer id;

	@Basic
	private String name;

       // Getters and Setters....
}</pre>
<p>The Smooks configuration looks like this:</p>
<pre class="brush: xml;">
&lt;!--
	In this example, we don't need to reference the Hibernate Session
	anywhere in the configuration. Later on, in the Smooks execution
	code (following snippet), you will see that we have set the
	Session as the default Session. This means that you don't need
	to reference it by name.  In the configuration of the previous
	post, we needed to reference every DAO by its name.
--&gt;
&lt;smooks-resource-list xmlns="http://www.milyn.org/xsd/smooks-1.1.xsd"
	xmlns:jb="http://www.milyn.org/xsd/smooks/javabean-1.1.xsd" xmlns:dao="http://www.milyn.org/xsd/smooks/persistence-1.2.xsd"&gt;

	&lt;!--
		This is a normal Javabean binding. It creates the order bean and binds
		data into it.
	--&gt;
	&lt;jb:bindings beanId="order" class="example.entity.Order"
		createOnElement="order"&gt;

		&lt;jb:value property="ordernumber" data="ordernumber" /&gt;
		&lt;jb:value property="customerId" data="customer" /&gt;
		&lt;jb:wiring setterMethod="addOrderLine" beanIdRef="orderLine" /&gt;
	&lt;/jb:bindings&gt;

	&lt;!--
		This is a normal Javabean binding. Notice that we have a wiring on
		'product'. The Product entity will not be created, but looked up by a
		locator.
	--&gt;
	&lt;jb:bindings beanId="orderLine" class="example.entity.OrderLine"
		createOnElement="order-item"&gt;

		&lt;jb:value property="quantity" data="quantity" decoder="Integer" /&gt;
		&lt;jb:wiring property="order" beanIdRef="order" /&gt;
		&lt;jb:wiring property="product" beanIdRef="product" /&gt;
	&lt;/jb:bindings&gt;

	&lt;!--
		This locator calls (via Scribe) the SessionDaoAdapter#lookupByQuery()
		method. The result will be added to the bean repository under the bean
		id 'product'. An exception is thrown when no result is found.
	--&gt;
	&lt;dao:locator beanId="product" lookupOnElement="order-item"
		onNoResult="EXCEPTION" uniqueResult="true"&gt;

		&lt;dao:query&gt;from Product p where p.id = :id&lt;/dao:query&gt;
		&lt;dao:params&gt;
			&lt;dao:value name="id" data="product" decoder="Integer" /&gt;
		&lt;/dao:params&gt;
	&lt;/dao:locator&gt;

	&lt;!--
		The inserter calls (via Scribe) the SessionDaoAdapter#insert() method
		at the visitAfter of the Order element. The SessioDaoAdapter#insert()
		uses the Hibernate Session#save() method to persist the entity to the
		database.
	--&gt;
	&lt;dao:inserter beanId="order" insertOnElement="order" /&gt;

&lt;/smooks-resource-list&gt;</pre>
<p>If we want to use the named query &#8216;productById&#8217; instead of the query string then the DAO locator configuration will look like this:</p>
<pre class="brush: xml;">	&lt;!--
		The lookup parameter is the query name
	--&gt;
    &lt;dao:locator beanId="product" lookupOnElement="order-item" lookup="product.byId"
    				onNoResult="EXCEPTION" uniqueResult="true"&gt;
    	&lt;dao:params&gt;
    		&lt;dao:value name="id" data="product" decoder="Integer"/&gt;
    	&lt;/dao:params&gt;
    &lt;/dao:locator&gt;</pre>
<p>The following code executes Smooks. Note that we use a SessionRegister object so that we can access the Hibernate Session from within Smooks.</p>
<pre class="brush: java;">
        // Note: In a real world application you should cache the Smooks instance
        // else you will have enormous performance penalties.
        Smooks smooks = new Smooks("smooks-config.xml");

        ExecutionContext executionContext = smooks.createExecutionContext();

        // The SessionRegister provides the bridge between Hibernate and the
        // Persistence Cartridge. We provide it with the Hibernate session.
        // The Hibernate Session is set as default Session.
        DaoRegister register = new SessionRegister(session);

        // This sets the DAO Register in the executionContext for Smooks
        // to access it.
        PersistenceUtil.setDAORegister(executionContext, register);

        Transaction transaction = session.beginTransaction();

        Source source = new StreamSource(new File("order.xml"));        

        smooks.filter(source, null, executionContext);

        transaction.commit();</pre>
<p>If you want to take a JPA version of this example for a spin, simply check out the examples from subversion (http://svn.codehaus.org/milyn/trunk/smooks-examples/) and you’ll find it in the “dao-router” folder.  It also shows you how to use custom DOA&#8217;s with the Persistence Cartridge.</p>
<p>With Scribe and the Persistence Cartridge it is very easy to use Hibernate, JPA and most other persistence frameworks within Smooks. Later on in this series I will explain how too write your own DAO Adapters, so that you can add support for other persistence frameworks.</p>
<p>In the next post of the series I will explain how you can use Ibatis with the Persistence Cartridge.</p>
<div style="display:block"><small><em>posted in <a href="http://blog.smooks.org/category/java-binding/">Java Binding</a> by Maurice <a href="http://blog.smooks.org/2009/03/25/smooks-persistence-part-2-how-to-use-hibernatejpa/#comments">Leave A Comment</a></em></small></div>]]></description>
			<content:encoded><![CDATA[<p>With the new Smooks Persistence cartridge in Smooks 1.2 you can directly use several entity persistence frameworks from within Smooks. In this post I will show you how this works with Hibernate and any other JPA compatible framework.</p>
<p><span id="more-113"></span></p>
<p>This post is part of a multi post article. You can find the previous post here: <a title="Smooks Persistence part 1: The Introduction" href="/2009/02/26/smooks-persistence-part-1-the-introduction/">Smooks Persistence part 1: The Introduction</a></p>
<p>In this post we will look at an example of how to persist Hibernate Entities. This example is based on the example of the previous post.</p>
<p>First, lets take a look at the data we are going to process. In this example we are processing XML data.  It should be noted however, that the input data could also be <strong>CSV</strong>, <strong>JSON</strong>, <strong>EDI</strong>, <strong>Java</strong> or any other structured/hierarchical data format.  The same principals apply, no matter what the data format is!</p>
<pre class="brush: xml;">&lt;order&gt;
    &lt;ordernumber&gt;1&lt;/ordernumber&gt;
    &lt;customer&gt;123456&lt;/customer&gt;
    &lt;order-items&gt;
        &lt;order-item&gt;
            &lt;product&gt;11&lt;/product&gt;
            &lt;quantity&gt;2&lt;/quantity&gt;
        &lt;/order-item&gt;
        &lt;order-item&gt;
            &lt;product&gt;22&lt;/product&gt;
            &lt;quantity&gt;7&lt;/quantity&gt;
        &lt;/order-item&gt;
    &lt;/order-items&gt;
&lt;/order&gt;</pre>
<p>These are the Hibernate entities we are going to use:</p>
<pre class="brush: java;">@Entity
@Table(name="orders")
public class Order {

	@Id
	private Integer ordernumber;

	@Basic
	private String customerId;

	@OneToMany(mappedBy = "order", cascade = CascadeType.ALL)
	private List orderItems = new ArrayList();

	public void addOrderLine(OrderLine orderLine) {
		orderItems.add(orderLine);
	}

       // Getters and Setters....
}</pre>
<pre class="brush: java;">@Entity
@Table(name="orderlines")
public class OrderLine {

	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	private Integer id;

	@ManyToOne
	@JoinColumn(name="orderid")
	private Order order;

	@Basic
	private Integer quantity;

	@ManyToOne
	@JoinColumn(name="productid")
	private Product product;

       // Getters and Setters....
}</pre>
<pre class="brush: java;">@Entity
@Table(name = "products")
@NamedQuery(name="product.byId", query="from Product p where p.id = :id")
public class Product {

	@Id
	private Integer id;

	@Basic
	private String name;

       // Getters and Setters....
}</pre>
<p>The Smooks configuration looks like this:</p>
<pre class="brush: xml;">
&lt;!--
	In this example, we don't need to reference the Hibernate Session
	anywhere in the configuration. Later on, in the Smooks execution
	code (following snippet), you will see that we have set the
	Session as the default Session. This means that you don't need
	to reference it by name.  In the configuration of the previous
	post, we needed to reference every DAO by its name.
--&gt;
&lt;smooks-resource-list xmlns="http://www.milyn.org/xsd/smooks-1.1.xsd"
	xmlns:jb="http://www.milyn.org/xsd/smooks/javabean-1.1.xsd" xmlns:dao="http://www.milyn.org/xsd/smooks/persistence-1.2.xsd"&gt;

	&lt;!--
		This is a normal Javabean binding. It creates the order bean and binds
		data into it.
	--&gt;
	&lt;jb:bindings beanId="order" class="example.entity.Order"
		createOnElement="order"&gt;

		&lt;jb:value property="ordernumber" data="ordernumber" /&gt;
		&lt;jb:value property="customerId" data="customer" /&gt;
		&lt;jb:wiring setterMethod="addOrderLine" beanIdRef="orderLine" /&gt;
	&lt;/jb:bindings&gt;

	&lt;!--
		This is a normal Javabean binding. Notice that we have a wiring on
		'product'. The Product entity will not be created, but looked up by a
		locator.
	--&gt;
	&lt;jb:bindings beanId="orderLine" class="example.entity.OrderLine"
		createOnElement="order-item"&gt;

		&lt;jb:value property="quantity" data="quantity" decoder="Integer" /&gt;
		&lt;jb:wiring property="order" beanIdRef="order" /&gt;
		&lt;jb:wiring property="product" beanIdRef="product" /&gt;
	&lt;/jb:bindings&gt;

	&lt;!--
		This locator calls (via Scribe) the SessionDaoAdapter#lookupByQuery()
		method. The result will be added to the bean repository under the bean
		id 'product'. An exception is thrown when no result is found.
	--&gt;
	&lt;dao:locator beanId="product" lookupOnElement="order-item"
		onNoResult="EXCEPTION" uniqueResult="true"&gt;

		&lt;dao:query&gt;from Product p where p.id = :id&lt;/dao:query&gt;
		&lt;dao:params&gt;
			&lt;dao:value name="id" data="product" decoder="Integer" /&gt;
		&lt;/dao:params&gt;
	&lt;/dao:locator&gt;

	&lt;!--
		The inserter calls (via Scribe) the SessionDaoAdapter#insert() method
		at the visitAfter of the Order element. The SessioDaoAdapter#insert()
		uses the Hibernate Session#save() method to persist the entity to the
		database.
	--&gt;
	&lt;dao:inserter beanId="order" insertOnElement="order" /&gt;

&lt;/smooks-resource-list&gt;</pre>
<p>If we want to use the named query &#8216;productById&#8217; instead of the query string then the DAO locator configuration will look like this:</p>
<pre class="brush: xml;">	&lt;!--
		The lookup parameter is the query name
	--&gt;
    &lt;dao:locator beanId="product" lookupOnElement="order-item" lookup="product.byId"
    				onNoResult="EXCEPTION" uniqueResult="true"&gt;
    	&lt;dao:params&gt;
    		&lt;dao:value name="id" data="product" decoder="Integer"/&gt;
    	&lt;/dao:params&gt;
    &lt;/dao:locator&gt;</pre>
<p>The following code executes Smooks. Note that we use a SessionRegister object so that we can access the Hibernate Session from within Smooks.</p>
<pre class="brush: java;">
        // Note: In a real world application you should cache the Smooks instance
        // else you will have enormous performance penalties.
        Smooks smooks = new Smooks("smooks-config.xml");

        ExecutionContext executionContext = smooks.createExecutionContext();

        // The SessionRegister provides the bridge between Hibernate and the
        // Persistence Cartridge. We provide it with the Hibernate session.
        // The Hibernate Session is set as default Session.
        DaoRegister register = new SessionRegister(session);

        // This sets the DAO Register in the executionContext for Smooks
        // to access it.
        PersistenceUtil.setDAORegister(executionContext, register);

        Transaction transaction = session.beginTransaction();

        Source source = new StreamSource(new File("order.xml"));        

        smooks.filter(source, null, executionContext);

        transaction.commit();</pre>
<p>If you want to take a JPA version of this example for a spin, simply check out the examples from subversion (http://svn.codehaus.org/milyn/trunk/smooks-examples/) and you’ll find it in the “dao-router” folder.  It also shows you how to use custom DOA&#8217;s with the Persistence Cartridge.</p>
<p>With Scribe and the Persistence Cartridge it is very easy to use Hibernate, JPA and most other persistence frameworks within Smooks. Later on in this series I will explain how too write your own DAO Adapters, so that you can add support for other persistence frameworks.</p>
<p>In the next post of the series I will explain how you can use Ibatis with the Persistence Cartridge.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smooks.org/2009/03/25/smooks-persistence-part-2-how-to-use-hibernatejpa/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Smooks Persistence part 1: The Introduction</title>
		<link>http://blog.smooks.org/2009/02/26/smooks-persistence-part-1-the-introduction/</link>
		<comments>http://blog.smooks.org/2009/02/26/smooks-persistence-part-1-the-introduction/#comments</comments>
		<pubDate>Thu, 26 Feb 2009 11:31:44 +0000</pubDate>
		<dc:creator>Maurice</dc:creator>
				<category><![CDATA[Java Binding]]></category>
		<category><![CDATA[Persistence]]></category>
		<category><![CDATA[Scribe]]></category>
		<category><![CDATA[Smooks]]></category>

		<guid isPermaLink="false">http://blog.smooks.org/?p=61</guid>
		<description><![CDATA[<p>One of the major new features in Smooks v1.2 will be the new Persistence Cartridge. This cartridge enables the use of several entity persistence frameworks from within Smooks, currently targeting Hibernate, Ibatis and any JPA compatible framework. It also allows you to use your own Data Access Objects (DAOs).</p>
<p>This cartridge is great for those cases where you already have your data access layer and want to use its power from within Smooks. It also allows you to reuse these persistence resources on any format of data, not just XML e.g. EDI, CSV, JSON etc.</p>
<p>This is the first post of a series of posts about the persistence cartridge. This post is an introduction of the cartridge.  I will give an overview of what the cartridge can do and also show an example where I use custom DAO&#8217;s to persist the data of an XML document.  In the next posts in this series, I will show examples of how Hibernate, JPA and Ibatis entities can be used.</p>
<p><span id="more-61"></span></p>
<p>The Persistence cartridge is build around a data access layer abstraction library called &#8220;Scribe&#8221;.  Scribe is a new Milyn subproject, born out of the needs of the Persistence cartridge. It enables the Persistence cartridge to use your DAOs without it actually needing to know the details of your DAOs. In fact, they don&#8217;t need to be DAOs at all.  You can also use any entity persistence framework without the Persistence cartridge seeing the difference.  Scribe supports abstracting the default actions you can expect from any DAO or persistence library like inserting, updating, deleting and querying for entities.</p>
<p>For Scribe to understand how to use your DAOs, it needs a mapping. Scribe offers two methods for doing this:</p>
<ul>
<li><strong>Java Annotations</strong><br />
Scribe has a set of Java Annotations like @Insert, @Update, @Delete and @Locate. These annotations enable you to map your DAOs to the DAO actions.</li>
<li><strong>Java Interfaces</strong><br />
Scribe defines a set of Java interfaces like DAO, Locator and Queryable.  You build your DAOs By combining and implementing these interfaces. These interfaces are primarily meant to be used for implementing adapters for persistence frameworks.</li>
</ul>
<p>The Persistence Cartridge defines a set of Smooks Visitor components that use the DAO actions defined by Scribe.  For example, the <strong>Inserter </strong>visitor can insert your entities by calling the method defined by the DAO action mapping.  We see an example of this later.</p>
<p>The cartridge has the following Smooks Visitor components:</p>
<ul>
<li><strong>Inserter<br />
</strong>Inserts/Persists entities</li>
<li><strong>Updater<br />
</strong>Updates/Merges entities</li>
<li><strong>Deleter</strong><br />
Deletes entities</li>
<li><strong>Locator</strong><br />
Locates entities with a query or with your own lookup method.</li>
</ul>
<p>Now that you have an idea of what the Persistence cartridge can do, let&#8217;s take a look at a DAO based example.  We will see Hibernate, IBatis and JPA examples in the followup posts in this series.</p>
<p>The example will read an XML file containing order information (note that this works just the same for EDI, CSV etc).  Using the javabean cartridge, it will bind the XML data into a set of entity beans.  Using the id of the products within the order items (the &lt;product&gt; element) it will locate the product entities and bind them to the order entity bean.  Finally, the order bean will be persisted.</p>
<p>The order XML message looks like this:</p>
<pre class="brush: xml;">&lt;order&gt;
    &lt;ordernumber&gt;1&lt;/ordernumber&gt;
    &lt;customer&gt;123456&lt;/customer&gt;
    &lt;order-items&gt;
        &lt;order-item&gt;
            &lt;product&gt;11&lt;/product&gt;
            &lt;quantity&gt;2&lt;/quantity&gt;
        &lt;/order-item&gt;
        &lt;order-item&gt;
            &lt;product&gt;22&lt;/product&gt;
            &lt;quantity&gt;7&lt;/quantity&gt;
        &lt;/order-item&gt;
    &lt;/order-items&gt;
&lt;/order&gt;</pre>
<p>The following custom DAO will be used to persist the Order entity:</p>
<pre class="brush: java;">@Dao
public class OrderDao {

   private final EntityManager em;

   public OrderDao(EntityManager em) {
     this.em = em;
   }

   @Insert
   public void insertOrder(Order order) {
     em.persist(order);
   }
}</pre>
<p>When looking at this class you should notice the <strong>@Dao</strong> and <strong>@Insert</strong> annotations. The <strong>@Dao</strong> annotation declares that the OrderDao is a DAO object. The <strong>@Insert</strong> annotation declares that the insertOrder method should be used to insert Order entities.</p>
<p>The following custom DAO will be used to lookup the Product entities:</p>
<pre class="brush: java;">@Dao
public class ProductDao {

   private final EntityManager em;

   public ProductDao(EntityManager em) {
      this.em = em;
   }

   @Lookup(name="id")
   public Product findProductById(@Param("id") int id) {
      return em.find(Product.class, id);
   }
}</pre>
<p>When looking at this class, you should notice the <strong>@Lookup</strong> and <strong>@Param</strong> annotation. The <strong>@Lookup</strong> annotation declares that the <strong>ProductDao#findByProductId</strong> method is used to lookup <strong>Product</strong> entities. The<strong> name</strong> parameter in the <strong>@Lookup</strong> annotation sets the lookup name reference for that method. When the name isn&#8217;t declared, the method name will be used. The optional <strong>@Param</strong> annotation let&#8217;s you name the parameters. This creates a better  abstraction between Smooks and the DAO. If you don&#8217;t declare the <strong>@Param</strong> annotation the parameters are resolved by there position.</p>
<p>The Smooks configuration look likes this:</p>
<pre class="brush: xml;">&lt;!--
    In this configuration you will see that we reference to the
    DAO's via the names 'order'  and 'product'. The persistence cartridge uses
    a DAO Register to map the DAO's to there names.
    Later on, in the java code that executes Smooks, you will see how that is done.
--&gt;
&lt;smooks-resource-list
   xmlns="http://www.milyn.org/xsd/smooks-1.1.xsd"
   xmlns:jb="http://www.milyn.org/xsd/smooks/javabean-1.1.xsd"
   xmlns:dao="http://www.milyn.org/xsd/smooks/persistence-1.2.xsd"&gt;

   &lt;!--
    This is a normal Javabean binding. It creates the order bean
    and binds data into it.
   --&gt;
   &lt;jb:bindings beanId="order" class="example.entity.Order"
                 createOnElement="order"&gt;
      &lt;jb:value property="ordernumber" data="ordernumber"/&gt;
      &lt;jb:value property="customerId" data="customer"/&gt;
      &lt;jb:wiring setterMethod="addOrderLine" beanIdRef="orderLine" /&gt;
   &lt;/jb:bindings&gt;

   &lt;!--
    This is a normal Javabean binding. Notice that we have a wiring on
    'product'. The Product entity will not be created, but looked up
    by a locator.
   --&gt;
   &lt;jb:bindings beanId="orderLine" class="example.entity.OrderLine"
                 createOnElement="order-item"&gt;
      &lt;jb:value property="quantity" data="quantity"/&gt;
      &lt;jb:wiring property="order" beanIdRef="order"/&gt;
      &lt;jb:wiring property="product" beanIdRef="product"/&gt;
   &lt;/jb:bindings&gt;

   &lt;!--
    This locator calls (via Scribe) the ProductDao#findById() method.
    The result will be added to the bean repository under
    the bean id 'product'.
    An exception is thrown when no result is found.
   --&gt;
   &lt;dao:locator beanId="product" dao="product" lookup="id"
           lookupOnElement="order-item" onNoResult="EXCEPTION"&gt;
      &lt;dao:params&gt;
         &lt;dao:value name="id" data="product" decoder="Integer"/&gt;
      &lt;/dao:params&gt;
   &lt;/dao:locator&gt;

   &lt;!--
    The inserter calls the OrderDao#insertOrder() method at
    end of Order message.
   --&gt;
   &lt;dao:inserter beanId="order" dao="order" insertOnElement="order" /&gt;

&lt;/smooks-resource-list&gt;</pre>
<p>The following code executes Smooks:</p>
<pre class="brush: java;">Smooks smooks = new Smooks("./smooks-configs/smooks-dao-config.xml");
ExecutionContext executionContext = smooks.createExecutionContext();

// The register is used to map the DAO's to a DAO name. The DAO name isbe used in
// the configuration.
// The MapRegister is a simple Map like implementation of the DaoRegister.
DaoRegister&lt;object&gt; register =
	MapRegister.builder()
		.put("product", new ProductDao(em))
		.put("order", new OrderDao(em))
		.build();

PersistenceUtil.setDAORegister(executionContext, mapRegister);

// Transaction management from within Smooks isn't supported yet,
// so we need to do it outside the filter execution
EntityTransaction tx = em.getTransaction();
tx.begin();

smooks.filter(new StreamSource(messageIn), null, executionContext);

tx.commit();</pre>
<p>If you want to take this example for a spin, simply check out the examples from subversion (http://svn.codehaus.org/milyn/trunk/smooks-examples/) and you&#8217;ll find it in the &#8220;dao-router&#8221; folder.  It also shows you how to use JPA directly, without any DAOs in between.</p>
<p>The cartridge is almost ready for it&#8217;s first release.  There is one thing that I am still not completely sure about and it would be great if people could provide some feedback.  I am not completely happy about the action names: <strong>insert</strong>, <strong>update </strong>and <strong>delete</strong>.  In the world of persistence frameworks, different sets of names are used for these actions.  JPA, for instance, uses <strong>persist</strong>, <strong>merge </strong>and <strong>remove</strong>.  Hibernate (outside of JPA) uses <strong>save, update</strong> and <strong>delete </strong>and Ibatis uses <strong>insert</strong>, <strong>update</strong> and <strong>delete</strong>. Which names would you choose and why?</p>
<p>In the next post of the series I will explain how to use Hibernate directly.</p>
<div style="display:block"><small><em>posted in <a href="http://blog.smooks.org/category/java-binding/">Java Binding</a> by Maurice <a href="http://blog.smooks.org/2009/02/26/smooks-persistence-part-1-the-introduction/#comments">Leave A Comment</a></em></small></div>]]></description>
			<content:encoded><![CDATA[<p>One of the major new features in Smooks v1.2 will be the new Persistence Cartridge. This cartridge enables the use of several entity persistence frameworks from within Smooks, currently targeting Hibernate, Ibatis and any JPA compatible framework. It also allows you to use your own Data Access Objects (DAOs).</p>
<p>This cartridge is great for those cases where you already have your data access layer and want to use its power from within Smooks. It also allows you to reuse these persistence resources on any format of data, not just XML e.g. EDI, CSV, JSON etc.</p>
<p>This is the first post of a series of posts about the persistence cartridge. This post is an introduction of the cartridge.  I will give an overview of what the cartridge can do and also show an example where I use custom DAO&#8217;s to persist the data of an XML document.  In the next posts in this series, I will show examples of how Hibernate, JPA and Ibatis entities can be used.</p>
<p><span id="more-61"></span></p>
<p>The Persistence cartridge is build around a data access layer abstraction library called &#8220;Scribe&#8221;.  Scribe is a new Milyn subproject, born out of the needs of the Persistence cartridge. It enables the Persistence cartridge to use your DAOs without it actually needing to know the details of your DAOs. In fact, they don&#8217;t need to be DAOs at all.  You can also use any entity persistence framework without the Persistence cartridge seeing the difference.  Scribe supports abstracting the default actions you can expect from any DAO or persistence library like inserting, updating, deleting and querying for entities.</p>
<p>For Scribe to understand how to use your DAOs, it needs a mapping. Scribe offers two methods for doing this:</p>
<ul>
<li><strong>Java Annotations</strong><br />
Scribe has a set of Java Annotations like @Insert, @Update, @Delete and @Locate. These annotations enable you to map your DAOs to the DAO actions.</li>
<li><strong>Java Interfaces</strong><br />
Scribe defines a set of Java interfaces like DAO, Locator and Queryable.  You build your DAOs By combining and implementing these interfaces. These interfaces are primarily meant to be used for implementing adapters for persistence frameworks.</li>
</ul>
<p>The Persistence Cartridge defines a set of Smooks Visitor components that use the DAO actions defined by Scribe.  For example, the <strong>Inserter </strong>visitor can insert your entities by calling the method defined by the DAO action mapping.  We see an example of this later.</p>
<p>The cartridge has the following Smooks Visitor components:</p>
<ul>
<li><strong>Inserter<br />
</strong>Inserts/Persists entities</li>
<li><strong>Updater<br />
</strong>Updates/Merges entities</li>
<li><strong>Deleter</strong><br />
Deletes entities</li>
<li><strong>Locator</strong><br />
Locates entities with a query or with your own lookup method.</li>
</ul>
<p>Now that you have an idea of what the Persistence cartridge can do, let&#8217;s take a look at a DAO based example.  We will see Hibernate, IBatis and JPA examples in the followup posts in this series.</p>
<p>The example will read an XML file containing order information (note that this works just the same for EDI, CSV etc).  Using the javabean cartridge, it will bind the XML data into a set of entity beans.  Using the id of the products within the order items (the &lt;product&gt; element) it will locate the product entities and bind them to the order entity bean.  Finally, the order bean will be persisted.</p>
<p>The order XML message looks like this:</p>
<pre class="brush: xml;">&lt;order&gt;
    &lt;ordernumber&gt;1&lt;/ordernumber&gt;
    &lt;customer&gt;123456&lt;/customer&gt;
    &lt;order-items&gt;
        &lt;order-item&gt;
            &lt;product&gt;11&lt;/product&gt;
            &lt;quantity&gt;2&lt;/quantity&gt;
        &lt;/order-item&gt;
        &lt;order-item&gt;
            &lt;product&gt;22&lt;/product&gt;
            &lt;quantity&gt;7&lt;/quantity&gt;
        &lt;/order-item&gt;
    &lt;/order-items&gt;
&lt;/order&gt;</pre>
<p>The following custom DAO will be used to persist the Order entity:</p>
<pre class="brush: java;">@Dao
public class OrderDao {

   private final EntityManager em;

   public OrderDao(EntityManager em) {
     this.em = em;
   }

   @Insert
   public void insertOrder(Order order) {
     em.persist(order);
   }
}</pre>
<p>When looking at this class you should notice the <strong>@Dao</strong> and <strong>@Insert</strong> annotations. The <strong>@Dao</strong> annotation declares that the OrderDao is a DAO object. The <strong>@Insert</strong> annotation declares that the insertOrder method should be used to insert Order entities.</p>
<p>The following custom DAO will be used to lookup the Product entities:</p>
<pre class="brush: java;">@Dao
public class ProductDao {

   private final EntityManager em;

   public ProductDao(EntityManager em) {
      this.em = em;
   }

   @Lookup(name="id")
   public Product findProductById(@Param("id") int id) {
      return em.find(Product.class, id);
   }
}</pre>
<p>When looking at this class, you should notice the <strong>@Lookup</strong> and <strong>@Param</strong> annotation. The <strong>@Lookup</strong> annotation declares that the <strong>ProductDao#findByProductId</strong> method is used to lookup <strong>Product</strong> entities. The<strong> name</strong> parameter in the <strong>@Lookup</strong> annotation sets the lookup name reference for that method. When the name isn&#8217;t declared, the method name will be used. The optional <strong>@Param</strong> annotation let&#8217;s you name the parameters. This creates a better  abstraction between Smooks and the DAO. If you don&#8217;t declare the <strong>@Param</strong> annotation the parameters are resolved by there position.</p>
<p>The Smooks configuration look likes this:</p>
<pre class="brush: xml;">&lt;!--
    In this configuration you will see that we reference to the
    DAO's via the names 'order'  and 'product'. The persistence cartridge uses
    a DAO Register to map the DAO's to there names.
    Later on, in the java code that executes Smooks, you will see how that is done.
--&gt;
&lt;smooks-resource-list
   xmlns="http://www.milyn.org/xsd/smooks-1.1.xsd"
   xmlns:jb="http://www.milyn.org/xsd/smooks/javabean-1.1.xsd"
   xmlns:dao="http://www.milyn.org/xsd/smooks/persistence-1.2.xsd"&gt;

   &lt;!--
    This is a normal Javabean binding. It creates the order bean
    and binds data into it.
   --&gt;
   &lt;jb:bindings beanId="order" class="example.entity.Order"
                 createOnElement="order"&gt;
      &lt;jb:value property="ordernumber" data="ordernumber"/&gt;
      &lt;jb:value property="customerId" data="customer"/&gt;
      &lt;jb:wiring setterMethod="addOrderLine" beanIdRef="orderLine" /&gt;
   &lt;/jb:bindings&gt;

   &lt;!--
    This is a normal Javabean binding. Notice that we have a wiring on
    'product'. The Product entity will not be created, but looked up
    by a locator.
   --&gt;
   &lt;jb:bindings beanId="orderLine" class="example.entity.OrderLine"
                 createOnElement="order-item"&gt;
      &lt;jb:value property="quantity" data="quantity"/&gt;
      &lt;jb:wiring property="order" beanIdRef="order"/&gt;
      &lt;jb:wiring property="product" beanIdRef="product"/&gt;
   &lt;/jb:bindings&gt;

   &lt;!--
    This locator calls (via Scribe) the ProductDao#findById() method.
    The result will be added to the bean repository under
    the bean id 'product'.
    An exception is thrown when no result is found.
   --&gt;
   &lt;dao:locator beanId="product" dao="product" lookup="id"
           lookupOnElement="order-item" onNoResult="EXCEPTION"&gt;
      &lt;dao:params&gt;
         &lt;dao:value name="id" data="product" decoder="Integer"/&gt;
      &lt;/dao:params&gt;
   &lt;/dao:locator&gt;

   &lt;!--
    The inserter calls the OrderDao#insertOrder() method at
    end of Order message.
   --&gt;
   &lt;dao:inserter beanId="order" dao="order" insertOnElement="order" /&gt;

&lt;/smooks-resource-list&gt;</pre>
<p>The following code executes Smooks:</p>
<pre class="brush: java;">Smooks smooks = new Smooks("./smooks-configs/smooks-dao-config.xml");
ExecutionContext executionContext = smooks.createExecutionContext();

// The register is used to map the DAO's to a DAO name. The DAO name isbe used in
// the configuration.
// The MapRegister is a simple Map like implementation of the DaoRegister.
DaoRegister&lt;object&gt; register =
	MapRegister.builder()
		.put("product", new ProductDao(em))
		.put("order", new OrderDao(em))
		.build();

PersistenceUtil.setDAORegister(executionContext, mapRegister);

// Transaction management from within Smooks isn't supported yet,
// so we need to do it outside the filter execution
EntityTransaction tx = em.getTransaction();
tx.begin();

smooks.filter(new StreamSource(messageIn), null, executionContext);

tx.commit();</pre>
<p>If you want to take this example for a spin, simply check out the examples from subversion (http://svn.codehaus.org/milyn/trunk/smooks-examples/) and you&#8217;ll find it in the &#8220;dao-router&#8221; folder.  It also shows you how to use JPA directly, without any DAOs in between.</p>
<p>The cartridge is almost ready for it&#8217;s first release.  There is one thing that I am still not completely sure about and it would be great if people could provide some feedback.  I am not completely happy about the action names: <strong>insert</strong>, <strong>update </strong>and <strong>delete</strong>.  In the world of persistence frameworks, different sets of names are used for these actions.  JPA, for instance, uses <strong>persist</strong>, <strong>merge </strong>and <strong>remove</strong>.  Hibernate (outside of JPA) uses <strong>save, update</strong> and <strong>delete </strong>and Ibatis uses <strong>insert</strong>, <strong>update</strong> and <strong>delete</strong>. Which names would you choose and why?</p>
<p>In the next post of the series I will explain how to use Hibernate directly.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smooks.org/2009/02/26/smooks-persistence-part-1-the-introduction/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>
