<?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>Java crumbs &#187; Spring</title>
	<atom:link href="http://blog.krecan.net/tag/spring/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.krecan.net</link>
	<description>Short remarks from Java world</description>
	<lastBuildDate>Tue, 27 Jul 2010 13:56:29 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Streaming a stream</title>
		<link>http://blog.krecan.net/2009/02/27/streaming-a-stream/</link>
		<comments>http://blog.krecan.net/2009/02/27/streaming-a-stream/#comments</comments>
		<pubDate>Fri, 27 Feb 2009 10:53:01 +0000</pubDate>
		<dc:creator>Lukáš Křečan</dc:creator>
				<category><![CDATA[Articles in English]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[HttpInvoker]]></category>
		<category><![CDATA[InputStream]]></category>
		<category><![CDATA[RMIIO]]></category>
		<category><![CDATA[Serializable]]></category>
		<category><![CDATA[serialization]]></category>

		<guid isPermaLink="false">http://blog.krecan.net/?p=286</guid>
		<description><![CDATA[I have another dirty trick for you. Let's imagine that you have a document server with following sophisticated interface.

public interface DocumentServer {
	/**
	 * Stores a document.
	 * @return document id
	 */
	public String storeDocument(InputStream in);

	/**
	 * Loads document with given id.
	 * @param id
	 * @return
	 */
	public InputStream loadDocument(String id);
}

It works well, until you realize, that [...]]]></description>
			<content:encoded><![CDATA[<p>I have another dirty trick for you. Let's imagine that you have a document server with following sophisticated interface.</p>
<pre name="code" class="java">
public interface DocumentServer {
	/**
	 * Stores a document.
	 * @return document id
	 */
	public String storeDocument(InputStream in);

	/**
	 * Loads document with given id.
	 * @param id
	 * @return
	 */
	public InputStream loadDocument(String id);
}
</pre>
<p>It works well, until you realize, that you want to call the DocumentServer remotely, for example using Spring <a href="http://static.springframework.org/spring/docs/2.0.x/reference/remoting.html#remoting-httpinvoker">HttpInvoker</a>. </p>
<p>HttpInvoker is a nice small tool, that lets you make remote method invocations over HTTP without much pain. It creates dynamic proxy, serializes all attributes using Java serialization, calls remote proxy, which deserializes arguments, calls the implementation and sends the result back in the same way. It is nice, simple and it works without any problem. You can configure it in five minutes. The downside is, that you have to have Spring Java application on both ends of the wire and all arguments that you send over the wire have to be Serializable.</p>
<p>And that's exactly the trouble we have with our DocumentServer. There is no standard InputStream implementation that implements serializable. Lets think about it. We need to have a stream that is able to stream itself into an <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/io/ObjectOutputStream.html">ObjectOutputStream</a>. Sounds strange, but it is quite easy. We can simply write a wrapper, that implements <a href="http://java.sun.com/developer/technicalArticles/Programming/serialization/">writeObject(ObjectOutputStream)</a> method and that takes all the bytes from the underlying stream and writes them to the ObjectOutputStream. It is simple and it does not consume much memory.</p>
<p>Deserialization is much harder. We have to implement readObject(ObjectInputStream in) method, load the data and store them somewhere for later use. We can store them in the memory or in a temporary file. If the streams are larger, temporary file is better choice but we have to delete them after use and the implementation gets messy. </p>
<p>The good news is, that we do not have to implement it, it's already done by <a href="http://openhms.sourceforge.net/rmiio/">RMIIO</a> library. They provide <a href="http://openhms.sourceforge.net/rmiio/apidocs/com/healthmarketscience/rmiio/SerializableInputStream.html">SerializableInputStream</a> class that does exactly what we need. You just have to ignore Javadoc comment saying:</p>
<blockquote><p>An additional layer around a RemoteInputStream which makes it Serializable and an InputStream. In general, this extra layer is not necessary and I do not recommend using this class. However, in the odd case where the callee really wants to get something which is already an InputStream, this class can be useful. </p></blockquote>
<p>The only thing we have to do is to wrap all the streams into SerializableInputStream like this</p>
<pre name="code" class="java">
new SerializableInputStream(new DirectRemoteInputStream(inputStream));
</pre>
<p>It can be done by hand written proxy, by dynamically generated proxy or by AOP.</p>
<p>Of course there are other alternatives. The easiest one is to create something like ByteArayInputStream that implements Serializable. If the streams are small enough, it's the best solution. </p>
<p>We can also try to use <a href="http://static.springframework.org/spring/docs/2.0.x/reference/remoting.html#remoting-caucho-protocols-hessian">Hessian</a>, but I had some troubles when method signatures were more complicated. And of course there is still a possibility to implement own remoting mechanism. After all, HTTP is meant to transport streams. But it would require lot of boilerplate code and I do not like boilerplate code. </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.krecan.net/2009/02/27/streaming-a-stream/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Spring managed Hibernate interceptor in JPA</title>
		<link>http://blog.krecan.net/2009/01/24/spring-managed-hibernate-interceptor-in-jpa/</link>
		<comments>http://blog.krecan.net/2009/01/24/spring-managed-hibernate-interceptor-in-jpa/#comments</comments>
		<pubDate>Sat, 24 Jan 2009 16:29:27 +0000</pubDate>
		<dc:creator>Lukáš Křečan</dc:creator>
				<category><![CDATA[Articles in English]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[injection]]></category>
		<category><![CDATA[interceptor]]></category>
		<category><![CDATA[JPA]]></category>

		<guid isPermaLink="false">http://blog.krecan.net/?p=261</guid>
		<description><![CDATA[I have been trying to teach Hibernate injecting dependencies into Entities (I know, there is magic @Configurable annotation, I wanted to try it without magic). It is quite easy to do it using Hibernate interceptor (for example like this). But there is one drawback. It is not straightforward to inject interceptor into Hibernate when JPA [...]]]></description>
			<content:encoded><![CDATA[<p>I have been trying to teach Hibernate injecting dependencies into Entities (I know, there is magic <a href="http://static.springframework.org/spring/docs/2.5.x/reference/aop.html#aop-atconfigurable">@Configurable</a> annotation, I wanted to try it without magic). It is quite easy to do it using Hibernate interceptor (for example like <a href="https://java-crumbs.svn.sourceforge.net/svnroot/java-crumbs/jpa-test/tags/jpa-test-3.0/jpa-test/src/main/java/net/krecan/javacrumbs/jpa/interceptor/SpringInjectingInterceptor.java">this</a>). But there is one drawback. It is not straightforward to inject interceptor into Hibernate when JPA abstraction is in the way. </p>
<p>It is simple to define interceptor in <code>persistence.xml</code> using <a href="http://www.hibernate.org/hib_docs/entitymanager/reference/en/html/configuration.html#setup-configuration-bootstrapping">hibernate.ejb.interceptor</a> property. But it is only possible to specify class name, you can not inject Spring bean. If you read documentation to Spring <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/orm/jpa/LocalContainerEntityManagerFactoryBean.html">LocalContainerEntityManagerFactoryBean</a> there is no possibility to specify the interceptor bean there neither. But there is a way how to achieve it. First of all, you have to redefine Hibernate PersistenceProvider. </p>
<pre name="code" class="java">
public class ConfigurableHibernatePersistence extends HibernatePersistence {
	private Interceptor interceptor;
	public Interceptor getInterceptor() {
		return interceptor;
	}

	public void setInterceptor(Interceptor interceptor) {
		this.interceptor = interceptor;
	}

	@SuppressWarnings("unchecked")
	@Override
	public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map map) {
		Ejb3Configuration cfg = new Ejb3Configuration();
		Ejb3Configuration configured = cfg.configure( info, map );
		postprocessConfiguration(info, map, configured);
		return configured != null ? configured.buildEntityManagerFactory() : null;
	}

	@SuppressWarnings("unchecked")
	protected void postprocessConfiguration(PersistenceUnitInfo info, Map map, Ejb3Configuration configured) {
		if (this.interceptor != null)
		{
			if (configured.getInterceptor()==null || EmptyInterceptor.class.equals(configured.getInterceptor().getClass()))
			{
				configured.setInterceptor(this.interceptor);
			}
			else
			{
				throw new IllegalStateException("Hibernate interceptor already set in persistence.xml ("+configured.getInterceptor()+")");
			}
		}
	}
}
</pre>
<p>(<a href="https://java-crumbs.svn.sourceforge.net/svnroot/java-crumbs/jpa-test/tags/jpa-test-3.0/jpa-test/src/main/java/net/krecan/javacrumbs/jpa/interceptor/ConfigurableHibernatePersistence.java">source</a>)</p>
<p>Here we override method <code>createContainerEntityManagerFactory</code> in order to add <code>postprocessConfiguration</code> method call. In this method, it is possible to change Hibernate configuration as needed. Now the only thing to be done is configuring Spring to use our new PersistenceProvider. It is quite simple.</p>
<pre name="code" class="xml">
	&lt;bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"&gt;
		&lt;property name="persistenceUnitName" value="testPU" /&gt;
		&lt;property name="dataSource" ref="dataSource" /&gt;
		&lt;property name="persistenceProvider"&gt;
			&lt;bean class="net.krecan.javacrumbs.jpa.interceptor.ConfigurableHibernatePersistence"&gt;
				&lt;property name="interceptor"&gt;
					&lt;bean class="net.krecan.javacrumbs.jpa.interceptor.SpringInjectingInterceptor"/&gt;
				&lt;/property&gt;
			&lt;/bean&gt;
		&lt;/property&gt;
	&lt;/bean&gt;
</pre>
<p>And that all folks, we have Spring configured interceptor even when using JPA abstraction. It would be better if similar classes were in Spring or Hibernate, but it's just few lines of code so feel free to copy them if you need to. If you know easier way how to do it, please mention it in the comments below.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.krecan.net/2009/01/24/spring-managed-hibernate-interceptor-in-jpa/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Skrytý drahokam Springu</title>
		<link>http://blog.krecan.net/2009/01/22/skryty-drahokam-springu/</link>
		<comments>http://blog.krecan.net/2009/01/22/skryty-drahokam-springu/#comments</comments>
		<pubDate>Thu, 22 Jan 2009 19:25:16 +0000</pubDate>
		<dc:creator>Lukáš Křečan</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[Annotation]]></category>
		<category><![CDATA[AspectJ]]></category>
		<category><![CDATA[Configurable]]></category>

		<guid isPermaLink="false">http://blog.krecan.net/?p=243</guid>
		<description><![CDATA[	Dnes jsem koukal na rozhovor s Rodem Johnsonem, v kterém mluvil o novinkách ve Springu 3.0. Mezi řečí se zmínil o anotaci @Configurable, která je už ve Springu 2.5 a označil ji za skrytý drahokam. Protože jsem o něčem takovém slyšel poprvé, tak jsem se podíval do dokumentace a docela mě to zaujalo. (Teda, teď [...]]]></description>
			<content:encoded><![CDATA[<p>	Dnes jsem koukal na <a href="http://www.infoq.com/interviews/Spring-3.0-Rod-Johnson">rozhovor s Rodem Johnsonem</a>, v kterém mluvil o novinkách ve Springu 3.0. Mezi řečí se zmínil o anotaci <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/beans/factory/annotation/Configurable.html">@Configurable</a>, která je už ve Springu 2.5 a označil ji za skrytý drahokam. Protože jsem o něčem takovém slyšel poprvé, tak jsem se podíval do <a href="http://static.springframework.org/spring/docs/2.5.x/reference/aop.html#aop-atconfigurable">dokumentace</a> a docela mě to zaujalo. (Teda, teď koukám, že jsem se o něčem podobném zmiňoval už před půl rokem <a href="http://blog.krecan.net/2007/06/03/uz-tam-budem/">zde</a>, ach ta paměť). V zásadě jde o to, že obvykle funguje dependency injection jen u bean, které spravuje Spring. Takže například nejde použít u JPA entit a podobně. Což je docela škoda, protože pak musíme dělat umělou servisní vrstvu a objektový model tím docela trpí. Máme na jednu stranu třídy, které drží stav (entity) a na druhou stranu servisní třídy, v kterých je jen kód a stavu mají pomálu. Ale ve správném objektovém programování bychom měli mít třídy, které kombinují oboje. Takže například objekt <code>User</code> by měl mít metodu <code>remove()</code>, která by ho smazala z databáze. Jenže to by znamenalo, že by každá instance této třídy musela mít v sobě odkaz na <code>EntityManager</code> nebo ještě lépe DAO, což neumíme injektnout. </p>
<p>Možná si říkáte, že jsem se zbláznil, že to je ošklivé. Musím se přiznat, že mi je tento přístup taky cizí, ale asi je to jen otázka zvyku. Nejspíš jsem jen zvyklý na to procedurální programování, kde mám servisní procedury v singletonu a jim předhazuji hloupé datové objekty, které se o sebe neumějí postarat samy. </p>
<p>	Anotace <code>@Configurable</code> je tu právě od toho, aby nám usnadnila injektování i do bean, které nejsou spravovány Springem. Předvedu na příkladu. Mám třídu <code>Bean</code>, které se dá podstrčit nějaký text.</p>
<pre name="code" class="java">
@Configurable
public class Bean {
	private String text;
	public String getText() {
		return text;
	}
	public void setText(String text) {
		this.text = text;
	}
}
</pre>
<p>Mým cílem je zprovoznit tento test.</p>
<pre name="code" class="java">
	public void testIt()
	{
		Bean bean = new Bean();
		assertEquals("Hallo",bean.getText());
	}
</pre>
<p>Všimněte si, že vytvářím novou instanci a koukám se, co je v ní nastaveno za text. Podle všeho by tam mělo být <code>null</code>. Ale pokud správně poladím Spring, tak tam může být cokoliv. </p>
<p>	Prvním krokem je samozřejmě anotace <code>@Configurable</code>, která označí beanu jako kandidáta na injektování. V druhém kroku musím nastavit, co chci injektnout. Mohu například zvolit klasickou XML konfiguraci.</p>
<pre name="code" class="xml">
	&lt;bean class="net.krecan.configurable.Bean" scope="prototype"&gt;
		&lt;property name="text" value="Hallo"/&gt;
	&lt;/bean&gt;

	&lt;context:spring-configured/&gt;

	&lt;context:load-time-weaver/
</pre>
<p>	Zde si všimněme několika věcí. Například toho, že Spring pozná to kam má co injektnout automaticky, podle jména třídy. Nicméně dají se použít i vlastní jména. Pak si všimněme použití rozsahu „<code>protoype</code>“. To dává smysl, já mohu new zavolat kolikrát chci (i když tam to <code>protoype</code> nedáte, tak se to chová stejně, takhle je to jen hezčí).  No a pak už nám zbývá jen magie. Pomocí prvního kouzelného slůvka <code>&lt;context:spring-configured/&gt;</code> zařídíme, aby se použil AspectJ aspekt, který to všechno zařídí. Ano, musí se použít AspectJ, zázraky ani Spring nedovede. Zatím.  </p>
<p>	Druhé kouzelné slůvko <code>&lt;context:load-time-weaver/&gt;</code> nastaví AspectJ, tak aby si podle potřeby při startu aplikace upravil třídy. Aby to totiž všechno fungovalo, tak je potřeba upravit bytecode. A to buď při kompilaci nebo při startu aplikace. Já jsem zvolil druhou variantu, která bohužel také vyžaduje, abyste to celé spouštěli s atributem virtuálního stroje <code>-javaagent:spring-agent-2.5.6.jar</code>. Pokud si kód budete zkoušet sami, tak na to prosím nezapomeňte.</p>
<p>	A to je vše, testy projdou bez problému. Vidíme, že Spring umí injektovat i do tříd, nad kterými na první pohled nemá kontrolu. A to aniž bychom nějak zvlášť museli študovat AspectJ. Všechno už máme pěkně připraveno. Samozřejmě, uvedený příklad je umělý, ale pokud bychom našli dost odvahy, tak můžeme bez problémů injektnout EntityManager přímo do entit. A to může být docela užitečné.</p>
<p>	Zdrojový kód je ke stažení <a href="https://java-crumbs.svn.sourceforge.net/svnroot/java-crumbs/trunk/spring-configurable">zde</a>, obzvláště doporučuji extra zvrhlou třídu <a href="https://java-crumbs.svn.sourceforge.net/svnroot/java-crumbs/trunk/spring-configurable/src/main/java/net/krecan/configurable/MagicBean.java">MagicBean</a>. No a pokud chcete umět Spring tak skvěle jako já, tak se mi ozvěte, můžu vás to naučit <img src='http://blog.krecan.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> .</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.krecan.net/2009/01/22/skryty-drahokam-springu/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Selects are IN</title>
		<link>http://blog.krecan.net/2008/05/10/selects-are-in/</link>
		<comments>http://blog.krecan.net/2008/05/10/selects-are-in/#comments</comments>
		<pubDate>Sat, 10 May 2008 16:52:06 +0000</pubDate>
		<dc:creator>Lukáš Křečan</dc:creator>
				<category><![CDATA[Articles in English]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[JDBC]]></category>
		<category><![CDATA[SimpleJdbcTemplate]]></category>

		<guid isPermaLink="false">http://blog.krecan.net/?p=71</guid>
		<description><![CDATA[Today it will be short. I will write about one small Spring feature that I have discovered recently.  It is another nice functionality of SimpleJdbcTemplate. 
Imagine that you want to find all account with given account numbers. Since we want to gain maximal performance we want to do it in one SQL statement. 
SELECT [...]]]></description>
			<content:encoded><![CDATA[<p>Today it will be short. I will write about one small Spring feature that I have discovered recently.  It is another nice functionality of <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/jdbc/core/simple/SimpleJdbcTemplate.html">SimpleJdbcTemplate</a>. </p>
<p>Imagine that you want to find all account with given account numbers. Since we want to gain maximal performance we want to do it in one SQL statement. </p>
<p>SELECT ACCOUNT_NUMBER, BALANCE FROM ACCOUNT WHERE ACCOUNT_NUMBER IN (?, ?)</p>
<p>Using Spring it is easy. The only trouble is, that I do not know number of account numbers beforehand. Therefore I do not know the number of question marks needed in the SQL query. Of course I can create the statement dynamically using string manipulation, but the code would be messy. Fortunately Spring comes to rescue. If I use named parameters in SimpleJdbcTemplate, Spring will automatically do everything for me. So the code will be nice and simple as it should be</p>
<pre name="code" class="java">
	public List&lt;Account&gt; findAccounts(Set&lt;String&gt; accountNumbers)
	{
		return getSimpleJdbcTemplate().query(
				"SELECT ACCOUNT_NUMBER, BALANCE FROM ACCOUNT WHERE ACCOUNT_NUMBER IN (:accountNumbers)",
				ACCOUNT_ROW_MAPPER,
				Collections.singletonMap("accountNumbers", accountNumbers)
		);
	}
</pre>
<p>Nice, isn't it? Source code can be found in <a href="https://java-crumbs.svn.sourceforge.net/svnroot/java-crumbs/spring-demo/trunk/src/main/java/net/krecan/spring/jdbc">SVN</a>.  More details are in the <a href="http://static.springframework.org/spring/docs/2.5.x/reference/jdbc.html#jdbc-in-clause">Spring documentation</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.krecan.net/2008/05/10/selects-are-in/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Simple JDBC template</title>
		<link>http://blog.krecan.net/2008/03/02/simple-jdbc-template/</link>
		<comments>http://blog.krecan.net/2008/03/02/simple-jdbc-template/#comments</comments>
		<pubDate>Sun, 02 Mar 2008 09:36:15 +0000</pubDate>
		<dc:creator>Lukáš Křečan</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[JDBC]]></category>
		<category><![CDATA[SimpleJdbcTemplate]]></category>

		<guid isPermaLink="false">http://blog.krecan.net/2008/03/02/simple-jdbc-template/</guid>
		<description><![CDATA[	Občas se mi stane, že nepotřebuji celou tu mašinérii kolem ORM. Chci jenom přistupovat do databáze. Zavolat pár insertů a pár selectů. V té chvíli přichází na řadu JDBC. Je samozřejmě možné používat JDBC přímo, ale jak říká Rod Johnson, je to „sackable offence“. (česky asi důvod k vyhazovu). Zvládnout bez chyby všechny ty try, [...]]]></description>
			<content:encoded><![CDATA[<p>	Občas se mi stane, že nepotřebuji celou tu mašinérii kolem ORM. Chci jenom přistupovat do databáze. Zavolat pár insertů a pár selectů. V té chvíli přichází na řadu JDBC. Je samozřejmě možné používat JDBC přímo, ale jak říká Rod Johnson, je to „sackable offence“. (česky asi důvod k vyhazovu). Zvládnout bez chyby všechny ty try, catche, finally, zavírání connection, result setů a kdoví čeho ještě je jen pro zkušené a velmi disciplinované vývojáře. Spring odjakživa poskytoval rozhranní <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/jdbc/core/JdbcTemplate.html">JdbcTemplate</a>, které krásně usnadňovalo volání JDBC a staralo se o všechnu tu nudnou a nebezpečnou práci se správou zdrojů. Chybělo mi tam ale několik věcí. První z nich bylo pojmenování parametrů jak je známe třeba z HQL. Prostě jsem místo všech těch otazníků v query chtěl psát jména parametrů. Chybělo mi také lepší provázanost s Javou 5 a generiky. (To mi mimochodem dost chybí i u JPA query, která je novější než Java 5).</p>
<p>	Nevím jestli se vám to také děje. Já když už umím nějakou technologii, tak se mi občas stane, že mi její zajímavé novinky občas uniknou. Podobně mi uniklo zavedení <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/jdbc/core/simple/SimpleJdbcTemplate.html">SimpleJdbcTemplate</a> do Springu 2.0. SimpleJdbcTemplate totiž všechny mé stesky řeší. Nejlépe si to ukážeme na příkladě (ten je převzatý z mého skvělého a nepostradatelného projektu <a href="http://www.mvnindex.org/">MvnIndex.org</a>, který si teď všichni povinně stáhnete a začnete ho používat, nebo se naštvu a už nikdy nic podobného nenapíšu). </p>
<p>Nejlepší je naimplementovat DAO, které rozšiřuje <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/jdbc/core/simple/SimpleJdbcDaoSupport.html">SimpleJdbcDaoSupport</a>. Tím si ušetříme spoustu práce, stačí nám už jen injektnout do této třídy DataSource. Pak už máme k dispozici SimpleJdbcTemplate a můžeme si dovolit například takovéto volání:</p>
<div align="left" class="java">
<table border="0" cellpadding="3" cellspacing="0" bgcolor="#ffffff">
<tr>
  <!-- start source code --></p>
<td nowrap="nowrap" valign="top" align="left">
    <code><br />
<font color="#ffffff">&nbsp;&nbsp;</font><font color="#7f0055"><b>public&nbsp;</b></font><font color="#000000">List&lt;BasicArtifactInfo&gt;&nbsp;searchArtifacts</font><font color="#000000">(</font><font color="#000000">String&nbsp;searchExpression,&nbsp;PagingInfo&nbsp;pagingInfo</font><font color="#000000">)&nbsp;{</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">Map&lt;String,Object&gt;&nbsp;args&nbsp;=&nbsp;</font><font color="#7f0055"><b>new&nbsp;</b></font><font color="#000000">HashMap&lt;String,&nbsp;Object&gt;</font><font color="#000000">()</font><font color="#000000">;</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">args.put</font><font color="#000000">(</font><font color="#2a00ff">&#34;searchExpression&#34;</font><font color="#000000">,&nbsp;</font><font color="#2a00ff">&#34;%&#34;</font><font color="#000000">+searchExpression+</font><font color="#2a00ff">&#34;%&#34;</font><font color="#000000">)</font><font color="#000000">;</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">args.put</font><font color="#000000">(</font><font color="#2a00ff">&#34;from&#34;</font><font color="#000000">,&nbsp;pagingInfo.getFrom</font><font color="#000000">())</font><font color="#000000">;</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">args.put</font><font color="#000000">(</font><font color="#2a00ff">&#34;size&#34;</font><font color="#000000">,&nbsp;pagingInfo.getSize</font><font color="#000000">())</font><font color="#000000">;</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>return&nbsp;</b></font><font color="#000000">getSimpleJdbcTemplate</font><font color="#000000">()</font><font color="#000000">.query</font><font color="#000000">(</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#2a00ff">&#34;select&nbsp;distinct&nbsp;group_id,&nbsp;artifact_id&nbsp;from&nbsp;ARTIFACT&nbsp;where&nbsp;artifact_id&nbsp;like&nbsp;:searchExpression&nbsp;or&nbsp;group_id&nbsp;like&nbsp;:searchExpression&nbsp;order&nbsp;by&nbsp;if(group_id&nbsp;like&nbsp;:searchExpression,&nbsp;0,&nbsp;1),&nbsp;group_id,&nbsp;artifact_id&nbsp;limit&nbsp;:from,&nbsp;:size&#34;</font><font color="#000000">,&nbsp;</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">BASIC_ARTIFACT_INFO_MAPPER&nbsp;,&nbsp;</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">args</font><font color="#000000">)</font><font color="#000000">;</font><br />
<font color="#ffffff">&nbsp;&nbsp;</font><font color="#000000">}</font></code></p>
</td>
<p>  <!-- end source code --><br />
   </tr>
</table>
</div>
<p>Vidíme že atributy dotazu dáme jednoduše do mapy, zavoláme dotaz, poskytneme mapovač výsledků a je to. V dotazu můžeme použít jména parametrů stejně jako to známe z HQL. Takže můžeme například psát „<code>... where artifact_id like :searchExpression or group_id like :searchExpression...</code>“.  Pro mapování výsledků musíme implementovat jednoduché rozhraní ParameterizedRowMapper. </p>
<div align="left" class="java">
<table border="0" cellpadding="3" cellspacing="0" bgcolor="#ffffff">
<tr>
  <!-- start source code --></p>
<td nowrap="nowrap" valign="top" align="left">
    <code><br />
<font color="#ffffff">&nbsp;&nbsp;</font><font color="#7f0055"><b>private&nbsp;static&nbsp;final&nbsp;</b></font><font color="#000000">ParameterizedRowMapper&lt;BasicArtifactInfo&gt;&nbsp;BASIC_ARTIFACT_INFO_MAPPER&nbsp;=&nbsp;</font><font color="#7f0055"><b>new&nbsp;</b></font><font color="#000000">ParameterizedRowMapper&lt;BasicArtifactInfo&gt;</font><font color="#000000">(){</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>public&nbsp;</b></font><font color="#000000">BasicArtifactInfo&nbsp;mapRow</font><font color="#000000">(</font><font color="#000000">ResultSet&nbsp;rs,&nbsp;</font><font color="#7f0055"><b>int&nbsp;</b></font><font color="#000000">rowNum</font><font color="#000000">)&nbsp;</font><font color="#7f0055"><b>throws&nbsp;</b></font><font color="#000000">SQLException&nbsp;</font><font color="#000000">{</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>return&nbsp;new&nbsp;</b></font><font color="#000000">BasicArtifactInfo</font><font color="#000000">(</font><font color="#000000">rs.getString</font><font color="#000000">(</font><font color="#2a00ff">&#34;group_id&#34;</font><font color="#000000">)</font><font color="#000000">,&nbsp;rs.getString</font><font color="#000000">(</font><font color="#2a00ff">&#34;artifact_id&#34;</font><font color="#000000">))</font><font color="#000000">;</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">}</font><br />
<font color="#ffffff">&nbsp;&nbsp;</font><font color="#000000">}</font><font color="#000000">;</font></code></p>
</td>
<p>  <!-- end source code --><br />
   </tr>
</table>
</div>
<p>Vidíme, že generika jsou tu plně podporována, takže si nemusíme dělat hlavu s přetypováváním, varováními překladače atp. Super ne? A to jsem zapomněl na to hlavní. Spring se mi postará o vytvoření PreparedStatementů, správu transakcí, mapování vyjímek a prostě o všechno na co jsme od něj zvyklí.</p>
<p>Takže pokud je pro vás Hibernate moc těžkopádný a nechcete se učit iBatis, pokud chcete jen volat JDBC, zkuste se podívat na SimpleJdbcTemplate, stojí to za to.</p>
<p><em>Celou třídu si můžete prohlédnout v <a href="http://m2-repoindex.svn.sourceforge.net/svnroot/m2-repoindex/trunk/mvnindex/server/mvnindex-indexer-server/src/main/java/net/krecan/mvnindex/indexer/dao/jdbc/JdbcArtifactInfoDao.java">SVN</a>.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.krecan.net/2008/03/02/simple-jdbc-template/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Spring factory method</title>
		<link>http://blog.krecan.net/2008/01/16/spring-factory-method/</link>
		<comments>http://blog.krecan.net/2008/01/16/spring-factory-method/#comments</comments>
		<pubDate>Wed, 16 Jan 2008 17:18:18 +0000</pubDate>
		<dc:creator>Lukáš Křečan</dc:creator>
				<category><![CDATA[Articles in English]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Hibernate statistics]]></category>
		<category><![CDATA[session factory]]></category>

		<guid isPermaLink="false">http://blog.krecan.net/2008/01/16/spring-factory-method/</guid>
		<description><![CDATA[Today I am going to write about a small trick that I have used recently. Lets imagine following problem: we are using JPA (Hibernate) and Spring together.



&#60;bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"&#62;
	&#60;property name="persistenceUnitName" value="testPU" /&#62;
	&#60;property name="dataSource" ref="dataSource" /&#62;
	&#60;property name="jpaProperties"&#62;
		&#60;props&#62;
			&#60;prop key="hibernate.hbm2ddl.auto"&#62;${hibernate.hbm2ddl.auto}&#60;/prop&#62;
		&#60;/props&#62;
	&#60;/property&#62;
&#60;/bean&#62;



It works nice, without any problem. But imagine that one day you need to access Hibernate statistics. To achieve [...]]]></description>
			<content:encoded><![CDATA[<p>Today I am going to write about a small trick that I have used recently. Lets imagine following problem: we are using JPA (Hibernate) and Spring together.</p>
<div  class="xml">
<pre>
<code>
&lt;bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"&gt;
	&lt;property name="persistenceUnitName" value="testPU" /&gt;
	&lt;property name="dataSource" ref="dataSource" /&gt;
	&lt;property name="jpaProperties"&gt;
		&lt;props&gt;
			&lt;prop key="hibernate.hbm2ddl.auto"&gt;${hibernate.hbm2ddl.auto}&lt;/prop&gt;
		&lt;/props&gt;
	&lt;/property&gt;
&lt;/bean&gt;
</code>
</pre>
</div>
<p>It works nice, without any problem. But imagine that one day you need to access <a href="http://www.javalobby.org/java/forums/t19807.html">Hibernate statistics</a>. To achieve this, you have to have access to the Hibernate session factory. But we have no session factory here, we are using the entity manager which hides session factory underneath. How to access it? The solution is simple, you can use factory method. </p>
<div  class="xml">
<pre>
<code>
&lt;!-- Publishing session factory to be able view statistics --&gt;
&lt;bean id="sessionFactory" factory-bean="entityManagerFactory" factory-method="getSessionFactory" /&gt;
</code>
</pre>
</div>
<p>By this simple code we say to Spring: Hey, just call the method getSessionFactory on the entityManagerFactory bean and store the result as a bean with name sessionFactory.  Since we are using Hibernate as the JPA provider, entityManagerFactory is instance of <a href="http://www.hibernate.org/hib_docs/entitymanager/api/org/hibernate/ejb/HibernateEntityManagerFactory.html">HibernateEntityManagerFactory</a> and by a chance it has  getSessionFactory method. Now we have access to the session factory and we can use it however we like.</p>
<p><em>Note: If you wonder why the hell I have started to write in something that looks almost like English when apparently I do even more mistakes than in Czech, the answer is simple. I just need to practice my English (apart from that I want to be world famous, not just known in Czech Republic)</em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.krecan.net/2008/01/16/spring-factory-method/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Testing with Spring 2.5</title>
		<link>http://blog.krecan.net/2007/12/12/testing-with-spring-25/</link>
		<comments>http://blog.krecan.net/2007/12/12/testing-with-spring-25/#comments</comments>
		<pubDate>Wed, 12 Dec 2007 18:45:16 +0000</pubDate>
		<dc:creator>Lukáš Křečan</dc:creator>
				<category><![CDATA[Articles in English]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Tests]]></category>
		<category><![CDATA[test]]></category>
		<category><![CDATA[transaction]]></category>

		<guid isPermaLink="false">http://blog.krecan.net/2007/12/12/testing-with-spring-25/</guid>
		<description><![CDATA[Besides other cool features, Spring 2.5 brought completely rewritten support for functional tests.  Before this version, Spring had support for functional tests using JUnit 3 only. If you needed to use  JUnit 4 or TestNG you just did not get any help from the framework 
Now you can use brand new annotations and [...]]]></description>
			<content:encoded><![CDATA[<p>Besides other cool features, Spring 2.5 brought completely rewritten support for functional tests.  Before this version, Spring had support for functional tests using JUnit 3 only. If you needed to use  JUnit 4 or TestNG you just did not get any help from the framework </p>
<p>Now you can use brand new annotations and you are not constrained in your choice of testing framework any more. For complete information, please consult <a href="http://static.springframework.org/spring/docs/2.5.x/reference/testing.html#integration-testing">Spring reference</a>, I will show only small subset of the new features. Let's take a look on the first example.</p>
<div align="left" class="java">
<table border="0" cellpadding="3" cellspacing="0" bgcolor="#ffffff">
<tr>
  <!-- start source code --></p>
<td nowrap="nowrap" valign="top" align="left">
    <code><br />
<font color="#808080">01</font>&nbsp;<font color="#646464">@RunWith</font><font color="#000000">(</font><font color="#000000">SpringJUnit4ClassRunner.</font><font color="#7f0055"><b>class</b></font><font color="#000000">)</font><br />
<font color="#808080">02</font>&nbsp;<font color="#646464">@ContextConfiguration</font><font color="#000000">(</font><font color="#000000">locations=</font><font color="#2a00ff">&#34;classpath:applicationContext.xml&#34;</font><font color="#000000">)</font><br />
<font color="#808080">03</font>&nbsp;<font color="#646464">@Transactional</font><br />
<font color="#808080">04</font>&nbsp;<font color="#7f0055"><b>public&nbsp;class&nbsp;</b></font><font color="#000000">TestJpaClientDao&nbsp;</font><font color="#000000">{</font><br />
<font color="#808080">05</font>&nbsp;<font color="#ffffff"></font><br />
<font color="#808080">06</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;</font><font color="#7f0055"><b>private&nbsp;static&nbsp;final&nbsp;</b></font><font color="#7f0055"><b>long&nbsp;</b></font><font color="#000000">PERSONAL_NUM&nbsp;=&nbsp;</font><font color="#990000">123L</font><font color="#000000">;</font><br />
<font color="#808080">07</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;</font><font color="#646464">@Autowired</font><br />
<font color="#808080">08</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;</font><font color="#7f0055"><b>private&nbsp;</b></font><font color="#000000">ClientDao&nbsp;clientDao;</font><br />
<font color="#808080">09</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;</font><br />
<font color="#808080">10</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;</font><font color="#646464">@Test</font><br />
<font color="#808080">11</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;</font><font color="#7f0055"><b>public&nbsp;</b></font><font color="#7f0055"><b>void&nbsp;</b></font><font color="#000000">testCreateClient</font><font color="#000000">()</font><br />
<font color="#808080">12</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;</font><font color="#000000">{</font><br />
<font color="#808080">13</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">Client&nbsp;client&nbsp;=&nbsp;</font><font color="#7f0055"><b>new&nbsp;</b></font><font color="#000000">Client</font><font color="#000000">(</font><font color="#000000">PERSONAL_NUM</font><font color="#000000">)</font><font color="#000000">;</font><br />
<font color="#808080">14</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">client.setName</font><font color="#000000">(</font><font color="#2a00ff">&#34;John&nbsp;Doe&#34;</font><font color="#000000">)</font><font color="#000000">;</font><br />
<font color="#808080">15</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">client.addAddress</font><font color="#000000">(</font><font color="#7f0055"><b>new&nbsp;</b></font><font color="#000000">Address</font><font color="#000000">(</font><font color="#2a00ff">&#34;Old&nbsp;st.&#34;</font><font color="#000000">,</font><font color="#2a00ff">&#34;2a&#34;</font><font color="#000000">,</font><font color="#2a00ff">&#34;Prague&#34;</font><font color="#000000">,</font><font color="#2a00ff">&#34;120&nbsp;00&#34;</font><font color="#000000">))</font><font color="#000000">;</font><br />
<font color="#808080">16</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">client.addAccount</font><font color="#000000">(</font><font color="#7f0055"><b>new&nbsp;</b></font><font color="#000000">Account</font><font color="#000000">(</font><font color="#2a00ff">&#34;123-4560789&#34;</font><font color="#000000">))</font><font color="#000000">;</font><br />
<font color="#808080">17</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">client.addAccount</font><font color="#000000">(</font><font color="#7f0055"><b>new&nbsp;</b></font><font color="#000000">Account</font><font color="#000000">(</font><font color="#2a00ff">&#34;888-8888888&#34;</font><font color="#000000">))</font><font color="#000000">;</font><br />
<font color="#808080">18</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">clientDao.createClient</font><font color="#000000">(</font><font color="#000000">client</font><font color="#000000">)</font><font color="#000000">;</font><br />
<font color="#808080">19</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><br />
<font color="#808080">20</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">Client&nbsp;loadedClient&nbsp;=&nbsp;clientDao.loadClientWithPersonalNumber</font><font color="#000000">(</font><font color="#000000">PERSONAL_NUM</font><font color="#000000">)</font><font color="#000000">;</font><br />
<font color="#808080">21</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">assertSame</font><font color="#000000">(</font><font color="#000000">client,&nbsp;loadedClient</font><font color="#000000">)</font><font color="#000000">;</font><br />
<font color="#808080">22</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;</font><font color="#000000">}</font></code></p>
</td>
<p>  <!-- end source code --><br />
   </tr>
</table>
</div>
<p>Here we see normal class with some annotations. But it is not normal class, it is JUnit 4 test. By <code>RunWith </code>annotation we are extending usual JUnit test runner in order to enable Spring support. Then we have to define where application context XML file(s) are (<code>@ContextConfiguration</code> annotation).  Now we can use <code>Autowire </code>annotations to have all necessary dependencies injected. If we use annotation <code>Transactional </code>we obtain similar behavior as when we were using old <code>AbstractTransactionalSpringContextTests</code>. It means:</p>
<ol>
<li>
The application context is shared for all test methods (in all test classes). So all the stuff is initialized only once. If your test does some changes to the application context and it has to be therefore discarded, you can use <code>DirtiesContext</code> annotation.</li>
<li>
All test methods are run in transaction which is rolled back at the end of every test method. You can change this behavior by <code>Rollback</code> annotation or by <code>TransactionConfiguration</code> annotation.</li>
</ol>
<p>The new Spring test support is great. I just miss one thing. Old test support classes gave me possibility to finish and start a transaction in the middle of the test method (by calling <code>setComplete</code>, <code>finishTransaction</code> and <code>startNewTransaction</code>). I agree, that you do not need such feature very often, but sometimes it is handy. I was not able to find something similar in the new support classes. Finally I found a solution but it is not so straightforward as the old one (If you know better one please inform me). </p>
<p>In the following example I am trying to test whether my DAO is fetching addresses of the client so I do not get LazyInit exception. In my test I need to store a client to the database, finish the transaction, then load the client from the DB in a new transaction and finally check if the addresses are accessible even when no transaction is active. </p>
<div align="left" class="java">
<table border="0" cellpadding="3" cellspacing="0" bgcolor="#ffffff">
<tr>
  <!-- start source code --></p>
<td nowrap="nowrap" valign="top" align="left">
    <code><br />
<font color="#808080">01</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;</font><font color="#646464">@Test</font><br />
<font color="#808080">02</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;</font><font color="#646464">@NotTransactional</font><br />
<font color="#808080">03</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;</font><font color="#7f0055"><b>public&nbsp;</b></font><font color="#7f0055"><b>void&nbsp;</b></font><font color="#000000">testCreateAndLoadInTwoTransactions</font><font color="#000000">()</font><br />
<font color="#808080">04</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;</font><font color="#000000">{</font><br />
<font color="#808080">05</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>final&nbsp;</b></font><font color="#000000">Client&nbsp;client&nbsp;=&nbsp;</font><font color="#7f0055"><b>new&nbsp;</b></font><font color="#000000">Client</font><font color="#000000">(</font><font color="#000000">PERSONAL_NUM</font><font color="#000000">)</font><font color="#000000">;</font><br />
<font color="#808080">06</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">client.setName</font><font color="#000000">(</font><font color="#2a00ff">&#34;John&nbsp;Doe&#34;</font><font color="#000000">)</font><font color="#000000">;</font><br />
<font color="#808080">07</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">client.addAddress</font><font color="#000000">(</font><font color="#7f0055"><b>new&nbsp;</b></font><font color="#000000">Address</font><font color="#000000">(</font><font color="#2a00ff">&#34;Old&nbsp;st.&#34;</font><font color="#000000">,</font><font color="#2a00ff">&#34;2a&#34;</font><font color="#000000">,</font><font color="#2a00ff">&#34;Prague&#34;</font><font color="#000000">,</font><font color="#2a00ff">&#34;120&nbsp;00&#34;</font><font color="#000000">))</font><font color="#000000">;</font><br />
<font color="#808080">08</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">client.addAccount</font><font color="#000000">(</font><font color="#7f0055"><b>new&nbsp;</b></font><font color="#000000">Account</font><font color="#000000">(</font><font color="#2a00ff">&#34;123-4560789&#34;</font><font color="#000000">))</font><font color="#000000">;</font><br />
<font color="#808080">09</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">client.addAccount</font><font color="#000000">(</font><font color="#7f0055"><b>new&nbsp;</b></font><font color="#000000">Account</font><font color="#000000">(</font><font color="#2a00ff">&#34;888-8888888&#34;</font><font color="#000000">))</font><font color="#000000">;</font><br />
<font color="#808080">10</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">getTransactionTemplate</font><font color="#000000">()</font><font color="#000000">.execute</font><font color="#000000">(</font><font color="#7f0055"><b>new&nbsp;</b></font><font color="#000000">TransactionCallback</font><font color="#000000">(){</font><br />
<font color="#808080">11</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>public&nbsp;</b></font><font color="#000000">Object&nbsp;doInTransaction</font><font color="#000000">(</font><font color="#000000">TransactionStatus&nbsp;status</font><font color="#000000">)&nbsp;{</font><br />
<font color="#808080">12</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>return&nbsp;</b></font><font color="#000000">clientDao.createClient</font><font color="#000000">(</font><font color="#000000">client</font><font color="#000000">)</font><font color="#000000">;</font><br />
<font color="#808080">13</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">}</font><br />
<font color="#808080">14</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><br />
<font color="#808080">15</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">})</font><font color="#000000">;</font><br />
<font color="#808080">16</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">Client&nbsp;loadedClient&nbsp;=&nbsp;</font><font color="#000000">(</font><font color="#000000">Client</font><font color="#000000">)&nbsp;</font><font color="#000000">getTransactionTemplate</font><font color="#000000">()</font><font color="#000000">.execute</font><font color="#000000">(</font><font color="#7f0055"><b>new&nbsp;</b></font><font color="#000000">TransactionCallback</font><font color="#000000">(){</font><br />
<font color="#808080">17</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>public&nbsp;</b></font><font color="#000000">Object&nbsp;doInTransaction</font><font color="#000000">(</font><font color="#000000">TransactionStatus&nbsp;status</font><font color="#000000">)&nbsp;{</font><br />
<font color="#808080">18</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>return&nbsp;</b></font><font color="#000000">clientDao.loadClientWithPersonalNumber</font><font color="#000000">(</font><font color="#000000">PERSONAL_NUM</font><font color="#000000">)</font><font color="#000000">;</font><br />
<font color="#808080">19</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">}</font><br />
<font color="#808080">20</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">})</font><font color="#000000">;</font><br />
<font color="#808080">21</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">assertEquals</font><font color="#000000">(</font><font color="#990000">2</font><font color="#000000">,loadedClient.getAccounts</font><font color="#000000">()</font><font color="#000000">.size</font><font color="#000000">())</font><font color="#000000">;</font><br />
<font color="#808080">22</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><br />
<font color="#808080">23</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#3f7f5f">//cleanup</font><br />
<font color="#808080">24</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">getTransactionTemplate</font><font color="#000000">()</font><font color="#000000">.execute</font><font color="#000000">(</font><font color="#7f0055"><b>new&nbsp;</b></font><font color="#000000">TransactionCallback</font><font color="#000000">(){</font><br />
<font color="#808080">25</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>public&nbsp;</b></font><font color="#000000">Object&nbsp;doInTransaction</font><font color="#000000">(</font><font color="#000000">TransactionStatus&nbsp;status</font><font color="#000000">)&nbsp;{</font><br />
<font color="#808080">26</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">clientDao.deleteClient</font><font color="#000000">(</font><font color="#000000">client.getId</font><font color="#000000">())</font><font color="#000000">;</font><br />
<font color="#808080">27</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>return&nbsp;null</b></font><font color="#000000">;</font><br />
<font color="#808080">28</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">}</font><br />
<font color="#808080">29</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><br />
<font color="#808080">30</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">})</font><font color="#000000">;</font><br />
<font color="#808080">31</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><br />
<font color="#808080">32</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;</font><font color="#000000">}</font><br />
<font color="#808080">33</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;</font><font color="#7f0055"><b>private&nbsp;</b></font><font color="#000000">TransactionTemplate&nbsp;getTransactionTemplate</font><font color="#000000">()&nbsp;{</font><br />
<font color="#808080">34</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>return&nbsp;new&nbsp;</b></font><font color="#000000">TransactionTemplate</font><font color="#000000">(</font><font color="#000000">transactionManager</font><font color="#000000">)</font><font color="#000000">;</font><br />
<font color="#808080">35</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;</font><font color="#000000">}</font></code></p>
</td>
<p>  <!-- end source code --><br />
   </tr>
</table>
</div>
<p>As you can see, I have marked the method as <code>NonTransactional</code>. Therefore, Spring does not create a  transaction for me and I can manage my transaction programmatically. For example using Spring transaction template. And that's it.</p>
<p><em>The source code can be downloaded from SVN repository <a href="https://java-crumbs.svn.sourceforge.net/svnroot/java-crumbs/jpa-test/tags/jpa-test-1.0">here</a>.</em></p>
<p><em>Note: If you wonder why the hell I have started to write in something that looks almost like English when apparently I do even more mistakes than in Czech, the answer is simple. I just need to practice my English (apart from that I want to be world famous, not just known in Czech Republic)</em><code></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.krecan.net/2007/12/12/testing-with-spring-25/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>
