<?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>JavaBeat &#187; MYSQL</title>
	<atom:link href="http://www.javabeat.net/category/database/mysql/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.javabeat.net</link>
	<description>Java Technology News</description>
	<lastBuildDate>Mon, 13 May 2013 20:10:23 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Hibernate, Maven and HSQL – Example Project (Using Annotations)</title>
		<link>http://www.javabeat.net/2013/03/hibernate-maven-and-hsql-annotations/</link>
		<comments>http://www.javabeat.net/2013/03/hibernate-maven-and-hsql-annotations/#comments</comments>
		<pubDate>Mon, 11 Mar 2013 14:28:21 +0000</pubDate>
		<dc:creator>Manisha Patil</dc:creator>
				<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[MYSQL]]></category>
		<category><![CDATA[MySQL]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=6131</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>In this tutorial we will write a simple Java project to demonstrate Hibernate, HSQL and Maven using Java 5 Annotations. For this we will use our previous example in the post Hibernate, Maven and HSQL &#8211; Example Project (XML Mapping)) as base and convert it from XML Mapping to Annotation. HSQL database is used to [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><a id="dd_start"></a><p>In this tutorial we will write a simple Java project to demonstrate <span style="text-decoration: underline;"><strong>Hibernate, HSQL and Maven</strong></span> using Java 5 Annotations. For this we will use our previous example in the post <a title="Hibernate, Maven and HSQL - Example Project(XML Mapping)" href="http://www.javabeat.net/2013/03/hibernate-maven-hsql/">Hibernate, Maven and HSQL &#8211; Example Project (XML Mapping))</a> as base and convert it from XML Mapping to Annotation.<br />
HSQL database is used to make the project simple, as we can use in-memory database and we would need only a JAR file to be included in our project. If you have any questions, please post it in the comments section. If you are interested in receiving the future articles on Java topics, please subscribe <a title="subscribe" href="http://www.javabeat.net/subscribe/">here</a>. If you are beginner for hibernate, please read the articles about <a href="http://www.javabeat.net/2007/05/hibernate-ormobjectrelational-framework-an-introduction/">introduction to hibernate</a>, <a href="http://www.javabeat.net/2007/05/interceptors-in-hibernate-orm-framework-an-introduction/">interceptors in hibernate</a> and <a href="http://www.javabeat.net/2007/10/integrating-spring-framework-with-hibernate-orm-framework/">spring &amp; hibernate integration</a>. We also recommend good reference books for learning hibernate in our post about <a href="http://www.javabeat.net/hibernate-framework-books/">hibernate books.</a><a href="http://www.javabeat.net/wp-content/uploads/2009/02/hibernate.jpg"><img class="aligncenter size-full wp-image-3777" alt="hibernate" src="http://www.javabeat.net/wp-content/uploads/2009/02/hibernate.jpg" width="306" height="85" /></a>.</p>
<p>Following are the tools and technologies required for this project:</p>
<ul>
<ol>
<li>Java JDK 5 or above</li>
<li>Eclipse IDE 3.2 or above</li>
<li>Maven 3.0 or above</li>
<li>Hibernate 3.0 or above (Download from <a title="http://hibernate.org/downloads" href="http://hibernate.org/downloads" target="_blank">http://hibernate.org/downloads</a>)</li>
<li>HsqlDB (Download from <a href="http://hsqldb.org/" target="_blank">http://hsqldb.org/</a>)</li>
</ol>
</ul>
<h2>1. Generating Maven Java project compatible with Eclipse</h2>
<p>Follow the steps in the post <a title="Hibernate, Maven and HSQL - Example Project(XML Mapping)" href="http://www.javabeat.net/2013/03/hibernate-maven-hsql/" target="_blank">Hibernate, Maven and HSQL &#8211; Example Project (XML Mapping))</a> to create project structure. Or you can directly download the source code from above post in Eclipse and rename the project in eclipse as <b>HibernateHelloWorldAnnotation</b>.</p>
<h2>2.Updating the Hibernate dependency in pom.xml</h2>
<p>As we are going to use Annotation mapping in Hibernate we will update our existing pom.xml file as below:</p>
<pre class="brush: java; title: ; notranslate">
 &lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
 xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd&quot;&gt;
 &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
 &lt;groupId&gt;net.javabeat.hibernate&lt;/groupId&gt;
 &lt;artifactId&gt;HibernateHelloWorldXML&lt;/artifactId&gt;
 &lt;packaging&gt;jar&lt;/packaging&gt;
 &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;
 &lt;name&gt;HibernateHelloWorldXML&lt;/name&gt;
 &lt;url&gt;http://maven.apache.org&lt;/url&gt;
 &lt;dependencies&gt;
   &lt;dependency&gt;
     &lt;groupId&gt;junit&lt;/groupId&gt;
     &lt;artifactId&gt;junit&lt;/artifactId&gt;
     &lt;version&gt;3.8.1&lt;/version&gt;
     &lt;scope&gt;test&lt;/scope&gt;
   &lt;/dependency&gt;
&lt;!-- Hibernate library dependecy start --&gt;
 &lt;b&gt; &lt;dependency&gt;
     &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
     &lt;artifactId&gt;hibernate-annotations&lt;/artifactId&gt;
     &lt;version&gt;4.1.9.Final&lt;/version&gt;
  &lt;/dependency&gt;&lt;/b&gt;
  &lt;dependency&gt;
     &lt;groupId&gt;org.hsqldb&lt;/groupId&gt;
     &lt;artifactId&gt;hsqldb&lt;/artifactId&gt;
     &lt;version&gt;2.2.9&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
     &lt;groupId&gt;dom4j&lt;/groupId&gt;
     &lt;artifactId&gt;dom4j&lt;/artifactId&gt;
     &lt;version&gt;1.6.1&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
     &lt;groupId&gt;commons-logging&lt;/groupId&gt;
     &lt;artifactId&gt;commons-logging&lt;/artifactId&gt;
     &lt;version&gt;1.1.1&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
     &lt;groupId&gt;commons-collections&lt;/groupId&gt;
     &lt;artifactId&gt;commons-collections&lt;/artifactId&gt;
     &lt;version&gt;3.2.1&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
     &lt;groupId&gt;cglib&lt;/groupId&gt;
     &lt;artifactId&gt;cglib&lt;/artifactId&gt;
     &lt;version&gt;2.2&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
     &lt;groupId&gt;asm&lt;/groupId&gt;
     &lt;artifactId&gt;asm&lt;/artifactId&gt;
     &lt;version&gt;4.0&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
     &lt;groupId&gt;dom4j&lt;/groupId&gt;
     &lt;artifactId&gt;dom4j&lt;/artifactId&gt;
     &lt;version&gt;1.6.1&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
      &lt;groupId&gt;ehcache&lt;/groupId&gt;
      &lt;artifactId&gt;ehcache&lt;/artifactId&gt;
      &lt;version&gt;1.2.3&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
      &lt;groupId&gt;hibernate-tools&lt;/groupId&gt;
      &lt;artifactId&gt;hibernate-tools&lt;/artifactId&gt;
      &lt;version&gt;3.2.3.GA&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
      &lt;groupId&gt;jta&lt;/groupId&gt;
      &lt;artifactId&gt;jta&lt;/artifactId&gt;
      &lt;version&gt;1.1&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
      &lt;groupId&gt;log4j&lt;/groupId&gt;
      &lt;artifactId&gt;log4j&lt;/artifactId&gt;
      &lt;version&gt;1.2.11&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
      &lt;groupId&gt;oscache&lt;/groupId&gt;
      &lt;artifactId&gt;oscache&lt;/artifactId&gt;
      &lt;version&gt;2.1&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
      &lt;groupId&gt;persistence-api&lt;/groupId&gt;
      &lt;artifactId&gt;persistence-api&lt;/artifactId&gt;
      &lt;version&gt;1.0&lt;/version&gt;
   &lt;/dependency&gt;
  &lt;!-- Hibernate library dependency end --&gt;
&lt;/dependencies&gt;
&lt;/project&gt;
 </pre>
<p>As a next step, let&#8217;s execute the following command so that maven will download all the required JARs and update eclipse classpath. Go to the directory of the project (in our case it is C:\HibernateHelloWorldXML) and execute the following command:</p>
<pre class="brush: java; title: ; notranslate">
mvn eclipse:eclipse
</pre>
<p>This step is optional. If your Eclipse has Maven plugin installed in your IDE (Latest eclipse comes with this plugin built-in) you can just enable Maven dependencies by following these instructions : Right click on project &gt; Maven &gt; Enable Dependency Management.</p>
<h2>3. Delete the unused Hibernate Mapping file</h2>
<p>The file src\main\resources\net\javabeat\hibernate\Contact.hbm.xml is not required anymore. Delete this file from the project.</p>
<h2>4. Update the Model class file</h2>
<p>We will add simple annotations to the model class (<em>src\main\java\net\javabeat\hibernate\Contact.java</em>) as below:</p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.hibernate;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * Model class for Conact
 */
@Entity
@Table(name=&quot;CONTACT&quot;)
public class Contact implements Serializable {
   @Id
   @GeneratedValue
   private Integer contactId;

   @Column(name=&quot;name&quot;)
   private String name;

   public Contact() {
   }

   public Integer getContactId() {
      return contactId;
   }

   public void setContactId(Integer contactId) {
      this.contactId = contactId;
   }

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

}
</pre>
<h2>5.Update the Hibernate Utility class</h2>
<p>In our previous post for XML mapping, we were using Configuration class to generate SessionFactory object. In HibernateUtil we had following line of code:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
sessionFactory = new Configuration().configure().buildSessionFactory();
</pre>
<p>We will update this and use AnnotationConfiguration instead of Configuration(). The updated HibernateUtil.java file is as below:</p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {
   private static final SessionFactory sessionFactory;
   static {
      try {
	   sessionFactory = new AnnotationConfiguration().configure()
	      .buildSessionFactory();
	   } catch (Throwable ex) {
	   System.err.println(&quot;Initial SessionFactory creation failed.&quot; + ex);
	   throw new ExceptionInInitializerError(ex);
      }
   }

   public static SessionFactory getSessionFactory() {
      return sessionFactory;
   }
}
</pre>
<h2>6. Update Hibernate Configuration file</h2>
<p>The configuration file hibernate.cfg.xml, needs to be changed to add the new Annotation based entity class Contact.java instead of old XML Mapping Contact.hbm.xml. The updated src\main\resources\hibernate.cfg.xml is as below:</p>
<pre class="brush: java; title: ; notranslate">
&lt;?xml version='1.0' encoding='utf-8'?&gt;
&lt;!DOCTYPE hibernate-configuration PUBLIC
        &quot;-//Hibernate/Hibernate Configuration DTD 3.0//EN&quot;
        &quot;http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd&quot;&gt;
&lt;?xml version='1.0' encoding='utf-8'?&gt;
&lt;!DOCTYPE hibernate-configuration PUBLIC
        &quot;-//Hibernate/Hibernate Configuration DTD 3.0//EN&quot;
        &quot;http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd&quot;&gt;
&lt;hibernate-configuration&gt;
  &lt;session-factory&gt;
    &lt;!-- Database connection settings, Connect to HSQL, IN Memory  --&gt;
    &lt;property name=&quot;dialect&quot;&gt;org.hibernate.dialect.HSQLDialect&lt;/property&gt;
    &lt;property name=&quot;connection.driver_class&quot;&gt;org.hsqldb.jdbcDriver&lt;/property&gt;
    &lt;property name=&quot;connection.url&quot;&gt;jdbc:hsqldb:mem:test&lt;/property&gt;
    &lt;property name=&quot;connection.username&quot;&gt;sa&lt;/property&gt;
    &lt;property name=&quot;connection.password&quot;&gt;&lt;/property&gt;

     &lt;!-- JDBC connection pool (use the built-in) --&gt;
     &lt;property name=&quot;connection.pool_size&quot;&gt;1&lt;/property&gt;
     &lt;property name=&quot;show_sql&quot;&gt;true&lt;/property&gt;&lt;property name=&quot;format_sql&quot;&gt;true&lt;/property&gt;
     &lt;property name=&quot;cache.provider_class&quot;&gt;org.hibernate.cache.NoCacheProvider&lt;/property&gt;
     &lt;!--create the database schema on startup if required --&gt;
     &lt;property name=&quot;hbm2ddl.auto&quot;&gt;update&lt;/property&gt;
     &lt;mapping class=&quot;net.javabeat.hibernate.Contact&quot;&gt;&lt;/mapping&gt;
  &lt;/session-factory&gt;
&lt;/hibernate-configuration&gt;
</pre>
<p>Here we have replaced</p>
<pre class="brush: java; title: ; notranslate">
&lt;mapping resource=&quot;net/javabeat/hibernate/Contact.hbm.xml&quot;&gt;&lt;/mapping&gt;
</pre>
<p>with</p>
<pre class="brush: java; title: ; notranslate">
 &lt;mapping class=&quot;net.javabeat.hibernate.Contact&quot;&gt;&lt;/mapping&gt;
</pre>
<h2>7. Final project structure</h2>
<p>Once you have created all these source files, your project structure should look like following:<br />
<a href="http://www.javabeat.net/wp-content/uploads/2013/03/final_proj_stuct_annotation.jpg"><img class="size-medium wp-image-6133 aligncenter" alt="final_proj_stuct_annotation" src="http://www.javabeat.net/wp-content/uploads/2013/03/final_proj_stuct_annotation-160x300.jpg" width="160" height="300" /></a></p>
<h2>8. Execution of the above code</h2>
<p>Now let us execute the code we created above. Let&#8217;s run the App class.<br />
Right click on App.java &gt;Run As &gt; Java Application.<br />
On start of each thread, a database schema will be created and the following actions will happen.</p>
<ul>
<ul>
<li>Each time a new thread starts the database schema will change the existing one as we have set <i>hbm2ddl.auto option to update</i>.</li>
<li>The SQL statement generated gets displayed on the console. This is set using the show_sql option in the hibernate configuration file.</li>
</ul>
</ul>
<p><b>Output on the console:</b></p>
<pre class="brush: java; title: ; notranslate">
Maven + Hibernate + HSQL
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Hibernate:
    insert
    into
        CONTACT
        (contactId, name)
    values
        (null, ?)
Hibernate:
    insert
    into
        CONTACT
        (contactId, name)
    values
        (null, ?)
Hibernate:
    insert
    into
        CONTACT
        (contactId, name)
    values
        (null, ?)
Hibernate:
    select
        contact0_.contactId as contactId0_,
        contact0_.name as name0_
    from
        CONTACT contact0_
Jiya
Manisha
Riya
</pre>
<h2>Summary</h2>
<p>In this post we updated our previous Java project from post <a title="Hibernate, Maven and HSQL - Example Project(XML Mapping)" href="http://www.javabeat.net/2013/03/hibernate-maven-hsql/" target="_blank">Hibernate, Maven and HSQL &#8211; Example Project (XML Mapping))</a> using Maven and made it compatible with eclipse. Then we updated the Hibernate configuration file and also deleted the hibernate mapping file. We also updated our Model class with Java annotations. We used a simple HSQL database, to insert records into CONTACT table and also listed these records. In the next article we shall look into Hibernate Association (One-to-one mapping(XML mapping)). If you have any questions, please post it in the comments section. If you are interested in receiving the future articles on Java topics, please subscribe <a title="subscribe" href="http://www.javabeat.net/subscribe/">here</a></p>
<div class='dd_outer'><div class='dd_inner'><div id='dd_ajax_float'><div class='dd_button_v'><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="http%3A%2F%2Fwww.javabeat.net%2Fcategory%2Fdatabase%2Fmysql%2Ffeed%2F" send="false" show_faces="false"  layout="box_count" width="50"  ></fb:like></div><div style='clear:left'></div><div class='dd_button_v'><script type='text/javascript' src='https://apis.google.com/js/plusone.js'></script><g:plusone size='tall' href='http://www.javabeat.net/category/database/mysql/feed/'></g:plusone></div><div style='clear:left'></div><div class='dd_button_v'><a href="http://twitter.com/share" class="twitter-share-button" data-url="http://www.javabeat.net/category/database/mysql/feed/" data-count="vertical" data-text="MYSQL" data-via="javabeat" ></a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div style='clear:left'></div><div class='dd_button_extra_v'><script type="text/javascript">jQuery(document).load(function(){ stLight.options({publisher:'bab47279-62c9-46af-addc-79fd1fe8fee0'}); });</script><div class="st_email_custom"><span id='dd_email_text'>email</span></div></div><div style='clear:left'></div><div class='dd_button_extra_v'><div id='dd_print_button'><span id='dd_print_text'><a href='javascript:window:print()'>print</a></span></div></div><div style='clear:left'></div></div></div></div><script type="text/javascript">var dd_offset_from_content = 44; var dd_top_offset_from_content = 0;</script><script type="text/javascript" src="http://www.javabeat.net/wp-content/plugins/digg-digg//js/diggdigg-floating-bar.js?ver=5.3.0"></script><div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2013/03/hibernate-maven-and-hsql-annotations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Spring Batch Infrastructure</title>
		<link>http://www.javabeat.net/2011/04/the-spring-batch-infrastructure/</link>
		<comments>http://www.javabeat.net/2011/04/the-spring-batch-infrastructure/#comments</comments>
		<pubDate>Fri, 01 Apr 2011 09:35:08 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[MYSQL]]></category>
		<category><![CDATA[Spring Framework]]></category>
		<category><![CDATA[Spring Batch]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=609</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>This article is based on SpringBatch in Action, to be published July-2011. It is being reproduced here by permission from Manning Publications. Manning publishes MEAP (Manning Early Access Program,) ebooks and pbooks. MEAPs are sold exclusively through Manning.com. All print book purchases include an ebook free of charge. When mobile formats become available all customers [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><em>This article is based on <a href="http://www.manning.com/templier/">SpringBatch in Action</a>, to be published July-2011. It is being reproduced here by permission from <a href="http://www.manning.com">Manning Publications</a>. Manning publishes MEAP (Manning Early Access Program,) ebooks and pbooks. MEAPs are sold exclusively through Manning.com. All print book purchases include an ebook free of charge. When mobile formats become available all customers will be contacted and upgraded. Visit Manning.com for more information.</em></p>
<p><center></p>
<h1>The Spring Batch Infrastructure</h1>
<p></center>The Spring Batch infrastructure includes components that launch your batch jobs and store job execution metadata. As a batch application developer, you don’t have to deal directly with these components because they provide supporting roles to your applications. However, you need to configure this infrastructure at least once in your Spring Batch application.</p>
<p>This article gives an overview of the job launcher, job repository, and their interactions, before showing how to configure persistence of the job repository.</p>
<h2>Launching jobs and storing job metadata</h2>
<p>The Spring Batch infrastructure is quite complex, but you mainly need to deal with two components: the job launcher and the job repository. These concepts match two straightforward Java interfaces: JobLauncher and JobRepository. Let’s start by studying the job launcher.</p>
<h3>The job launcher</h3>
<p>As figure 1 shows, the job launcher is the entry point to launch Spring Batch jobs.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/04/1.jpg"><img class="aligncenter size-medium wp-image-1147" title="1" src="http://www.javabeat.net/wp-content/uploads/2011/04/1-300x141.jpg" alt="" width="300" height="141" /></a>This is where the external world meets Spring Batch. The JobLauncher interface is simple:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">package org.springframework.batch.core.launch;
	(...)
	public interface JobLauncher {
		public JobExecution run(Job job, JobParameters jobParameters)
		throws JobExecutionAlreadyRunningException,
			JobRestartException, JobInstanceAlreadyCompleteException,
			JobParametersInvalidException;
	}</pre></td></tr></table></div>

<p>The run method accepts two parameters: a Job, which is typically a Spring bean configured in Spring Batch XML, and a JobParameters, which is usually created on the fly by the launching mechanism.</p>
<p>Who calls the job launcher? Your own Java program can use the job launcher to launch a job but so can command-line programs or schedulers (like cron or the Java-based Quartz).</p>
<p>The job launcher encapsulates launching strategies, like executing a job synchronously or asynchronously. Spring Batch provides one implementation of the JobLauncher interface: SimpleJobLauncher. The SimpleJobLauncher class only launches a job but doesn’t create it because it delegates this work to the job repository.</p>
<h3>The job repository</h3>
<p>The job repository maintains all metadata related to job executions. Here is the definition of the JobRepository interface:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">package org.springframework.batch.core.repository;
&nbsp;
	(...)
&nbsp;
	public interface JobRepository {
		boolean isJobInstanceExists(String jobName, JobParameters jobParameters);
		JobExecution createJobExecution(
			String jobName, JobParameters jobParameters)
			throws JobExecutionAlreadyRunningException, JobRestartException,
			JobInstanceAlreadyCompleteException;
		void update(JobExecution jobExecution);
&nbsp;
		void add(StepExecution stepExecution);
&nbsp;
		void update(StepExecution stepExecution);
&nbsp;
		void updateExecutionContext(StepExecution stepExecution);
&nbsp;
		void updateExecutionContext(JobExecution jobExecution);
&nbsp;
		StepExecution getLastStepExecution(JobInstance jobInstance,
			String stepName);
&nbsp;
		int getStepExecutionCount(JobInstance jobInstance, String stepName);
&nbsp;
		JobExecution getLastJobExecution(String jobName,
			JobParameters jobParameters);
	}</pre></td></tr></table></div>

<p>The JobRepository interface provides all the services to manage the batch job lifecycle including the creation and the updates.</p>
<p>Figure 2 shows how a Spring Batch application interacts with the outside world.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/04/2.jpg"><img class="aligncenter size-medium wp-image-1148" title="2" src="http://www.javabeat.net/wp-content/uploads/2011/04/2-300x87.jpg" alt="" width="300" height="87" /></a>To explain the interactions in figure 2, the job launcher delegates job creation to the job repository and a job calls the job repository during execution to store its current state. This is useful for monitoring how your job executions proceed and restarting a job exactly where it failed. Note that the Spring Batch runtime handles all calls to the job repository, meaning that persistence of the job execution metadata is transparent to the application developer.</p>
<p>What constitutes runtime metadata? It includes the list of executed steps, how many items Spring Batch read, wrote, or skipped, the duration of each step, and so forth.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>Spring Batch provides two implementations of the JobRepository interface. One stores metadata in memory, which is useful for testing or when you don’t want monitoring or restart capabilities, and the other stores metadata in a relational database. Next, we see how to configure the Spring Batch infrastructure in a database.</p>
<h2>Configuring the Spring Batch infrastructure in a database</h2>
<p>Spring Batch provides a job repository implementation to store your job metadata in a database. This allows you to monitor the execution of your batch processes and their results (success or failure.) Persistent metadata also makes it possible to restart a job exactly where it failed.</p>
<p>Spring Batch delivers the following to support persistent job repositories:</p>
<ul>
<li>SQL scripts to create the necessary database tables for the most popular database engines</li>
<li>A database implementation of JobRepository (SimpleJobRepository) that executes all necessary SQL statements to insert, update, and query the job repository tables</li>
</ul>
<p>Let’s now see how to configure the database job repository.</p>
<h3>Creating the database tables for a job repository</h3>
<p>The SQL scripts to create the database tables are located in the core Spring Batch JAR file, in the org.springframework.batch.core package. The SQL scripts use the following naming convention: schema-[database].sql for creating tables and schema-drop-[database].sql for dropping tables, where [database] is the name of a database engine. To initialize H2 for Spring Batch, we use the file schema-h2.sql.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="language" style="font-family:monospace;"> &lt;strong&gt;Spring Batch Database Support&lt;/strong&gt;</pre></td></tr></table></div>

<p>Spring Batch supports the following database engines: DB2, Derby, H2, HSQLDB, MySQL, Oracle, PostgreSql, SQLServer, and Sybase.</p>
<p>Create a database for Spring Batch and then execute the corresponding SQL script for your database engine.</p>
<h3>Configuring the job repository with Spring</h3>
<p>Listing 1 shows how to configure a job repository in a database:</p>
<p><strong>Listing 1 Configuration of a persistent job repository</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
	&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
		xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
		xmlns:batch=&quot;http://www.springframework.org/schema/batch&quot;
		xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/batch
		http://www.springframework.org/schema/batch/spring-batch-2.1.xsd&quot;&gt;
		&lt;batch:job-repository id=&quot;jobRepository&quot; #1
			data-source=&quot;dataSource&quot; #1
			transaction-manager=&quot;transactionManager&quot; /&gt; #1
		&lt;bean id=&quot;jobLauncher&quot;
			class=&quot;org.springframework.batch.core.launch.support.SimpleJobLauncher&quot;&gt;
			&lt;property name=&quot;jobRepository&quot; ref=&quot;jobRepository&quot; /&gt;
		&lt;/bean&gt;
		&lt;bean id=&quot;dataSource&quot; #2
			class=&quot;org.springframework.jdbc.datasource. #2
			[CA]SingleConnectionDataSource&quot;&gt; #2
			&lt;property name=&quot;driverClassName&quot; #2
				value=&quot;org.h2.Driver&quot; /&gt; #2
			&lt;property name=&quot;url&quot; value=&quot; #2
				[CA] jdbc:h2:mem:sbia_ch03;DB_CLOSE_DELAY=-1&quot; /&gt; #2
			&lt;property name=&quot;username&quot; value=&quot;sa&quot; /&gt; #2
			&lt;property name=&quot;password&quot; value=&quot;&quot; /&gt; #2
			&lt;property name=&quot;suppressClose&quot; value=&quot;true&quot; /&gt; #2
		&lt;/bean&gt; #2
		&lt;bean id=&quot;transactionManager&quot; class=&quot;org.springframework.jdbc.datasource.
			[CA] DataSourceTransactionManager&quot;&gt;
			&lt;property name=&quot;dataSource&quot; ref=&quot;dataSource&quot; /&gt;
		&lt;/bean&gt;
	&lt;/beans&gt;
	#1 Declares persistent job repository
	#2 Declares data source</pre></td></tr></table></div>

<p>The job-repository XML element in the batch namespace creates a persistent job repository (#1). To work properly, the persistent job repository needs a data source and a transaction manager. Note that, at #2, we use a data source implementation that holds a single JDBC connection and reuses it for each query. We did so because it’s convenient and good enough for a single-threaded application (like a batch process.) If you plan to use the data source in a concurrent application, then use a connection pool like Apache Commons DBCP or c3p0.</p>
<p>Now that we have the persistent job repository ready, let’s take a closer look at it.</p>
<h3>Accessing job metadata</h3>
<p>If you look at the job repository database, you see that the SQL script created nine tables. Figure 3 shows how you can use the Spring Batch Admin web application to view job executions. Spring Batch Admin accesses the job repository tables to provide this functionality.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/04/3.jpg"><img class="aligncenter size-medium wp-image-1146" title="3" src="http://www.javabeat.net/wp-content/uploads/2011/04/3-300x160.jpg" alt="" width="300" height="160" /></a></p>
<p><strong>What is Spring Batch Admin?</strong> Spring Batch Admin is an open source project from SpringSource that provides a web-based user interface for Spring Batch applications.</pre>
<h2>Summary</h2>
<p>Using a well-defined vocabulary, you can paint a clear picture of your batch applications. We’ve seen how the Spring Batch framework models these concepts, an important requirement to understand how to implement batch solutions. We focused on the framework’s infrastructure components: the job launcher and the job repository.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2011/04/the-spring-batch-infrastructure/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>How to perform indexing in MySQL?</title>
		<link>http://www.javabeat.net/2010/10/how-to-perform-indexing-in-mysql/</link>
		<comments>http://www.javabeat.net/2010/10/how-to-perform-indexing-in-mysql/#comments</comments>
		<pubDate>Thu, 28 Oct 2010 00:25:57 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[MYSQL]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=1617</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>MySQL Admin Cookbook MySQL is the most popular open-source database and is also known for its easy set up feature. However, proper configuration beyond the default settings is still a challenge, along with some other day-to-day maintenance tasks such as backup and restoring, performance tuning, and server monitoring. This book provides both step-by-step recipes and [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><H1><CENTER>MySQL Admin Cookbook</CENTER></H1><br />
<P>MySQL is the most popular open-source database and is also known for its easy set up<br />
feature. However, proper configuration beyond the default settings is still a challenge,<br />
along with some other day-to-day maintenance tasks such as backup and restoring,<br />
performance tuning, and server monitoring.</P><br />
<P>This book provides both step-by-step recipes and relevant background information on<br />
these topics and more. It covers everything from basic to advanced aspects of MySQL<br />
administration and configuration. All recipes are based on real-world experience and<br />
were derived from proven solutions used in an enterprise environment.</P><br />
<H1>What This Book Covers</H1><br />
<P>Chapter 1, <I>Replication</I>: In this chapter, you will see how to set up MySQL replication,<br />
useful for load balancing, online backups, and fail-over scenarios. Advanced replication<br />
scenarios using the blackhole engine and streaming slave deployment are discussed<br />
beyond the basic topics.</P><br />
<P>Chapter 2, <I>Indexing</I>: You will be shown how to create, drop, and modify indexes,<br />
perhaps the most important means of optimizing your MySQL servers&#8217; performance.<br />
Fulltext indexing, clustered and non-clustered indexes are compared and presented with<br />
their respective strengths and typical use cases. Moreover, you will learn how to identify<br />
duplicate indexes, which can hinder your servers&#8217; performance.</P><br />
<P>Chapter 3, <I>Tools</I>: This chapter will get you acquainted with the MySQL Administrator<br />
and Query Browser GUiTools as well as the MySQL command-line client and how to<br />
use it in concert with external scripts and tools. You will also see how to create custom<br />
diagrams for MySQL Administrator and share connection profiles between<br />
multiple computers.</P><br />
<P>Chapter 4, <I>Backing Up and Restoring MySQL Data</I>: In this chapter, we introduce the<br />
basic approaches to backing up your database and restoring data again. Advanced<br />
techniques like on-the-fly compression, point in time recovery, avoiding extended lock<br />
situations, backup in replication scenarios, and partial backup and restore<br />
are also covered.</P><br />
<P>Chapter 5, <I>Managing Data</I>: You will learn some tricks beyond the basic SQL<br />
commands, which enable you to delete data in a highly efficient manner and insert data<br />
based on existing database content, and how to import and export data to and<br />
from your database.</P><br />
<P>Chapter 6, <I>Monitoring and Analyzing a MySQL Installation</I>: We present approaches to<br />
monitoring table space usage, and how to use database metadata to your advantage.<br />
Typical performance bottlenecks and lock contention problems are discussed as well.</P><br />
<P>Chapter 7, <I>Configuring MySQL</I>: This chapter deals with MySQL configuration and<br />
how to best leverage available settings to their full potential. Table space management,<br />
pool sizing, and logging options are discussed along with platform-specific caveats and<br />
advanced installation scenarios, such as multiple instances on one server.</P><br />
<P>Chapter 8, <I>MySQL User Management</I>: Management of MySQL user accounts is<br />
discussed in detail throughout this chapter. Typical user roles with appropriate privileges<br />
and approaches to restricting access sensibly are proposed. You will also learn how to<br />
regain access to your database in case the administrative user credentials are lost.</P><br />
<P>Chapter 9, <I>Managing Schemas</I>: This chapter includes topics such as adding and<br />
removing columns to and from tables and choosing a suitable storage engine and<br />
character set for individual needs. Another recipe covers a technique to add a new<br />
primary key column to a table already filled with data. Ways to manage and automate<br />
database schema evolution, as part of a software life cycle are presented as well. And if<br />
you have always missed &#8220;ADD INDEX IF NOT EXISTS&#8221;, you will find a<br />
solution to this, too.</P><br />
<P>Appendix, <I>Good to Know</I>: In this final part of the book you can find several things that<br />
can turn out useful in everyday situations, but did not fit the step-by-step recipe format<br />
naturally. Topics range from choosing character sets to getting the most out of 32 bit<br />
address space limitations.</P><br />
<H1><CENTER>Indexing</CENTER></H1><br />
<P>In this chapter, we will cover:</P><br />
<UL><br />
	<LI>Adding indexes to tables</LI><br />
	<LI>Adding a fulltext index</LI><br />
	<LI>Creating a normalized text search column</LI><br />
	<LI>Removing indexes from tables</LI><br />
	<LI>Estimating InnoDB index space requirements</LI><br />
	<LI>Using prefix primary keys</LI><br />
	<LI>Choosing InnoDB primary key columns</LI><br />
	<LI>Speeding up searches for (sub)domains</LI><br />
	<LI>Finding duplicate indexes</LI><br />
</UL><br />
<H1>Introduction</H1><br />
<P>One of the most important features of relational database management systems—MySQL<br />
being no exception—is the use of indexes to allow rapid and efficient access to the enormous<br />
amounts of data they keep safe for us. In this chapter, we will provide some useful recipes for<br />
you to get the most out of your databases.</P><br />
<H3>Infinite storage, infinite expectations</H3><br />
<P>We have got accustomed to nearly infinite storage space at our disposal—storing everything<br />
from music to movies to high resolution medical imagery, detailed geographical information,<br />
or just plain old business data. While we take it for granted that we hardly ever run out of<br />
space, we also expect to be able to locate and retrieve every bit of information we save in an<br />
instant. There are examples everywhere in our lives—business and personal:</P><br />
<UL><br />
<LI>Your pocket music player&#8217;s library can easily contain tens of thousands of songs and<br />
yet can be browsed effortlessly by artist name or album title, or show you last week&#8217;s<br />
top 10 rock songs.</LI><br />
<LI>Search engines provide thousands of results in milliseconds for any arbitrary search<br />
term or combination.</LI><br />
<LI>A line of business application can render your sales numbers charted and displayed<br />
on a map, grouped by sales district in real-time.</LI><br />
</UL><br />
<P>These are a few simple examples, yet for each of them huge amounts of data must be<br />
combed to quickly provide just the right subset to satisfy each request. Even with the<br />
immense speed of modern hardware, this is not a trivial task to do and requires some<br />
clever techniques.</P><br />
<H3>Speed by redundancy</H3><br />
<P>Indexes are based on the principle that searching in sorted data sets is way faster than<br />
searching in unsorted collections of records. So when MySQL is told to create an index on one<br />
or more columns, it copies these columns&#8217; contents and stores them in a sorted manner. The<br />
remaining columns are replaced by a reference to the original table with the unsorted data.</P><br />
<P>This combines two benefits—providing fast retrieval while maintaining reasonably efficient<br />
storage requirements. So, without wasting too much space this approach enables you to<br />
create several of those indexes (or indices, both are correct) at a relatively low cost.</P><br />
<P>However, there is a drawback to this as well: while reading data, indexes allow for immense<br />
speeds, especially in large databases; however, they do slow down writing operations. In the<br />
course of <B>INSERT</B>s, <B>UPDATE</B>s, and <B>DELETE</B>s, all indexes need to be updated in addition to<br />
the data table itself. This can place significant additional load on the server, slowing down<br />
all operations.</P><br />
<P>For this reason, keeping the number of indexes as low as possible is paramount, especially for<br />
the largest tables where they are most important. In this chapter, you&#8217;ll find some recipes that<br />
will help you to decide how to define indexes and show you some pitfalls to avoid.</P><br />
<H3>Storage engine differences</H3><br />
<P>We will not go into much detail here about the differences between the MyISAM and the<br />
InnoDB storage engines offered by MySQL. However, regarding indexes there are some<br />
important differences to know between MySQL&#8217;s two most important storage engines. They<br />
infl uence some decisions you will have to make.</P><br />
<H3>MyISAM</H3><br />
<P>In the figure below you can see a simplified schema of how indexes work with the MyISAM<br />
storage engine. Their most important property can be summed up as &#8220;all indexes are created<br />
equal&#8221;. This means that there is no technical difference between the primary and<br />
secondary keys.</P><br />
<P><CENTER><IMG SRC="images/2010/10/MySQLAdmin/1.jpg"/></CENTER></P><br />
<P>The diagram shows a single (theoretical) data table called <B>books</B>. It has three columns<br />
named <B>isbn</B>, <B>title</B>, and <B>author</B>. This is a very simple schema, but it is sufficient for explanation<br />
purposes. The exact definition can be found in the <I>Adding indexes</I> to tables recipe in this<br />
chapter. For now, it is not important.</P><br />
<P>MyISAM tables store information in the order it is inserted. In the example, there are three<br />
records representing a single book each. The ISBN number is declared as the <I>primary key</I> for<br />
this table. As you can see, the records are not ordered in the table itself—the ISBN numbers<br />
are out of what would be their lexical order. Let&#8217;s assume they have been inserted by someone<br />
in this order.</P><br />
<P>Now, have a look at the first index—the <B>PRIMARY KEY</B>. The index is sorted by the <B>isbn</B> column.<br />
Associated with each index entry is a row pointer that leads to the actual data record in the<br />
<B>books</B> table. When looking up a specific ISBN number in the primary key index, the database<br />
server follows the row pointer to retrieve the remaining data fields. The same holds true for<br />
the other two indexes <I>IDX_TITLE</I> and <I>IDX_AUTHOR</I>, which are sorted by the respective fields<br />
and also contain a row pointer each.</P><br />
<P>Looking up a book&#8217;s details by any one of the three possible search criteria is a two-part<br />
operation: first, find the index record, and then follow the row pointer to get the rest of the data.</P><br />
<P>With this technique you can insert data very quickly because the actual data records are<br />
simply appended to the table. Only the relatively small index records need to be kept in order,<br />
meaning much less data has to be shuffled around on the disk.</P><br />
<P>There are drawbacks to this approach as well. Even in cases where you only ever want to look<br />
up data by a single search column, there will be two accesses to the storage subsystem—one<br />
for the index, another for the data.</P><br />
<H3>InnoDB</H3><br />
<P>However, InnoDB is different. Its index system is a little more complicated, but it has<br />
some advantages:</P><br />
<P><CENTER><IMG SRC="images/2010/10/MySQLAdmin/2.jpg"/></CENTER></P><br />
<H3>Primary (clustered) indexes</H3><br />
<P>Whereas in MyISAM all indexes are structured identically, InnoDB makes a distinction between<br />
the primary key and additional secondary ones.</P><br />
<P>The primary index in InnoDB is a <I>clustered index</I>. This means that one or more columns<br />
of each record make up a unique key that identifies this exact record. In contrast to other<br />
indexes, a clustered index&#8217;s main property is that it itself is part of the data instead of being<br />
stored in a different location. Both data and index are clustered together.</P><br />
<P>An index is only serving its purpose if it is stored in a sorted fashion. As a result, whenever you<br />
insert data or modify the key column(s), it needs to be put in the correct location according to<br />
the sort order. For a clustered index, the whole record with all its data has to be relocated.</P><br />
<P>That is why bulk data insertion into InnoDB tables is best performed in correct primary key<br />
order to minimize the amount of disk I/O needed to keep the records in index order. Moreover,<br />
the clustered index should be defined so that it is hardly ever changed for existing rows, as<br />
that too would mean relocating full records to different sectors on the disk.</P><br />
<P>Of course, there are significant advantages to this approach. One of the most important<br />
aspects of a clustered key is that it actually <I>is a part</I> of the data. This means that when<br />
accessing data through a primary key lookup, there is no need for a two-part operation as<br />
with MyISAM indexes. The location of the index is at the same time the location of the data<br />
itself—there is no need for following a row pointer to get the rest of the column data, saving<br />
an expensive disk access.</P><br />
<P>Looking up a book by ISBN in our example table simply means locating it quickly, as it is<br />
stored in order, and then reading the complete record in one go.</P><br />
<H3>Secondary indexes</H3><br />
<P>Consider if you were to search for a book by title to find out the ISBN number. An index on<br />
the name column is required to prevent the database from scanning through the whole<br />
(ISBN-sorted) table. In contrast to MyISAM, the InnoDB storage engine creates secondary<br />
indexes differently.</P><br />
<P>Instead of record pointers, it uses a copy of the whole primary key for each record to establish<br />
the connection to the actual data contents.</P><br />
<P>In the previous figure, have a look at the <I>IDX_TITLE</I> index. Instead of a simple pointer to the<br />
corresponding record in the data table, you can see the ISBN number duplicated as well. This<br />
is because the <B>isbn</B> column is the primary key of the <B>books</B> table. The same goes for the other<br />
indexes in the figure—they all contain the book ISBN number as well. You do not need to (and<br />
should not) specify this yourself when creating and indexing on InnoDB tables, it all happens<br />
automatically under the covers.</P><br />
<P>Lookups by secondary index are similar to MyISAM index lookups. In the first step, the index<br />
record that matches your search term is located. Then secondly, the remaining data is<br />
retrieved from the data table by means of another access—this time by primary key.</P><br />
<P>As you might have figured, the second access is optional, depending on what information you<br />
request in your query. Consider a query looking for the ISBN numbers of all known issues of<br />
Moby Dick:</P><br />
<P><PRE><CODE><br />
	SELECT isbn FROM books WHERE title LIKE &#8216;Moby Dick%&#8217;;<br />
</CODE></PRE></P><br />
<P>Issued against a presumably large library database, it will most certainly result in an index<br />
lookup on the <I>IDX_TITLE</I> key. Once the index records are found, there is no need for another<br />
lookup to the actual data pages on disk because the ISBN number is already present in the<br />
index. Even though you cannot see the column in the index definition, MySQL will skip the<br />
second seek saving valuable I/O operations.</P><br />
<P>But there is a drawback to this as well. MyISAM&#8217;s row pointers are comparatively small. The<br />
primary key of an InnoDB table can be much bigger—the longer the key, the more the data<br />
that is stored redundantly.</P><br />
<P>In the end, it can often be quite difficult to decide on the optimal balance between increased<br />
space requirements and maintenance costs on index updates. But do not worry; we are going<br />
to provide help on that in this chapter as well.</P><br />
<H3>General requirements for the recipes in this chapter</H3><br />
All the recipes in this chapter revolve around changing the database schema. In order to add<br />
indexes or remove them, you will need access to a user account that has an effective <B>INDEX</B><br />
privilege or the <B>ALTER</B> privilege on the tables you are going to modify.<br />
While the <B>INDEX</B> privilege allows for use of the <B>CREATE INDEX</B> command, <B>ALTER</B> is required<br />
for the <B>ALTER TABLE ADD INDEX</B> syntax. The MySQL manual states that the former is mapped<br />
to the latter automatically. However, an important difference exists: <B>CREATE INDEX</B> can only<br />
be used to add a single index at a time, while <B>ALTER TABLE ADD INDEX</B> can be used to add<br />
more than one index to a table in a single go.</P><br />
<P>This is especially relevant for InnoDB tables because up to MySQL version 5.1 every change<br />
to the definition of a table internally performs a copy of the whole table. While for small<br />
databases this might not be of any concern, it quickly becomes infeasible for large tables due<br />
to the high load copying may put on the server. With more recent versions this might have<br />
changed, but make sure to consult your version&#8217;s manual.</P><br />
<P>In the recipes throughout this chapter, we will consistently use the <B>ALTER TABLE ADD INDEX</B><br />
syntax to modify tables, assuming you have the appropriate privileges. If you do not, you will<br />
have to rewrite the statements to use the <B>CREA TE INDEX</B> syntax.</P></p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2010/10/how-to-perform-indexing-in-mysql/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating your MySQL Database</title>
		<link>http://www.javabeat.net/2009/09/creating-your-mysql-database/</link>
		<comments>http://www.javabeat.net/2009/09/creating-your-mysql-database/#comments</comments>
		<pubDate>Wed, 30 Sep 2009 14:24:36 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[MYSQL]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=2022</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Creating your MySQL Database MySQL, launched in 1995, has become the most popular open source database system. The popularity of MySQL and phpMyAdmin has allowed many non-IT specialists to build dynamic websites with a MySQL backend. This book is a short but complete guide showing beginners how to design good data structures for MySQL. It [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h1><center>Creating your MySQL Database</center></h1>
<p>MySQL, launched in 1995, has become the most popular open source database system. The<br />
popularity of MySQL and phpMyAdmin has allowed many non-IT specialists to build dynamic<br />
websites with a MySQL backend. This book is a short but complete guide showing beginners how<br />
to design good data structures for MySQL. It teaches how to plan the data structure and how to<br />
implement it physically using MySQL&#8217;s model.</p>
<h1><center>What This Book Covers</center></h1>
<p><i>Chapter 1</i> introduces the concept of MySQL, and discusses MySQL&#8217;s growing popularity and its<br />
impact as a powerful tool. This chapter gives us a brief overview of the relational models and<br />
Codd&#8217;s rules, which are required for designing purposes. A brief introduction to our case study —<br />
&#8220;car dealer&#8221; is provided at the end.</p>
<p><i>Chapter 2</i> shows how to deal with the raw data information that comes from the users or other<br />
sources, and the techniques that can help us build a comprehensive data collection. Also, this<br />
chapter covers the exact limits of the analyzed system, how one should gather documents, and<br />
interview activities for our case study.</p>
<p><i>Chapter 3</i> emphasises on transforming the data elements gathered in the collection process into a<br />
cohesive set of column names. The concept of data naming is also discussed in this chapter.</p>
<p>Chapter 4 provides the technique of grouping column names into tables. Rules for table layout, the<br />
concepts such as primary key, unique key, data redundancy, and data dependency are covered in<br />
this chapter.</p>
<p><i>Chapter 5</i> presents various techniques for improving our data structure in terms of security,<br />
performance, and documentation. The final data structure for the car dealer&#8217;s case study is<br />
provided at the end.</p>
<p><i>Chapter 6</i> covers a supplemental case study about an airline system. This case study involves<br />
various steps such as gathering documents, preparing preliminary list of data elements, preparing a<br />
list of tables, sample values, and queries for the airline system..</p>
<h1><center>Data Naming</center></h1>
<p>In this chapter, we focus on transforming the data elements gathered in the collection<br />
process into a cohesive set of column names. Although this chapter has sections for<br />
the various steps we should accomplish for efficient data naming, there is no specific<br />
order in which to apply those steps. In fact, the whole process is broken down into<br />
steps to shed some light on each one in turn, but the actual naming process applies<br />
all those steps at the same time. Moreover, the division between the naming and<br />
grouping processes is somewhat artificial – you&#8217;ll see that some decisions about<br />
naming infl uence the grouping phase, which is the subject of the next chapter.</p>
<h1>Data Cleaning</h1>
<p>Having gathered information elements from various sources, some cleaning work is<br />
appropriate to improve the significance of these elements. The way each interviewee<br />
named elements might be inconsistent; moreover, the significance of a term can vary<br />
from person to person. Thus, a synonym detection process is in order.</p>
<p>Since we took note of sample values, now it is time to cross-reference our list of<br />
elements with those sample values. Here is a practical example, using the car&#8217;s<br />
id number.</p>
<p>When the decision is made to order a car – a Mitsou 2007 – the office clerk opens<br />
a new file and assigns a sequential number dubbed car_id number to the file, for<br />
instance, 725. At this point, no confirmation has been received from any car supplier,<br />
so the clerk does not know the future car&#8217;s serial number – a unique number stamped<br />
on the engine and other critical parts of the vehicle.</p>
<p>This car&#8217;s id number is referred to as the car_number by the office clerk. The store<br />
assistants who register car movements use the name stock_number. But using this<br />
car number or the stock number is not meaningful for financing and insurance<br />
purposes; the car&#8217;s serial number is used instead for that purpose.</p>
<p>At this point, a consensus must be reached by convincing users about the importance<br />
of standard terms. It must become clear to everyone that the term car_number is not<br />
precise enough to be used, so it will be replaced by car_internal_number in the<br />
data elements list, probably also in any user interface (UI) or report.</p>
<p>It can be argued that car_internal_number should be replaced by something more<br />
appropriate; the important point here is we merged two synonyms: car_number and<br />
stock_number, and established the difference between two elements that looked<br />
similar but were not, eliminating a source of confusion.</p>
<p>Therefore we end up with the following elements:</p>
<ul>
<li>Car_serial_number</li>
<li>Car_internal_number (former car id number and stock number)</li>
</ul>
<p>Eventually, when dealing with data grouping, another decision will have to be taken:<br />
to which number, serial or internal, do we associate the car&#8217;s physical key number.</p>
<h1>Subdividing Data Elements</h1>
<p>In this section, we try to find out if some elements should be broken into more simple<br />
ones. The reason for doing so is that, if an element is composed of many parts,<br />
applications will have to break it for sorting and selection purposes. Thus it&#8217;s better<br />
to break the elements right now at the source. Recomposing it will be easier at the<br />
application level.</p>
<p>Breaking the elements provides more clarity at the UI level. Therefore, at this<br />
level we will avoid (as much as possible) the well-known last-name/first-name<br />
inversion problem.</p>
<p>As an example for this problem, let&#8217;s take the buyer&#8217;s name. During the interview, we<br />
noticed that the name is expressed in various ways on the forms:</p>
<table border="1" aligh="center">
<tr>
<th>Form</th>
<th>How the name is expressed</th>
</tr>
<tr>
<td>Delivery certificate</td>
<td>Mr Joe Smith</td>
</tr>
<tr>
<td>Sales contract</td>
<td>Smith, Joe</td>
</tr>
</table>
<p>We notice that</p>
<ul>
<li>There is a salutation element, Mr</li>
<li>The element name is too imprecise; we really have a first name and a last name</li>
<li>On the sales contract, the comma after our last name should really be<br />
excluded from the element, as it&#8217;s only a formatting character</li>
</ul>
<p>As a result, we determine that we should sub-divide the name into the following<br />
elements:</p>
<ul>
<li>Salutation</li>
<li>First name</li>
<li>Last name</li>
</ul>
<p>Sometimes it&#8217;s useful to sub-divide an element, sometimes it&#8217;s not. Let&#8217;s consider<br />
the date elements. We could sub-divide each one into year, month, and day (three<br />
integers) but by doing so, we would lose the date calculation possibilities that<br />
MySQL offers. Among those are, finding the week day from a date, or determining<br />
the date that falls thirty days after a certain date. So for the date (and time), a single<br />
column can handle it all, although at the UI level, separate entry fields should be<br />
displayed for year, month, and day. This is to avoid any possibility of mix-up and<br />
also because we cannot expect users to know about what MySQL accepts as a valid<br />
date. There is a certain latitude in the range of valid values but we can take it for<br />
granted that users have unlimited creativity, regarding how to enter invalid values.<br />
If a single field is present on the UI, clear directions should be provided to help<br />
with filling this field correctly.</p>
<h1>Data Elements Containing Formatting Characters</h1>
<p>The last case we&#8217;ll examine is the phone number. In many parts of the world, the<br />
phone number follows a specific pattern and also uses formatting characters for<br />
legibility. In North America, we have a regional code, an exchange number, and<br />
phone number, for example, 418-111-2222; an extension could possibly be appended<br />
to the phone number. However, in practice only the regional code and extension<br />
are separated from the rest into data elements of their own. Moreover, people often<br />
enter formatting characters like (418) 111-2222 and expect those to be output back.<br />
So, a standard output format must be chosen, and then the correct number of<br />
sub-elements will have to be set into the model to be able to recreate the<br />
expected output.</p>
<h1>Data that are Results</h1>
<p>Even though it might seem natural to have a distinct element for the total_price of<br />
the car, in practice this is not justified. The reason is that the total price is a computed<br />
result. Having the total price printed on a sales contract constitutes an output. Thus,<br />
we eliminate this information in the list of column names. For the same reason, we<br />
could omit the tax column because it can be computed.</p>
<p>By removing the total price column, we could encounter a pitfall. We have to be sure<br />
that we can reconstruct this total price from other sub-total elements, now and in the<br />
future. This might not be possible for a number of reasons:</p>
<ul>
<li>The total price includes an amount located in another table, and this table<br />
will change over time (for example, the tax rate). To avoid this problem, see<br />
the recommendations in the <i>Scalability over</i> Time section in Chapter 4.</li>
<li>This total price contains an arbitrary value, due to some exceptional cases,<br />
for example, where there is a special sale, and the rebate was not planned<br />
in the system, or when the lucky buyer is the brother-in-law of the general<br />
manager! In this case, a decision can be made: adding a new column<br />
other_rebate.</li>
</ul>
<h1>Data as a Column&#8217;s or Table&#8217;s Name</h1>
<p>Now is the time to uncover what is perhaps the least known of the data naming<br />
problems: data hidden in a column&#8217;s or even a table&#8217;s name.</p>
<p>We had one example of this in Chapter 1. Remember the qty_2006_1 column name.<br />
Although this is a commonly seen mistake, it&#8217;s a mistake nonetheless. We clearly<br />
have two ideas here, the quantity and the date. Of course, to be able to use just two<br />
columns, some work will have to be done regarding the keys – this is covered in<br />
Chapter 4. For now, we should just use elements like quantity and date in our<br />
elements list, avoiding representing data in a column&#8217;s name.</p>
<p>To find those problematic cases in our model, a possible method is to look for<br />
numbers. Column names like address1, address2 or phone1, phone2 should<br />
look suspicious.</p>
<p>Now, have a look in Chapter 2 at the data elements we got from our store assistant.<br />
Can you find a case of data being hidden in a column name?</p>
<p>If you have done this exercise, you might have found many past participles hidden<br />
into the column names, like <i>ordered, arrived</i>, and <i>washed</i>. These describe the events<br />
that happen to a car. We could try to anticipate all possible events but it might prove<br />
impossible. Who knows when a new column car_provided_with_big_ribbon will<br />
be needed? Such events, if treated as distinct column names, must be addressed by</p>
<ul>
<li>A change in the data structure</li>
<li>A change in the code (UI and reports)</li>
</ul>
<p>To stay fl exible and avoid the wide-table syndrome, we need two tables: car_event<br />
and event.</p>
<p><center><img src="images/2009/09/mySQL/1.GIF"></center></p>
<p>Here are the structure and sample values for those tables:</p>
<p>
<pre><code>
	CREATE TABLE `event` (
		`code` int(11) NOT NULL,
		`description` char(40) NOT NULL,
		PRIMARY KEY ('code')
	) ENGINE=MyISAM DEFAULT CHARSET=latin1;

	INSERT INTO `event` VALUES (1, 'washed');

		The usage of backticks here ('event'), although not standard
		SQL, is a MySQL extension used to enclose and protect
		identifiers. In this specific case, it could help us with
		MySQL 5.1 in which the event keyword is scheduled to
		become part of the language for some another purpose
		(CREATE EVENT). At the time of writing, beta version
		MySQL 5.1.11 accepts CREATE TABLE event, but it might
		not always be true.
</code></pre>
</p>
<p>The following image shows sample values entered into the event table from within<br />
the <b>Insert</b> sub-page of phpMyAdmin:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p><center><img src="images/2009/09/mySQL/2.GIF"></center></p>
<p>
<pre><code>
	CREATE TABLE `car_event` (
		`internal_number` int(11) NOT NULL,
		`moment` datetime NOT NULL,
		`event_code` int(11) NOT NULL,
		PRIMARY KEY ('internal_number')
	) ENGINE=MyISAM DEFAULT CHARSET=latin1;

	INSERT INTO `car_event` VALUES (412, '2006-05-20 09:58:38', 1);
</code></pre>
</p>
<p>Again, sample values are entered via phpMyAdmin:</p>
<p><center><img src="images/2009/09/mySQL/3.GIF"></center></p>
<p>Data can also hide in a table name. Let&#8217;s consider the car and truck tables. They<br />
should probably be merged into a vehicle table, since the vehicle&#8217;s category – truck,<br />
car, and other values like minivan is really an attribute of a particular vehicle.<br />
We could also find another case for this table name problem: a table named<br />
vehicle_1996.</p>
<h1>Planning for Changes</h1>
<p>When designing a data structure, we have to think about how to manage its growth<br />
and the possible implications of the chosen technique.</p>
<p>Let&#8217;s say an unplanned car characteristic – the weight – has to be supported. The<br />
normal way of solving this is to find the proper table and add a column. Indeed, this<br />
is the best solution; however, someone has to alter the table&#8217;s structure, and probably<br />
the UI too.</p>
<p>The <b>free fields technique</b>, also called second-level data or <b>EAV</b> (Entity-Attribute-<br />
Value) technique is sometimes used in this case. To summarize this technique, we<br />
use a column whose value is a column name by itself.</p>
<p>
<pre><code>
	Even if this technique is shown here, I do not recommend
	using it, for the reasons explained in the <i>Pitfalls of the Free
	Fields Technique</i> section below.
</code></pre>
</p>
<p>The difference between this technique and our car_event table is that, for<br />
car_event, the various attributes can all be related to a common subject, which is<br />
the event. On the contrary, free fields can store any kind of dissimilar data. This<br />
might also be a way to store data specific to a single instance or row of a table.</p>
<p>In the following example, we use the car_free_field table to store unplanned<br />
information about the car whose internal_number is 412. The weight and special<br />
paint had not been planned, so the UI gave the user the chance to specify which<br />
information they want to keep, and the corresponding value. We see here a<br />
screenshot from phpMyAdmin but most probably, another UI would be presented<br />
to the user – for example the salesperson who might not be trained to play at the<br />
database level.</p>
<p>
<pre><code>
	CREATE TABLE `car_free_field` (
		`internal_number` int(11) NOT NULL,
		`free_name` varchar(30) NOT NULL,
		`free_value` varchar(30) NOT NULL,
		PRIMARY KEY ('internal_number','free_name')
	) ENGINE=MyISAM DEFAULT CHARSET=latin1;

	INSERT INTO `car_free_field` VALUES (412, 'weight', '2000');
	INSERT INTO `car_free_field` VALUES (412, 'special paint needed',
	'gold');
</code></pre>
</p>
<p><center><img src="images/2009/09/mySQL/4.GIF"></center></p>
<h2>Pitfalls of the Free Fields Technique</h2>
<p>Even if it&#8217;s tempting to use this kind of table for added fl exibility and to avoid user<br />
interface maintenance, there are a number of reasons why we should avoid using it.</p>
<ul>
<li>It becomes impossible to link this &#8220;column&#8221; (for example the <b>special paint<br />
needed</b>) to a lookup table containing the possible colors, with a foreign<br />
key constraint.</li>
<li>The free_value field itself must be defined with a generic field type like<br />
VARCHAR whose size must be wide enough to accommodate all values for all<br />
possible corresponding free_name values.</li>
<li>It prevents easy validation (for a weight, we need a numeric value).</li>
<li>Coding the SQL queries on these free fields becomes more complex – i.e.<br />
SELECT internal_number from car_free_field where<br />
free_name = &#8216;weight&#8217; and free_value > 2000.</li>
</ul>
<h2>Naming Recommendations</h2>
<p>Here we touch a subject that can become sensitive. Establishing a naming convention<br />
is not easily done, because it can interfere with the psychology of the designers.</p>
<h2>Designer&#8217;s Creativity</h2>
<p>Programmers and designers usually think of themselves as imaginative, creative<br />
people; UI design and data model are the areas in which they want to express<br />
those qualities. Since naming is writing, they want to put a personal stamp to the<br />
column and table names. This is why working as a team for data structure design<br />
necessitates a good dose of humility and achieves good results only if everyone is a<br />
good team player.</p>
<p>Also, when looking at the work of others in this area, there is a great temptation to<br />
<i>improve</i> the data elements names. Some discipline in the standardization has to be<br />
applied and all the team members have to collaborate.</p>
<h2>Abbreviations</h2>
<p>Probably because older database systems had severe restrictions about the<br />
representation of variables and data elements in general, the practice of abbreviating<br />
has been taught for many years and is followed by many data structure designers<br />
and programmers. I used programming languages that accepted only two characters<br />
for variable names – we had to extensively comment the correspondence between<br />
those cropped variables and their meaning.</p>
<p>Nowadays, I see no valid reasons for systematically abbreviating all column and<br />
table names; after all, who will understand the meaning of your T1 table or your<br />
B7 field?</p>
<h3>Clarity versus Length: an Art</h3>
<p>A consistent style of abbreviations should be used. In general, only the most<br />
meaningful words of a sentence should be put into a name, dropping prepositions,<br />
and other small words. As an example, let&#8217;s take the postal code. We could express<br />
this element with different column names:</p>
<ul>
<li>the_postal_code</li>
<li>pstl_code</li>
<li>pstlcd</li>
<li>postal_code</li>
</ul>
<p>I recommend the last one for its simplicity.</p>
<h3>Suffixing</h3>
<p>Carefully chosen suffixes can add clarity to column names. As an example,<br />
for the <i>date of first payment</i> element, I would suggest first_payment_date. In fact,<br />
the last word of a column name is often used to describe the type of content – like<br />
customer_no, color_code, interest_amount.</p>
<h2>The Plural Form</h2>
<p>Another point of controversy for table names: should we use the plural form cars<br />
table? It can be argued that the answer is yes because this table contains many cars<br />
– in other words, it is a set. Nonetheless, I tend not to use the plural form for the<br />
simple reason that it adds nothing in terms of information. I know that a table is a<br />
set, so using the plural form would be redundant. It can be said also that each row<br />
describes one car.</p>
<p>If we consider the subject on the angle of queries, we can draw different<br />
conclusions depending on the query. A query referring to the car table –<br />
select car.color_code from car where car.id = 34 is more elegant if the<br />
plural form is not used, because the main idea here is that we retrieve one car<br />
whose id equals 34. Some other queries might make more sense with a plural, like<br />
select count(*) from cars.</p>
<p>As a conclusion for this section, the debate is not over, but the most important point<br />
is to choose a form and be consistent throughout the whole system.</p>
<h2>Naming Consistency</h2>
<p>We should ensure that a data element that is present in more than one table is<br />
represented everywhere by the same column name. In MySQL, a column name does<br />
not exist by itself; it is always inside a table. This is why, unfortunately, we cannot<br />
pick up consistent column names from, say, a pool of standardized column names<br />
and associate it with the tables. Instead, during each table&#8217;s creation we indicate<br />
the exact column names we want and their attributes. So, let&#8217;s avoid using different<br />
names – internal_number and internal_num when they refer to the same reality.</p>
<p>An exception for this: if the column&#8217;s name refers to a key in another table – the<br />
state column – and we have more than one column referring to it like<br />
state_of_birth, `state_of_residence`.</p>
<h2>MySQL&#8217;s Possibilities versus Portability</h2>
<p>MySQL permits the use of many more characters for identifiers – database, table,<br />
and column names than its competitors. The blank space is accepted as are accented<br />
characters. The simple trade-off is that we need to enclose such special names<br />
with back quotes like &#8216;state of residence&#8217;. This procures a great liberty in the<br />
expression of data elements, especially for non-English designers, but introduces a<br />
state of non-portability because those identifiers are not accepted in standard SQL.<br />
Even some SQL implementations only accept uppercase characters for identifiers.</p>
<p>I recommend being very prudent before deciding to include such characters.<br />
Even when staying faithful to MySQL, there has been a portability issue between<br />
versions earlier than 4.1 when upgrading to 4.1. In 4.1.x, MySQL started to represent<br />
identifiers internally in UTF-8 code, so a renaming operation had to be done to<br />
ensure that no accented characters in the database, table, column and constraint<br />
names were present before the upgrade. This tedious operation is not very practical<br />
in a 24/7 system availability context.</p>
<h2>Table Name into a Column Name</h2>
<p>Another style I often see: one would systematically add the table name as a prefix<br />
to every column name. Thus the car table would be comprised of the columns:<br />
car_id_number, car_serial_number. I think this is redundant and it shows its<br />
inelegance when examining the queries we build:</p>
<p>
<pre><code>
	select car_id_number from car
</code></pre>
</p>
<p>is not too bad, but when joining tables we get a query such as</p>
<p>
<pre><code>
	select car.car_id_number,
	buyer.buyer_name
	from car, buyer
</code></pre>
</p>
<p>Since at the application level, the majority of queries we code are multi-tables like<br />
the one used above, the clumsiness of using a table name even abbreviated as part of<br />
column names becomes readily apparent. Of course, the same exception we saw in<br />
the <i>Naming Consistency</i> section applies: a column – foreign key – referring to a lookup<br />
table normally includes this table&#8217;s name as part of the column&#8217;s name. For example,<br />
in the car_event table, we have event_code which refers to the code column in<br />
table event.</p>
<h1>Summary</h1>
<p>To get a clear and understandable data structure, proper data elements naming is<br />
important. We examined many techniques to apply in order to build consistent table<br />
and column names.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2009/09/creating-your-mysql-database/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to use datasource in Hibernate application?</title>
		<link>http://www.javabeat.net/2008/07/how-to-use-datasource-in-hibernate-application/</link>
		<comments>http://www.javabeat.net/2008/07/how-to-use-datasource-in-hibernate-application/#comments</comments>
		<pubDate>Wed, 23 Jul 2008 10:51:25 +0000</pubDate>
		<dc:creator>JavaBeat</dc:creator>
				<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[JBoss]]></category>
		<category><![CDATA[MYSQL]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=180</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>This article explains how to configure datasource in the JBoss application server and how to use the same datasource in the hibernate configuration file.Before looking into the hibernate configuration, we will start with creating datasource inside JBoss application server. Create MySql datasource in JBoss To create datasource for the MySql database inside the JBoss application [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>This article explains how to configure <b><i>datasource</i></b> in the <b><i>JBoss</i></b> application server and how to use the same datasource in the hibernate configuration file.Before looking into the hibernate configuration, we will start with creating datasource inside <b><i>JBoss application server</i></b>.</p>
<h1>Create MySql datasource in JBoss</h1>
<p>To create datasource for the <b><i>MySql</i></b> database inside the JBoss application server, you have to<br />
first create <b><i>mysql-ds.xml</i></b> file with the following entries:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;datasources&gt;
  &lt;local-tx-datasource&gt;
    &lt;jndi-name&gt;SampleDS&lt;/jndi-name&gt;
    &lt;connection-url&gt;jdbc:mysql://localhost:3306/SampleDB&lt;/connection-url&gt;
    &lt;driver-class&gt;com.mysql.jdbc.Driver&lt;/driver-class&gt;
     &lt;min-pool-size&gt;1&gt;/min-pool-size&gt;
      &lt;max-pool-size&gt;20&gt;/max-pool-size&gt;
      &lt;user-name&gt;root&gt;/user-name&lt;
      &lt;password&gt;root&lt;/password&gt;
     &lt;metadata&gt;
       &lt;type-mapping&amp;g;mySQL&lt;/type-mapping&gt;
    &lt;/metadata&gt;
  &lt;/local-tx-datasource&gt;
&lt;/datasource&gt;</pre></td></tr></table></div>

<p>Put <b><i>mysql-ds.xml</i></b> file under <b><i>jbossserverdefaultdeploy</i></b>. <b><i>JBoss</i></b> application server will<br />
automatically take this file and create the datasource for you. You need not restart the server. Creating datasource<br />
is completed. Next we will look into the hibernate configuration file for maping this datasource.
</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<h1>Use datasource in Hibernate configuration</h1>
<p>
	To map <b><i>datasource</i></b> in the <b><i>hibernate</i></b> configuration file is simple task and need not<br />
	specify anything other than the datasource name. You have to include the following two lines of code<br />
	in the configuration file to tell the <b><i>hibernate container</i></b> to use datasouce for retrieving the new<br />
	connection from the databse.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;property name=&quot;dialect&quot;&gt;
	org.hibernate.dialect.MySQLDialect
&lt;/property&gt;
&lt;property name=&quot;connection.datasource&quot;&gt;SampleDS&lt;/property&gt;</pre></td></tr></table></div>

<p>Now we have configured datasource and mapped to the hibernate configuration file. All the connection<br />
from the hibernate will be retrieved from datasource instead of directly from the database. This approach is<br />
most widely used for the application development.
</p>
<h4>mysql-ds.xml</h4>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&nbsp;
&lt;!-- $Id: mysql-ds.xml 63175 2007-05-21 16:26:06Z rrajesh $ --&gt;
&lt;!--  Datasource config for MySQL using 3.0.9 available from:
http://www.mysql.com/downloads/api-jdbc-stable.html
--&gt;
&nbsp;
&lt;datasources&gt;
  &lt;local-tx-datasource&gt;
    &lt;jndi-name&gt;SampleDS&lt;/jndi-name&gt;
    &lt;connection-url&gt;jdbc:mysql://localhost:3306/SimpleDB&lt;/connection-url&gt;
    &lt;driver-class&gt;com.mysql.jdbc.Driver&lt;/driver-class&gt;
     &lt;min-pool-size&gt;1&lt;/min-pool-size&gt;
      &lt;max-pool-size&gt;20&lt;/max-pool-size&gt;
      &lt;user-name&gt;root&lt;/user-name&gt;
    &lt;password&gt;root&lt;/password&gt;--&gt;
    &lt;metadata&gt;
       &lt;type-mapping&gt;mySQL&lt;/type-mapping&gt;
    &lt;/metadata&gt;
  &lt;/local-tx-datasource&gt;
&lt;/datasource&gt;</pre></td></tr></table></div>

<h4>hibernate.cfg.xml</h4>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;?xml version='1.0' encoding='UTF-8'?&gt;
&lt;!DOCTYPE hibernate-configuration PUBLIC
          &quot;-//Hibernate/Hibernate Configuration DTD 3.0//EN&quot;
          &quot;http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd&quot;&gt;
&nbsp;
&lt;hibernate-configuration&gt;
    &lt;session-factory&gt;
            &lt;property name=&quot;dialect&quot;&gt;
            org.hibernate.dialect.MySQLDialect
        &lt;/property&gt;
        &lt;property name=&quot;connection.datasource&quot;&gt;SampleDS&lt;/property&gt;
    &lt;/session-factory&gt;
&nbsp;
&lt;/hibernate-configuration&gt;</pre></td></tr></table></div>

<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2008/07/how-to-use-datasource-in-hibernate-application/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
