<?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>ViralPatel.net &#187; MySQL</title> <atom:link href="http://viralpatel.net/blogs/category/database/mysql/feed" rel="self" type="application/rss+xml" /><link>http://viralpatel.net/blogs</link> <description>Tutorials, Java, J2EE, Struts, AJAX, JavaScript, CSS, Web 2.0, MySQL, Articles</description> <lastBuildDate>Tue, 24 Jan 2012 13:45:10 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.3.1</generator> <item><title>How To Reset MySQL Autoincrement Column</title><link>http://viralpatel.net/blogs/2011/12/reseting-mysql-autoincrement-column.html</link> <comments>http://viralpatel.net/blogs/2011/12/reseting-mysql-autoincrement-column.html#comments</comments> <pubDate>Thu, 22 Dec 2011 07:31:38 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Database]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[database indexes]]></category> <category><![CDATA[How-To]]></category> <category><![CDATA[mysqldump]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2473</guid> <description><![CDATA[MySQL database provides a wonderful feature of Autoincrement Column index. Your database table can define its primary key as Autoincrement number and MySQL will take care of its unique value while inserting new rows. Each time you add a new row, MySQL increments the value automatically and persist it to table. But sometime you may [...]]]></description> <content:encoded><![CDATA[<p><img src="http://img.viralpatel.net/mysql-logo.png" alt="mysql-logo" title="mysql-logo" width="187" height="118" class="alignright size-full wp-image-669" />MySQL database provides a wonderful feature of <a href="http://viralpatel.net/blogs/2008/12/get-autoincrement-value-after-insert-query-in-mysql.html">Autoincrement Column</a> index. Your database table can define its primary key as Autoincrement number and MySQL will take care of its unique value while inserting new rows.</p><p>Each time you add a new row, MySQL increments the value automatically and persist it to table. But sometime you may want to reset the Autoincrement column value to 1. Say you writing a sample application and you have inserted few rows already in the table. Now you want to delete these rows and reset the autoincrement column to 1 so that new row which you insert will have primary key value 1.</p><p>There are few methods to achieve this.</p><h2>1. Directly Reset Autoincrement Value</h2><p>Alter table syntax provides a way to reset autoincrement column. Take a look at following example.</p><pre class="brush: sql; gutter: false; title: ; notranslate">
ALTER TABLE table_name AUTO_INCREMENT = 1;
</pre><p>Note that you cannot reset the counter to a value less than or equal to any that have already been used. For MyISAM, if the value is less than or equal to the maximum value currently in the AUTO_INCREMENT column, the value is reset to the current maximum plus one. For InnoDB, if the value is less than the current maximum value in the column, no error occurs and the current sequence value is not changed.</p><h2>2. Truncate Table</h2><p>Truncate table automatically reset the Autoincrement values to 0.</p><pre class="brush: sql; gutter: false; title: ; notranslate">
TRUNCATE TABLE table_name;
</pre><p>Use this with caution. When Truncation is used, it resets any AUTO_INCREMENT counter to zero. From MySQL 5.0.13 on, the AUTO_INCREMENT counter is reset to zero by TRUNCATE TABLE, regardless of whether there is a foreign key constraint.</p><p>Once TRUNCATE is fired, the table handler does not remember the last used AUTO_INCREMENT value, but starts counting from the beginning. This is true even for MyISAM and InnoDB, which normally do not reuse sequence values.</p><h2>3. Drop &#038; Recreate Table</h2><p>This is another way of reseting autoincrement index. Although not very desirable.</p><pre class="brush: sql; gutter: false; title: ; notranslate">
DROP TABLE table_name;
CREATE TABLE table_name { ... };
</pre><p>All these techniques are value techniques to reset autoincrement column number. Use whatever suits your requirement.</p><p><strong>Disclaimer:</strong> The above commands can delete all your data! Be very very cautious.</p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2009/01/mysql-database-backup-mysql-mysqldump-backup-command.html" title="MySQL Database Backup using mysqldump command.">MySQL Database Backup using mysqldump command.</a></li><li><a href="http://viralpatel.net/blogs/2009/04/full-text-search-using-mysql-full-text-search-capabilities.html" title="Full-Text Search using MySQL: Full-Text Search Capabilities">Full-Text Search using MySQL: Full-Text Search Capabilities</a></li><li><a href="http://viralpatel.net/blogs/2008/12/how-to-reset-mysql-root-password.html" title="How to: Reset MySQL root password">How to: Reset MySQL root password</a></li><li><a href="http://viralpatel.net/blogs/2008/12/get-autoincrement-value-after-insert-query-in-mysql.html" title="Get Autoincrement value after INSERT query in MySQL">Get Autoincrement value after INSERT query in MySQL</a></li><li><a href="http://viralpatel.net/blogs/2008/11/mysql-change-root-password.html" title="MySQL Change root Password">MySQL Change root Password</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-annotation-mapping-tutorial.html" title="Hibernate Many To Many Annotation Mapping Tutorial">Hibernate Many To Many Annotation Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-xml-mapping-example.html" title="Hibernate Many To Many XML Mapping Tutorial">Hibernate Many To Many XML Mapping Tutorial</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2011/12/reseting-mysql-autoincrement-column.html/feed</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>Hibernate One To One Mapping Tutorial (XML Mapping)</title><link>http://viralpatel.net/blogs/2011/11/hibernate-one-to-one-mapping-tutorial-xml-mapping.html</link> <comments>http://viralpatel.net/blogs/2011/11/hibernate-one-to-one-mapping-tutorial-xml-mapping.html#comments</comments> <pubDate>Tue, 15 Nov 2011 08:10:56 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Hibernate]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[hibernate-configuration]]></category> <category><![CDATA[maven]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2200</guid> <description><![CDATA[Let us understand how One-to-one mapping works in Hibernate. Following is a simply yet concept building example where we will understand One-to-one mapping in Hibernate framework using XML Mappings. We will use two tables &#8220;employee&#8221; and &#8220;employeedetail&#8221; which exhibits one-to-one relationship. Using Hibernate we will implement this relationship. Tools and technologies used in this article: [...]]]></description> <content:encoded><![CDATA[<p>Let us understand how One-to-one mapping works in Hibernate. Following is a simply yet concept building example where we will understand One-to-one mapping in Hibernate framework using XML Mappings. We will use two tables &#8220;employee&#8221; and &#8220;employeedetail&#8221; which exhibits one-to-one relationship. Using Hibernate we will implement this relationship.<br /><style>#hibernate_tutorial_list{background-color:#EF9;padding:5px;border-radius:10px;color:#222;width:98%;font-size:90%}#hibernate_tutorial_list ul
li{padding:3px
0px}#hibernate_tutorial_list ul li
li{padding:2px
0px}</style><div id="hibernate_tutorial_list"><h3>Hibernate Tutorial Series</h3><ul><li><a href="http://viralpatel.net/blogs/2011/11/introduction-to-hibernate-framework-architecture.html">Introduction to Hibernate Framework</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-maven-mysql-hello-world-example-xml-mapping.html">Hibernate Maven MySQL Hello World example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-hello-world-example-annotation.html">Hibernate Maven MySQL Hello World example (Annotation)</a></li><li>Understanding Relationship Mapping<ul><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-one-to-one-mapping-tutorial-xml-mapping.html">One To One Mapping example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2214/hibernate-one-to-one-mapping-tutorial-using-annotation">One To One Mapping example (Annotation)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-xml-mapping-tutorial.html">One To Many Mapping example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-annotation-tutorial.html">One To Many Mapping example (Annotation)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-xml-mapping-example.html">Many To Many Mapping example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-annotation-mapping-tutorial.html">Many To Many Mapping example (Annotation)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotations-one-to-many-mapping.html">Self-Join One To Many Annotations Mapping example</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotation-mapping-many-to-many-example.html">Self-Join Many To Many Annotations Mapping example</a></li></ul></li><li>Inheritance in Hibernate<ul><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritence-table-per-hierarchy-mapping.html">One Table Per Class Hierarchy (Annotation & XML mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-subclass-annotation-xml-mapping.html">One Table Per Subclass (Annotation & XML mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-concrete-class-annotation-xml-mapping.html">One Table Per Concrete Class (Annotation & XML mapping)</a></li></ul></li></ul></div></p><p>Tools and technologies used in this article:</p><ol><li>Java JDK 1.5 above</li><li>MySQL 5 above</li><li>Eclipse 3.2 above</li><li>Hibernate 3 above</li><li>Maven 3 above</li></ol><h2>1. Create Database</h2><p>We will use MySQL in our example. Create two tables &#8220;employee&#8221; and &#8220;employeedetail&#8221; with One-to-one relationship. Following is the SQL script for same.</p><pre class="brush: sql; title: ; notranslate">
/* EMPLOYEE table */
CREATE TABLE `employee` (
	`employee_id` BIGINT(10) NOT NULL AUTO_INCREMENT,
	`firstname` VARCHAR(50) NULL DEFAULT NULL,
	`lastname` VARCHAR(50) NULL DEFAULT NULL,
	`birth_date` DATE NOT NULL,
	`cell_phone` VARCHAR(15) NOT NULL,
	PRIMARY KEY (`employee_id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
ROW_FORMAT=DEFAULT
AUTO_INCREMENT=216

/* EMPLOYEEDETAIL table */
CREATE TABLE `employeedetail` (
	`employee_id` BIGINT(20) NOT NULL AUTO_INCREMENT,
	`street` VARCHAR(50) NULL DEFAULT NULL,
	`city` VARCHAR(50) NULL DEFAULT NULL,
	`state` VARCHAR(50) NULL DEFAULT NULL,
	`country` VARCHAR(50) NULL DEFAULT NULL,
	PRIMARY KEY (`employee_id`),
	CONSTRAINT `FKEMPL` FOREIGN KEY (`employee_id`) REFERENCES `employee` (`employee_id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
ROW_FORMAT=DEFAULT
AUTO_INCREMENT=216
</pre><p>Note that a one-to-one relationships occurs when one entity is related to exactly one occurrence in another entity. Thus, there will be one primary key which will be mapped with both the entities.</p><h2>2. Hibernate Maven dependency</h2><p>Following dependencies we will use in Maven which will add Hibernate support.</p><p><i>File: /pom.xml</i></p><pre class="brush: xml; 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.viralpatel.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;mysql&lt;/groupId&gt;
			&lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
			&lt;version&gt;5.1.10&lt;/version&gt;
		&lt;/dependency&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;org.hibernate&lt;/groupId&gt;
			&lt;artifactId&gt;hibernate&lt;/artifactId&gt;
			&lt;version&gt;3.2.6.ga&lt;/version&gt;
		&lt;/dependency&gt;
	&lt;/dependencies&gt;
&lt;/project&gt;
</pre><p><br/></p><h2>3. Hibernate Model class</h2><p>For this example we will create two Model class: Employee.java and EmployeeDetail.java. Add following in your project.</p><p><i>File: /src/main/java/net/viralpatel/hibernate/Employee.java</i></p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

import java.sql.Date;

public class Employee {

	private Long employeeId;
	private String firstname;
	private String lastname;
	private Date birthDate;
	private String cellphone;
	private EmployeeDetail employeeDetail;

	public Employee() {

	}

	public Employee(String firstname, String lastname, Date birthdate,
			String phone) {
		this.firstname = firstname;
		this.lastname = lastname;
		this.birthDate = birthdate;
		this.cellphone = phone;
	}

	// Getter and Setter methods
}
</pre><p><br/><br /> <i>File: /src/main/java/net/viralpatel/hibernate/EmployeeDetail.java</i></p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

public class EmployeeDetail {

	private Long employeeId;
	private String street;
	private String city;
	private String state;
	private String country;

	private Employee employee;

	public EmployeeDetail() {

	}

	public EmployeeDetail(String street, String city, String state, String country) {
		this.street = street;
		this.city = city;
		this.state = state;
		this.country = country;
	}

	// Getter and Setter methods	

}
</pre><p>Note that in above model classes, employeeId is common. This is the primary key of Employee table that exhibits One-to-one relationship with EmployeeDetail table.</p><h2>4. Hibernate XML Mapping (HBM)</h2><p>Add following hibernate mapping (hbm) files <code>Employee.hbm.xml</code> and <code>EmployeeDetail.hbm.xml</code> for the model classes created in above steps.</p><p><i>File: /src/main/java/net/viralpatel/hibernate/Employee.hbm.xml</i></p><pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!DOCTYPE hibernate-mapping PUBLIC
        &quot;-//Hibernate/Hibernate Mapping DTD 3.0//EN&quot;
        &quot;http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd&quot;&gt;

&lt;hibernate-mapping package=&quot;net.viralpatel.hibernate&quot;&gt;

	&lt;class name=&quot;Employee&quot; table=&quot;EMPLOYEE&quot;&gt;
		&lt;id name=&quot;employeeId&quot; column=&quot;EMPLOYEE_ID&quot;&gt;
			&lt;generator class=&quot;native&quot; /&gt;
		&lt;/id&gt;
		&lt;one-to-one name=&quot;employeeDetail&quot; class=&quot;net.viralpatel.hibernate.EmployeeDetail&quot;
			cascade=&quot;save-update&quot;&gt;&lt;/one-to-one&gt;

		&lt;property name=&quot;firstname&quot; /&gt;
		&lt;property name=&quot;lastname&quot; column=&quot;lastname&quot; /&gt;
		&lt;property name=&quot;birthDate&quot; type=&quot;date&quot; column=&quot;birth_date&quot; /&gt;
		&lt;property name=&quot;cellphone&quot; column=&quot;cell_phone&quot; /&gt;

	&lt;/class&gt;
&lt;/hibernate-mapping&gt;
</pre><p><i>File: /src/main/java/net/viralpatel/hibernate/EmployeeDetail.hbm.xml</i></p><pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!DOCTYPE hibernate-mapping PUBLIC
        &quot;-//Hibernate/Hibernate Mapping DTD 3.0//EN&quot;
        &quot;http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd&quot;&gt;

&lt;hibernate-mapping package=&quot;net.viralpatel.hibernate&quot;&gt;

    &lt;class name=&quot;EmployeeDetail&quot; table=&quot;EMPLOYEEDETAIL&quot;&gt;

 		&lt;id name=&quot;employeeId&quot; type=&quot;java.lang.Long&quot;&gt;
			&lt;column name=&quot;EMPLOYEE_ID&quot; /&gt;
			&lt;generator class=&quot;foreign&quot;&gt;
				&lt;param name=&quot;property&quot;&gt;employee&lt;/param&gt;
			&lt;/generator&gt;
		&lt;/id&gt;
		&lt;one-to-one name=&quot;employee&quot; class=&quot;net.viralpatel.hibernate.Employee&quot;
			constrained=&quot;true&quot;&gt;&lt;/one-to-one&gt;

        &lt;property name=&quot;street&quot; column=&quot;STREET&quot;/&gt;
        &lt;property name=&quot;city&quot; column=&quot;CITY&quot;/&gt;
        &lt;property name=&quot;state&quot; column=&quot;STATE&quot;/&gt;
        &lt;property name=&quot;country&quot; column=&quot;COUNTRY&quot;/&gt;
	&lt;/class&gt;

&lt;/hibernate-mapping&gt;
</pre><p>Note that in above hibernate mapping we are implementing One-to-one relationship. For both the model classes we are using a single primary key EmployeeId. In EmployeeDetail hbm file we have defined a foreign identifier generator so that primary it uses primary key of Employee table.</p><h2>5. Hibernate Configuration</h2><p>Following is the hibernate configuration hibernate.cfg.xml file. Add this in your project.</p><p><i>File: /src/main/resources/hibernate.cfg.xml</i></p><pre class="brush: xml; 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;hibernate-configuration&gt;
    &lt;session-factory&gt;
        &lt;property name=&quot;connection.driver_class&quot;&gt;com.mysql.jdbc.Driver&lt;/property&gt;
        &lt;property name=&quot;connection.url&quot;&gt;jdbc:mysql://localhost:3306/tutorial&lt;/property&gt;
        &lt;property name=&quot;connection.username&quot;&gt;root&lt;/property&gt;
        &lt;property name=&quot;connection.password&quot;&gt;&lt;/property&gt;

        &lt;property name=&quot;connection.pool_size&quot;&gt;1&lt;/property&gt;
        &lt;property name=&quot;dialect&quot;&gt;org.hibernate.dialect.MySQLDialect&lt;/property&gt;
        &lt;property name=&quot;current_session_context_class&quot;&gt;thread&lt;/property&gt;
        &lt;property name=&quot;cache.provider_class&quot;&gt;org.hibernate.cache.NoCacheProvider&lt;/property&gt;
        &lt;property name=&quot;show_sql&quot;&gt;true&lt;/property&gt;
        &lt;property name=&quot;hbm2ddl.auto&quot;&gt;validate&lt;/property&gt;

        &lt;mapping resource=&quot;net/viralpatel/hibernate/EmployeeDetail.hbm.xml&quot;/&gt;
        &lt;mapping resource=&quot;net/viralpatel/hibernate/Employee.hbm.xml&quot;/&gt;

    &lt;/session-factory&gt;
&lt;/hibernate-configuration&gt;
</pre><p><br/></p><h2>6. Hibernate Utility class</h2><p><i>File:/src/main/java/net/viralpatel/hibernate/HibernateUtil.java</i></p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration()
            		.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><p></br></p><h2>7. Main class to test One-to-one mapping</h2><p>Add following Main.java class in your project to test One-to-one relationship mapping functionality.</p><p><i>File:/src/main/java/net/viralpatel/hibernate/Main.java</i></p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

import java.sql.Date;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class Main {

	public static void main(String[] args) {

		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.openSession();
		session.beginTransaction();

		EmployeeDetail employeeDetail = new EmployeeDetail(&quot;10th Street&quot;, &quot;LA&quot;, &quot;San Francisco&quot;, &quot;U.S.&quot;);

		Employee employee = new Employee(&quot;Nina&quot;, &quot;Mayers&quot;, new Date(121212),
				&quot;114-857-965&quot;);
		employee.setEmployeeDetail(employeeDetail);
		employeeDetail.setEmployee(employee);

		session.save(employee);

		List&lt;Employee&gt; employees = session.createQuery(&quot;from Employee&quot;).list();
		for (Employee employee1 : employees) {
			System.out.println(employee1.getFirstname() + &quot; , &quot;
					+ employee1.getLastname() + &quot;, &quot;
					+ employee1.getEmployeeDetail().getState());
		}

		session.getTransaction().commit();
		session.close();

	}
}
</pre><p><br/></p><h2>8. Review Project Structure</h2><p>Below is the final project structure with all the source files.</p><p><img src="http://img.viralpatel.net/2011/11/hibernate-one-to-one-example-project-structure.png" alt="hibernate-one-to-one-example-project-structure" title="hibernate-one-to-one-example-project-structure" width="290" height="376" class="aligncenter size-full wp-image-2201" /></p><p><br/></p><h2>8. Execute the example</h2><p>Execute the Main class. Hibernate will insert a row in Employee and EmployeeDetail table.</p><p><i>Output:</i></p><pre class="brush: xml; title: ; notranslate">
Hibernate: insert into EMPLOYEE (firstname, lastname, birth_date, cell_phone) values (?, ?, ?, ?)
Hibernate: insert into EMPLOYEEDETAIL (STREET, CITY, STATE, COUNTRY, EMPLOYEE_ID) values (?, ?, ?, ?, ?)
Hibernate: select employee0_.EMPLOYEE_ID as EMPLOYEE1_1_, employee0_.firstname as firstname1_, employee0_.lastname as lastname1_, employee0_.birth_date as birth4_1_, employee0_.cell_phone as cell5_1_ from EMPLOYEE employee0_
Hibernate: select employeede0_.EMPLOYEE_ID as EMPLOYEE1_0_0_, employeede0_.STREET as STREET0_0_, employeede0_.CITY as CITY0_0_, employeede0_.STATE as STATE0_0_, employeede0_.COUNTRY as COUNTRY0_0_ from EMPLOYEEDETAIL employeede0_ where employeede0_.EMPLOYEE_ID=?
Nina , Mayers, San Francisco
</pre><h2>That&#8217;s All Folks</h2><p>Today we saw how to write Hibernate program and implements One-to-one relationship mapping using XML mappings. We used Maven to generate Java project and added Hibernate dependencies into it.</p><h2>Download Source</h2><p><b><a href="http://viralpatel.net/blogs/download/hibernate/Hibernate-One-to-one-tutorial-XML-Mapping.zip">Hibernate-One-to-one-tutorial-XML-Mapping.zip (9 kb)</a></b><br /> <br/></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-maven-mysql-hello-world-example-xml-mapping.html" title="Hibernate Maven MySQL Hello World example (XML Mapping)">Hibernate Maven MySQL Hello World example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-annotation-mapping-tutorial.html" title="Hibernate Many To Many Annotation Mapping Tutorial">Hibernate Many To Many Annotation Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-xml-mapping-example.html" title="Hibernate Many To Many XML Mapping Tutorial">Hibernate Many To Many XML Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2214/hibernate-one-to-one-mapping-tutorial-using-annotation" title="Hibernate One To One Annotation Mapping Tutorial">Hibernate One To One Annotation Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-hello-world-example-annotation.html" title="Hibernate Hello World example using Annotation">Hibernate Hello World example using Annotation</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-subclass-annotation-xml-mapping.html" title="Hibernate Inheritance: Table Per Subclass (Annotation &#038; XML mapping)">Hibernate Inheritance: Table Per Subclass (Annotation &#038; XML mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-annotation-tutorial.html" title="Hibernate One To Many Annotation tutorial">Hibernate One To Many Annotation tutorial</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2011/11/hibernate-one-to-one-mapping-tutorial-xml-mapping.html/feed</wfw:commentRss> <slash:comments>4</slash:comments> </item> <item><title>Hibernate Maven MySQL Hello World example (XML Mapping)</title><link>http://viralpatel.net/blogs/2011/11/hibernate-maven-mysql-hello-world-example-xml-mapping.html</link> <comments>http://viralpatel.net/blogs/2011/11/hibernate-maven-mysql-hello-world-example-xml-mapping.html#comments</comments> <pubDate>Tue, 08 Nov 2011 06:33:39 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Hibernate]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[hibernate-architecture]]></category> <category><![CDATA[hibernate-configuration]]></category> <category><![CDATA[maven]]></category> <category><![CDATA[xml]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=2190</guid> <description><![CDATA[In this tutorial, we will try to write a small hello world program using Hibernate, MySQL and Maven. We will create a Java project using Maven and will then try to add Hibernate on it. Following are the tools and technologies used in this project. Java JDK 5 or above Eclipse IDE 3.2 or above [...]]]></description> <content:encoded><![CDATA[<p>In this tutorial, we will try to write a small hello world program using Hibernate, MySQL and Maven. We will create a Java project using Maven and will then try to add Hibernate on it.<br /><style>#hibernate_tutorial_list{background-color:#EF9;padding:5px;border-radius:10px;color:#222;width:98%;font-size:90%}#hibernate_tutorial_list ul
li{padding:3px
0px}#hibernate_tutorial_list ul li
li{padding:2px
0px}</style><div id="hibernate_tutorial_list"><h3>Hibernate Tutorial Series</h3><ul><li><a href="http://viralpatel.net/blogs/2011/11/introduction-to-hibernate-framework-architecture.html">Introduction to Hibernate Framework</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-maven-mysql-hello-world-example-xml-mapping.html">Hibernate Maven MySQL Hello World example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-hello-world-example-annotation.html">Hibernate Maven MySQL Hello World example (Annotation)</a></li><li>Understanding Relationship Mapping<ul><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-one-to-one-mapping-tutorial-xml-mapping.html">One To One Mapping example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2214/hibernate-one-to-one-mapping-tutorial-using-annotation">One To One Mapping example (Annotation)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-xml-mapping-tutorial.html">One To Many Mapping example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-annotation-tutorial.html">One To Many Mapping example (Annotation)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-xml-mapping-example.html">Many To Many Mapping example (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-annotation-mapping-tutorial.html">Many To Many Mapping example (Annotation)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotations-one-to-many-mapping.html">Self-Join One To Many Annotations Mapping example</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-self-join-annotation-mapping-many-to-many-example.html">Self-Join Many To Many Annotations Mapping example</a></li></ul></li><li>Inheritance in Hibernate<ul><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritence-table-per-hierarchy-mapping.html">One Table Per Class Hierarchy (Annotation & XML mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-subclass-annotation-xml-mapping.html">One Table Per Subclass (Annotation & XML mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-concrete-class-annotation-xml-mapping.html">One Table Per Concrete Class (Annotation & XML mapping)</a></li></ul></li></ul></div></p><p>Following are the tools and technologies used in this project.</p><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</li><li>MySQL 5.0 or above</li></ol><h2>1. Database Creation</h2><p>For this tutorial, we will create a simple table &#8220;employe&#8221; in MySQL. Use following script to create the table.</p><pre class="brush: sql; title: ; notranslate">
CREATE TABLE `employee` (
	`id` BIGINT(10) NOT NULL AUTO_INCREMENT,
	`firstname` VARCHAR(50) NULL DEFAULT NULL,
	`lastname` VARCHAR(50) NULL DEFAULT NULL,
	`birth_date` DATE NOT NULL,
	`cell_phone` VARCHAR(15) NOT NULL,
	PRIMARY KEY (`id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
ROW_FORMAT=DEFAULT
AUTO_INCREMENT=606
</pre><p>Thus, following will be the connection string to connect with MySQL.</p><pre>
Connection URL:	jdbc:mysql://localhost:3306/tutorial
DB Username:	root
DB Password:	<your mysql password>
</pre><h2>2. Generate Maven Java project compatible with Eclipse</h2><p>Open a command prompt and execute following code to generate a Maven Java project.</p><pre class="brush: java; title: ; notranslate">
mvn archetype:generate \
	-DgroupId=net.viralpatel.hibernate \
	-DartifactId=HibernateHelloWorldXML \
	-DarchetypeArtifactId=maven-archetype-quickstart \
	-DinteractiveMode=false
</pre><p>Once you execute above command, a project &#8220;HibernateHelloWorldXML&#8221; is created. Note that this is a Java project which already has folder structures compatible to Maven.</p><p>Once this is done, we will convert it to be compatible with Eclipse. For that executes following command on command prompt.</p><pre class="brush: java; title: ; notranslate">
mvn eclipse:eclipse
</pre><h2>3. Import project in Eclipse</h2><p>Open Eclipse and import the above Java project.</p><pre>
File > Import... > General > Existing Projects into Workspace > Choose above Java project
</pre><p>Once imported, the folder structure will look like following:</p><p><img src="http://img.viralpatel.net/2011/11/hibernate-maven-blank-folder-structure.png" alt="hibernate-maven-blank-folder-structure" title="hibernate-maven-blank-folder-structure" width="240" height="308" class="aligncenter size-full wp-image-2191" /></p><h4>Important:</h4><p>In case you get following error after importing project in Eclipse:<br /> <img src="http://img.viralpatel.net/2011/11/hibernate-maven-repo-error.png" alt="hibernate-maven-repo-error" title="hibernate-maven-repo-error" width="604" height="110" class="aligncenter size-full wp-image-2194" /></p><p>If you are getting this Hibernate Maven Repo error, then you need to define <strong>M2_REPO</strong> environment variable in eclipse pointing to your local maven repository.</p><p>Goto Window > Preferences&#8230; > Java > Build Path > Classpath Variables > Define new variable M2_REPO pointing to your local maven repository.<br /> <img src="http://img.viralpatel.net/2011/11/eclipse-maven-repo-environment-variable.png" alt="eclipse-maven-repo-environment-variable" title="eclipse-maven-repo-environment-variable" width="569" height="368" class="aligncenter size-full wp-image-2193" /></p><p>Once you will define this variable and rebuild the project, the above error will go.</p><h2>4. Add Hibernate Dependency to Maven pom.xml</h2><p>Add following dependencies to Maven pom.xml.</p><pre class="brush: xml; 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.viralpatel.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;mysql&lt;/groupId&gt;
      &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
      &lt;version&gt;5.1.10&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
      &lt;artifactId&gt;hibernate&lt;/artifactId&gt;
      &lt;version&gt;3.2.6.ga&lt;/version&gt;
    &lt;/dependency&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;/dependencies&gt;
&lt;/project&gt;
</pre><p>Once we have added these dependencies, we will execute following command so that maven will download required Jar files and add the same to eclipse classpath.</p><pre class="brush: java; title: ; notranslate">
mvn eclipse:eclipse
</pre><p>The above step is not mandatory. If you have Maven plugin for Eclipse installed in your IDE (Latest eclipse comes with this plugin built-in) you can just enable Maven dependencies by doing<br /> Right click on project > Maven > Enable Dependency Management.</p><h2>5. Add Hibernate Configuration XML</h2><p>Now our project setup is ready. We will add following Hibernate configuration xml file in <b>/src/main/resources</b> folder. Note that this folder is not present in your project structure.</p><p>Create a source folder:<br /> Right click on Project > New > Source Folder > Give folder name &#8220;/src/main/resources/&#8221; and click Finish.</p><p>Copy following file in your project.</p><p><i>File: /src/main/resources/hibernate.cfg.xml</i></p><pre class="brush: xml; 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;hibernate-configuration&gt;
    &lt;session-factory&gt;
        &lt;!-- Database connection settings --&gt;
        &lt;property name=&quot;connection.driver_class&quot;&gt;com.mysql.jdbc.Driver&lt;/property&gt;
        &lt;property name=&quot;connection.url&quot;&gt;jdbc:mysql://localhost:3306/tutorial&lt;/property&gt;
        &lt;property name=&quot;connection.username&quot;&gt;root&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;!-- SQL dialect --&gt;
        &lt;property name=&quot;dialect&quot;&gt;org.hibernate.dialect.MySQLDialect&lt;/property&gt;

        &lt;!-- Enable Hibernate's automatic session context management --&gt;
        &lt;property name=&quot;current_session_context_class&quot;&gt;thread&lt;/property&gt;

        &lt;!-- Disable the second-level cache  --&gt;
        &lt;property name=&quot;cache.provider_class&quot;&gt;org.hibernate.cache.NoCacheProvider&lt;/property&gt;

        &lt;!-- Echo all executed SQL to stdout --&gt;
        &lt;property name=&quot;show_sql&quot;&gt;false&lt;/property&gt;

        &lt;property name=&quot;hbm2ddl.auto&quot;&gt;validate&lt;/property&gt;

        &lt;mapping resource=&quot;net/viralpatel/hibernate/Employee.hbm.xml&quot;/&gt;

    &lt;/session-factory&gt;
&lt;/hibernate-configuration&gt;
</pre><p>One thing we need to make sure in Eclipse is that the Java build path must reflect **/*.xml.<br /> Right click on project > Properties > Java Build Path > Source > Add **/*.xml as follow:<br /> <img src="http://img.viralpatel.net/2011/11/hibernate-java-build-path-include-xml.png" alt="hibernate-java-build-path-include-xml" title="hibernate-java-build-path-include-xml" width="523" height="374" class="aligncenter size-full wp-image-2195" /></p><h2>6. Add Java source code</h2><p><i>File: /src/main/java/net/viralpatel/hibernate/Employee.java</i></p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

import java.sql.Date;

public class Employee {

	private Long id;

	private String firstname;

	private String lastname;

	private Date birthDate;

	private String cellphone;

	public Employee() {

	}

	public Employee(String firstname, String lastname, Date birthdate, String phone) {
		this.firstname = firstname;
		this.lastname = lastname;
		this.birthDate = birthdate;
		this.cellphone = phone;

	}

	// Getter and Setter methods

}
</pre><p>Above is the Employee POJO class that we will use to fetch data from Employee table. This Java class will be mapped by Hiberate with Employee table. Note that we have define two constructors first default and second with arguements. The second constructor is optional. But note that you must define a default (No-arguement) constructor in your mapping class.</p><p><i>File: /src/main/java/net/viralpatel/hibernate/HibernateUtil.java</i></p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration()
            		.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><p>As discussed in previous article <a href="http://viralpatel.net/blogs/2011/11/introduction-to-hibernate-framework-architecture.html" target="_new">Introduction to Hibernate framework</a>, we have to create SessionFactory instance in order to communicate with Database in Hibernate. We will use a Utility class called HibernateUtil to instantiate SessionFactory.</p><p><i>File: /src/main/java/net/viralpatel/hibernate/Employee.hbm.xml</i></p><pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!DOCTYPE hibernate-mapping PUBLIC
        &quot;-//Hibernate/Hibernate Mapping DTD 3.0//EN&quot;
        &quot;http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd&quot;&gt;

&lt;hibernate-mapping package=&quot;net.viralpatel.hibernate&quot;&gt;

    &lt;class name=&quot;Employee&quot; table=&quot;EMPLOYEE&quot;&gt;
 		&lt;id name=&quot;id&quot; column=&quot;ID&quot;&gt;
            &lt;generator class=&quot;native&quot;/&gt;
        &lt;/id&gt;
        &lt;property name=&quot;firstname&quot; /&gt;
        &lt;property name=&quot;lastname&quot; column=&quot;lastname&quot;/&gt;
        &lt;property name=&quot;birthDate&quot; type=&quot;date&quot; column=&quot;birth_date&quot;/&gt;
        &lt;property name=&quot;cellphone&quot; column=&quot;cell_phone&quot;/&gt;
	&lt;/class&gt;

&lt;/hibernate-mapping&gt;
</pre><h2>7. CRUD operations in Hibernate</h2><p>Let us see the basic CRUD operation in Hibernate. We will use Employee table for this.</p><h4>7.1 Writing (Create) data in Hibernate</h2><p>Following is the code snippet that insert a row in database.</p><pre class="brush: java; title: ; notranslate">
private static Employee save(Employee employee) {
	SessionFactory sf = HibernateUtil.getSessionFactory();
	Session session = sf.openSession();
	session.beginTransaction();

	Long id = (Long) session.save(employee);
	employee.setId(id);

	session.getTransaction().commit();

	session.close();

	return employee;
}

...
...
...

// Call the save() method to insert a record in database.
System.out.println(&quot;******* WRITE *******&quot;);
Employee empl = new Employee(&quot;Jack&quot;, &quot;Bauer&quot;, new Date(System.currentTimeMillis()), &quot;911&quot;);
empl = save(empl);
</pre><h4>7.2 Reading (Read) data in Hibernate</h2><p>Below code snippet demos read functionality in Hibernate. Note that there are two methods one to list all the employees and other to read details about just one.</p><pre class="brush: java; title: ; notranslate">
private static List list() {
	SessionFactory sf = HibernateUtil.getSessionFactory();
	Session session = sf.openSession();

	List employees = session.createQuery(&quot;from Employee&quot;).list();
	session.close();
	return employees;
}
private static Employee read(Long id) {
	SessionFactory sf = HibernateUtil.getSessionFactory();
	Session session = sf.openSession();

	Employee employee = (Employee) session.get(Employee.class, id);
	session.close();
	return employee;
}
</pre><h4>7.3 Updating (Update) data in Hibernate</h2><p>Following is the code snippet to update a record in Hibernate.</p><pre class="brush: java; title: ; notranslate">
private static Employee update(Employee employee) {
	SessionFactory sf = HibernateUtil.getSessionFactory();
	Session session = sf.openSession();

	session.beginTransaction();

	session.merge(employee);

	session.getTransaction().commit();

	session.close();
	return employee;

}
</pre><h4>7.4 Remove (Delete) data in Hibernate</h2><p>Following is code snippet to remove a record in Hibernate.</p><pre class="brush: java; title: ; notranslate">
private static void delete(Employee employee) {
	SessionFactory sf = HibernateUtil.getSessionFactory();
	Session session = sf.openSession();

	session.beginTransaction();

	session.delete(employee);

	session.getTransaction().commit();

	session.close();
}
</pre><p>We have created a file Main.java which will test all these functionality. Following is the complete source code of Main.java.<br /> <i>File: /src/main/java/net/viralpatel/hibernate/Main.java</i></p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.hibernate;

import java.sql.Date;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class Main {

	public static void main(String[] args) {

		// Read
		System.out.println(&quot;******* READ *******&quot;);
		List employees = list();
		System.out.println(&quot;Total Employees: &quot; + employees.size());

		// Write
		System.out.println(&quot;******* WRITE *******&quot;);
		Employee empl = new Employee(&quot;Jack&quot;, &quot;Bauer&quot;, new Date(System.currentTimeMillis()), &quot;911&quot;);
		empl = save(empl);
		empl = read(empl.getId());
		System.out.printf(&quot;%d %s %s \n&quot;, empl.getId(), empl.getFirstname(), empl.getLastname());

		// Update
		System.out.println(&quot;******* UPDATE *******&quot;);
		Employee empl2 = read(1l); // read employee with id 1
		System.out.println(&quot;Name Before Update:&quot; + empl2.getFirstname());
		empl2.setFirstname(&quot;James&quot;);
		update(empl2);	// save the updated employee details

		empl2 = read(1l); // read again employee with id 1
		System.out.println(&quot;Name Aftere Update:&quot; + empl2.getFirstname());

		// Delete
		System.out.println(&quot;******* DELETE *******&quot;);
		delete(empl);
		Employee empl3 = read(empl.getId());
		System.out.println(&quot;Object:&quot; + empl3);
	}

	private static List list() {
		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.openSession();

		List employees = session.createQuery(&quot;from Employee&quot;).list();
		session.close();
		return employees;
	}
	private static Employee read(Long id) {
		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.openSession();

		Employee employee = (Employee) session.get(Employee.class, id);
		session.close();
		return employee;
	}
	private static Employee save(Employee employee) {
		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.openSession();

		session.beginTransaction();

		Long id = (Long) session.save(employee);
		employee.setId(id);

		session.getTransaction().commit();

		session.close();

		return employee;
	}

	private static Employee update(Employee employee) {
		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.openSession();

		session.beginTransaction();

		session.merge(employee);

		session.getTransaction().commit();

		session.close();
		return employee;

	}

	private static void delete(Employee employee) {
		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.openSession();

		session.beginTransaction();

		session.delete(employee);

		session.getTransaction().commit();

		session.close();
	}

}
</pre><h2>8. Final project structure</h2><p>Once you have created all these source files, your project structure should look like following. Note that we have removed the default App.java and AppTest.java generated by Maven as we dont these files.<br /> <img src="http://img.viralpatel.net/2011/11/hibernate-maven-final-project-structure.png" alt="hibernate-maven-final-project-structure" title="hibernate-maven-final-project-structure" width="263" height="307" class="aligncenter size-full wp-image-2196" /></p><h2>9. Execute project</h2><p>Execute the Main.java class and see output.</p><pre class="brush: xml; title: ; notranslate">
******* READ *******
Total Employees: 200
******* WRITE *******
201 Jack Bauer
******* UPDATE *******
Name Before Update:Paula
Name Aftere Update:James
******* DELETE *******
Object:null
</pre><h2>That&#8217;s All Folks</h2><p>Today we saw how to write our first Hibernate hello world example using XML Configuration. We used Maven to generate Java project and added Hibernate dependencies into it. Also we saw how to do different CRUD operations in Hibernate.</p><h2> Download Source</h2><p><b><a href="http://viralpatel.net/blogs/download/hibernate/HibernateHelloWorldXML.zip">HibernateHelloWorldXML.zip (8 kb)</a></b></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-one-to-one-mapping-tutorial-xml-mapping.html" title="Hibernate One To One Mapping Tutorial (XML Mapping)">Hibernate One To One Mapping Tutorial (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-concrete-class-annotation-xml-mapping.html" title="Hibernate Inheritance: Table Per Concrete Class (Annotation &#038; XML mapping)">Hibernate Inheritance: Table Per Concrete Class (Annotation &#038; XML mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-inheritance-table-per-subclass-annotation-xml-mapping.html" title="Hibernate Inheritance: Table Per Subclass (Annotation &#038; XML mapping)">Hibernate Inheritance: Table Per Subclass (Annotation &#038; XML mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-annotation-mapping-tutorial.html" title="Hibernate Many To Many Annotation Mapping Tutorial">Hibernate Many To Many Annotation Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-xml-mapping-example.html" title="Hibernate Many To Many XML Mapping Tutorial">Hibernate Many To Many XML Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-annotation-tutorial.html" title="Hibernate One To Many Annotation tutorial">Hibernate One To Many Annotation tutorial</a></li><li><a href="http://viralpatel.net/blogs/2214/hibernate-one-to-one-mapping-tutorial-using-annotation" title="Hibernate One To One Annotation Mapping Tutorial">Hibernate One To One Annotation Mapping Tutorial</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2011/11/hibernate-maven-mysql-hello-world-example-xml-mapping.html/feed</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Full-Text Search using MySQL: Full-Text Search Capabilities</title><link>http://viralpatel.net/blogs/2009/04/full-text-search-using-mysql-full-text-search-capabilities.html</link> <comments>http://viralpatel.net/blogs/2009/04/full-text-search-using-mysql-full-text-search-capabilities.html#comments</comments> <pubDate>Wed, 22 Apr 2009 13:15:36 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Database]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[database indexes]]></category> <category><![CDATA[full-text search]]></category> <category><![CDATA[myisam]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=1202</guid> <description><![CDATA[Have you ever thought how does the search functionality is implemented in all the websites! Most of the internet blogs and websites are powered by MySQL database. MySQL provides a wonderful way (Full-text Search) of implementing a little search engine in your website. All you have to do is to have MySQL 4.x and above. [...]]]></description> <content:encoded><![CDATA[<p><img src="http://img.viralpatel.net/mysql-full-text-search.gif" alt="mysql-full-text-search" title="mysql-full-text-search" width="196" height="178" class="alignleft size-full wp-image-1203" />Have you ever thought how does the search functionality is implemented in all the websites! Most of the internet blogs and websites are powered by MySQL database. MySQL provides a wonderful way (<strong>Full-text Search</strong>) of implementing a little search engine in your website. All you have to do is to have MySQL 4.x and above. MySQL provides full text search capabilities that we can use to implement search functionality.</p><p>First let us setup a sample table for our example. We will create a table called Article.</p><pre class="brush: sql; title: ; notranslate">
CREATE TABLE articles (
    id INT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY,
    title VARCHAR(200),
    body TEXT,
    FULLTEXT (title,body)
);
</pre><p>Also add some sample data in this table. Execute following insert query.</p><pre class="brush: sql; title: ; notranslate">
INSERT INTO articles (title,body) VALUES
    ('MySQL Tutorial','DBMS stands for DataBase ...'),
    ('How To Use MySQL Well','After you went through a ...'),
    ('Optimizing MySQL','In this tutorial we will show ...'),
    ('1001 MySQL Tricks','1. Never run mysqld as root. 2. ...'),
    ('MySQL vs. YourSQL','In the following database comparison ...'),
    ('MySQL Security','When configured properly, MySQL ...');
</pre><p>Once the sample data is ready in our table, we can start with our <strong>full-text search</strong> functionality.</p><h2>Natural Language Full-Text Searches</h2><p>Try to execute following Select query on our sample table.</p><pre class="brush: sql; title: ; notranslate">
SELECT * FROM articles
    WHERE MATCH (title,body) AGAINST ('database');
</pre><p>You will be able to see following result:</p><pre>
  5        MySQL vs. YourSQL        In the following database comparison ...
  1        MySQL Tutorial               DBMS stands for DataBase ...
</pre><p>In above sql query we used MATCH (title,body) AGAINST (&#8216;database&#8217;) to select all the records by performing a full text search on columns title and body.</p><p>You can modify this query and create your own version to perform full-text search in your own database.</p><h2>Boolean Full-Text Searches</h2><p>It may happen that you want to specify certain keywords in your search criteria. Also you may want to ignore certain keywords. Boolean Full-Text Search can used to perform a full text search for such requirements.</p><p>Check the following Select query.</p><pre class="brush: sql; title: ; notranslate">
SELECT * FROM articles WHERE MATCH (title,body)
     AGAINST ('+MySQL -YourSQL' IN BOOLEAN MODE);
</pre><p>If you notice the above Select query, we have added IN BOOLEAN MODE in against(). This query will fetch all the records which has <strong>MySQL</strong> keyword but not <strong>YourSQL</strong> keyword. Notice the + and &#8211; that we have specified before the keywords!</p><p>In implementing this feature, MySQL uses what is sometimes referred to as implied Boolean logic, in which:<br /> <strong>+</strong> stands for <strong>AND</strong><br /> <strong>-</strong> stands for <strong>NOT</strong><br /> <strong>[no operator]</strong> implies <strong>OR</strong></p><p>Following are few examples for the boolean search criteria.</p><p><strong>&#8216;apple banana&#8217;</strong><br /> Find rows that contain at least one of the two words.</p><p><strong>&#8216;+apple +juice&#8217;</strong><br /> Find rows that contain both words.</p><p><strong>&#8216;+apple macintosh&#8217;</strong><br /> Find rows that contain the word “apple”, but rank rows higher if they also contain “macintosh”.</p><p><strong>&#8216;+apple -macintosh&#8217;</strong><br /> Find rows that contain the word “apple” but not “macintosh”.</p><p><strong>&#8216;+apple ~macintosh&#8217;</strong><br /> Find rows that contain the word “apple”, but if the row also contains the word “macintosh”, rate it lower than if row does not. This is “softer” than a search for &#8216;+apple -macintosh&#8217;, for which the presence of “macintosh” causes the row not to be returned at all.</p><p><strong>&#8216;+apple +(&gt;turnover &lt;strudel)&#8217;</strong><br /> Find rows that contain the words “apple” and “turnover”, or “apple” and “strudel” (in any order), but rank “apple turnover” higher than “apple strudel”.</p><h2>Restrictions</h2><p>The Full-text searches are supported for <strong>MyISAM</strong> tables only. As of MySQL 4.1, the use of multiple character sets within a single table is supported. However, all columns in a FULLTEXT index must use the same character set and collation. The <strong>MATCH()</strong> column list must match exactly the column list in some <strong>FULLTEXT</strong> index definition for the table, unless this MATCH() is <strong>IN BOOLEAN MODE</strong>. Boolean-mode searches can be done on non-indexed columns, although they are likely to be slow.</p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2011/12/reseting-mysql-autoincrement-column.html" title="How To Reset MySQL Autoincrement Column">How To Reset MySQL Autoincrement Column</a></li><li><a href="http://viralpatel.net/blogs/2010/06/invisible-indexes-in-oracle-11g.html" title="Invisible Indexes in Oracle 11g">Invisible Indexes in Oracle 11g</a></li><li><a href="http://viralpatel.net/blogs/2010/02/understanding-primary-keypk-constraint-in-oracle.html" title="Understanding Primary Key(PK) Constraint in Oracle">Understanding Primary Key(PK) Constraint in Oracle</a></li><li><a href="http://viralpatel.net/blogs/2009/05/fetch-random-rows-from-database-mysql-oracle-ms-sql-postgresql-example.html" title="Fetch Random rows from Database (MySQL, Oracle, MS SQL, PostgreSQL)">Fetch Random rows from Database (MySQL, Oracle, MS SQL, PostgreSQL)</a></li><li><a href="http://viralpatel.net/blogs/2009/01/maria-extended-myisam-engine-mysql-myisam-maria-mysql.html" title="MARIA, An extended MyISAM engine for MySQL">MARIA, An extended MyISAM engine for MySQL</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-annotation-mapping-tutorial.html" title="Hibernate Many To Many Annotation Mapping Tutorial">Hibernate Many To Many Annotation Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-xml-mapping-example.html" title="Hibernate Many To Many XML Mapping Tutorial">Hibernate Many To Many XML Mapping Tutorial</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2009/04/full-text-search-using-mysql-full-text-search-capabilities.html/feed</wfw:commentRss> <slash:comments>7</slash:comments> </item> <item><title>Generating Tag cloud with PHP and MySQL</title><link>http://viralpatel.net/blogs/2009/03/generating-tag-cloud-with-php-mysql.html</link> <comments>http://viralpatel.net/blogs/2009/03/generating-tag-cloud-with-php-mysql.html#comments</comments> <pubDate>Mon, 16 Mar 2009 05:27:54 +0000</pubDate> <dc:creator>Vimal Patel</dc:creator> <category><![CDATA[MySQL]]></category> <category><![CDATA[PHP]]></category> <category><![CDATA[Web 2.0]]></category> <category><![CDATA[cloud]]></category> <category><![CDATA[tag]]></category> <category><![CDATA[tag-cloud]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=980</guid> <description><![CDATA[The basic idea this time is to present a way to form a tag cloud from user input text and text entered in the past. A tag cloud is a visual depiction of user-generated tags, or simply the word content of a site, used typically to describe the content of web sites. for this we will [...]]]></description> <content:encoded><![CDATA[<p>The basic idea this time is to present a way to form a <strong>tag cloud</strong> from user input text and text entered in the past. A <strong>tag cloud</strong> is a visual depiction of user-generated tags, or simply the word content of a site, used typically to describe the content of web sites.</p><p>for this we will create an HTML form that will accept user text &amp; also allow user to see tag cloud generated from <strong>mysql</strong> database which contains the text entered in the past.</p><pre class="brush: php; title: ; notranslate">
&lt;?php
	echo '&lt;form method=&quot;post&quot; action=&quot;tag_cloud_gen.php&quot; name=&quot;gen_tag_db&quot;&gt;';
	echo '&lt;p&gt;Input your text here:&lt;br /&gt;&lt;textarea name=&quot;tag_input&quot; rows=&quot;20&quot; cols=&quot;80&quot;&gt;&lt;/textarea&gt;&lt;/p&gt;';
	echo '&lt;input type=&quot;submit&quot; name=&quot;submit&quot;&gt;';
	echo '&lt;/form&gt;';
?&gt;
&lt;br /&gt;
&lt;h3&gt;OR&lt;/h3&gt;
&lt;br /&gt;
&lt;p&gt;see the current tag cloud here&lt;/p&gt;
&lt;?php
	echo '&lt;form name=&quot;show_tag_cloud&quot; method=&quot;post&quot; action=&quot;show_tag_cloud.php&quot;&gt;';
	echo '&lt;input type=&quot;submit&quot; value=&quot;show current tag cloud&quot; &gt;';
	echo '&lt;/form&gt;';
?&gt;
</pre><p>The entered text will be tokenized into single words with php function strtok(), each of which will have its frequency counted and the pair will go into an array. This array will then be stored into a mysql database, we can optionally keep a coloumn in the mysql database table to store links if any for future expansion of this project.</p><p>1) tag_id &#8212;- int,primary key,auto increament</p><p>2) keyword &#8212; varchar(20),unique</p><p>3) weight &#8212; int</p><p>4) link &#8212; varchar(256).</p><p>Next make a php file and name it tag_cloud_gen.php . The php code written in following lines just make an array &#8216;$words&#8217; which has keyword in lower case &amp; its frequency association from input text. The pairs from the array are then feed into the mysql database &#8216;tagcloud_db&#8217; which has a table callet &#8216;tags&#8217; whose columns are listed above. On encountering error the mysql _errrno() returns error number. While feeding the word array to the tags table duplication may occour, because of the previous entries, so we check whether this is the case by comparing the number returned to &#8217;1062&#8242; which indicates duplicate field present in the table (the keyword coloumn of table has unique constraint). On encountering this we simply update the mysql database to include the count of this input word/tag too.</p><pre class="brush: php; title: ; notranslate">
&lt;?php
///////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* this function will update the mysql database table to reflect the new count of the keyword
* i.e. the sum of current count in the mysql database &amp;amp;amp;amp;amp;amp; current count in the input.
*/
function update_database_entry($connection,$table,$keyword,$weight){

	$string=$_POST['tag_input'];
	$connection = mysql_connect(&quot;localhost&quot;, &quot;root&quot;, &quot;&quot;);
	/**
	* now comes the main part of generating the tag cloud
	* we would use a css styling for deciding the size of the tag according to its weight,
	* both of which would be fetched from mysql database.
	*/

	$query=&quot;select * from `tagcloud_db`.`tags` where keyword like '%$keyword%'&quot;;
	$resultset=mysql_query($query,$connection);

	if(!$resultset){
		die('Invalid query: ' . mysql_error());
	} else {
		while($row=mysql_fetch_array($resultset)){
		$query=&quot;UPDATE `tagcloud_db`.`tags` SET weight=&quot;.($row[2]+$weight).&quot; where tag_id=&quot;.$row[0].&quot;;&quot;;
		mysql_query($query,$connection);
	}
}
}
?&gt;
&lt;?php
/*
* get the input string from the post and then tokenize it to get each word, save the words in an array
* in case the word is repeated add '1' to the existing words counter
*/
	$count=0;
	$tok = strtok($string, &quot; \t,;.\'\&quot;!&amp;-`\n\r&quot;);//considering line-return,line-feed,white space,comma,ampersand,tab,etc... as word separator
	if(strlen($tok)&gt;0) $tok=strtolower($tok);
	$words=array();
	$words[$tok]=1;
	while ($tok !== false) {
		echo &quot;Word=$tok&lt;br /&gt;&quot;;
		$tok = strtok(&quot; \t,;.\'\&quot;!&amp;-`\n\r&quot;);
		if(strlen($tok)&gt;0) {
		$tok=strtolower($tok);
		if($words[$tok]&gt;=1){
			$words[$tok]=$words[$tok] + 1;
		} else {
			$words[$tok]=1;
		}
	}
}
print_r($words);
echo '&lt;br /&gt;&lt;br /&gt;';
/**
* now enter the above array of word and corresponding count values into the database table
* in case the keyword already exist in the table then update the database table using the function 'update_database_entry(...)'
*/
$table=&quot;tagcloud_db&quot;;
mysql_select_db($table,$connection);
foreach($words as $keyword=&gt;$weight){
	$query=&quot;INSERT INTO `tagcloud_db`.`tags` (keyword,weight,link) values ('&quot;.$keyword.&quot;',&quot;.$weight.&quot;,'NA')&quot;;
	if(!mysql_query($query,$connection)){
		if(mysql_errno($connection)==1062){
			update_database_entry($connection,$table,$keyword,$weight);
		}
	}
}
mysql_close($connection);
?&gt;
</pre><p>Make anether file and name it style.css . Put the following code in it.</p><pre class="brush: xml; title: ; notranslate">
HTML, BODY
{
padding: 0;
border: 0px none;
font-family: Verdana;
font-weight: none;
}
.tags_div
{
padding: 3px;
border: 1px solid #A8A8C3;
background-color: white;
width: 500px;
-moz-border-radius: 5px;
}
H1
{
font-size: 16px;
font-weight: none;
}
A:link
{
color: #676F9D;
text-decoration: none;
}
A:hover
{
text-decoration: none;
background-color: #4F5AA1;
color: white;
}
</pre><p>This will make our tag cloud look pretty, save it as style.css .<br /> again make a new php file and name it show_tag_cloud.php .<br /> In the php code that follows we connect to mysql database, fetch back all the tags, its weight and link.</p><p>Then it calculates the size for each tag using its weight &amp; minimum assumed size for tags, it also associates each tag the link retrieved from the database or with a google link if no link was there i.e. &#8216;NA&#8217;</p><pre class="brush: php; title: ; notranslate">
&lt;?php
	$connection = mysql_connect(&quot;localhost&quot;, &quot;root&quot;, &quot;&quot;);
	$table=&quot;tagcloud_db&quot;;
	$words=array();
	$words_link=array();
	mysql_select_db($table,$connection);
	$query=&quot;SELECT keyword,weight,link FROM `tagcloud_db`.`tags`;&quot;;

	if($resultset=mysql_query($query,$connection)){
		while($row=mysql_fetch_row($resultset)){
			$words[$row[0]]=$row[1];
			$words_link[$row[0]]=$row[2];
		}
	}
// Incresing this number will make the words bigger; Decreasing will do reverse
$factor = 0.5;

// Smallest font size possible
$starting_font_size = 12;

// Tag Separator
$tag_separator = '&amp;nbsp; &amp;nbsp; &amp;nbsp;';
$max_count = array_sum($words);

?&gt;
&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0 Transitional//EN&quot;&gt;
&lt;HTML&gt;
	&lt;HEAD&gt;
		&lt;TITLE&gt; Tag Cloud Generator &lt;/TITLE&gt;
		&lt;META NAME=&quot;Keywords&quot; CONTENT=&quot;tag, cloud, php, mysql&quot;&gt;
		&lt;META NAME=&quot;Description&quot; CONTENT=&quot;A Tag Cloud using php and mysql&quot;&gt;
		&lt;LINK REL=&quot;stylesheet&quot; HREF=&quot;style.css&quot; TYPE=&quot;text/css&quot;&gt;
	&lt;/HEAD&gt;
&lt;BODY&gt;
&lt;center&gt;&lt;h1&gt;Tag Cloud using php and mysql &lt;/h1&gt;&lt;div align='center' class='tags_div'&gt;
&lt;?php
foreach($words as $tag =&gt; $weight )
{
	$x = round(($weight * 100) / $max_count) * $factor;
	$font_size = $starting_font_size + $x.'px';
	if($words_link[$tag]=='NA') echo &quot;&lt;span style='font-size: &quot;.$font_size.&quot;; color: #676F9D;'&gt;&lt;a href='http://www.google.co.in/search?hl=en&amp;q=&quot;.$tag.&quot;&amp;meta='&gt;&quot;.$tag.&quot;&lt;/a&gt;&lt;/span&gt;&quot;.$tag_separator;
	else echo &quot;&lt;span style='font-size: &quot;.$font_size.&quot;; color: #676F9D;'&gt;&lt;a href='http://&quot;.$words_link[$tag].&quot;/'&gt;&quot;.$tag.&quot;&lt;/a&gt;&lt;/span&gt;&quot;.$tag_separator;
}
?&gt;
&lt;/div&gt;&lt;/center&gt;
&lt;/BODY&gt;
&lt;/HTML&gt;
</pre><p>now put them all in your webserver&#8217;s root directory and watch the results. Each query will give you new results over time as the database grows.</p><p>a sample output from my tag cloug looks like this:</p><p><img class="size-medium wp-image-987" src="http://img.viralpatel.net/tag-300x224.jpg" alt="a sample tag cloud on my computer" width="300" height="224" /></p><p>This tag cloud was generated using the following data:</p><p>                     tag_id;keyword;weight;link<br /> &#8220;1&#8243;;&#8221;vimal&#8221;;&#8221;7&#8243;;&#8221;www.vimalkumarpatel.blogspot.com&#8221;<br /> &#8220;2&#8243;;&#8221;scet&#8221;;&#8221;5&#8243;;&#8221;NA&#8221;<br /> &#8220;3&#8243;;&#8221;engg&#8221;;&#8221;2&#8243;;&#8221;NA&#8221;<br /> &#8220;4&#8243;;&#8221;0&#8243;;&#8221;1&#8243;;&#8221;NA&#8221;<br /> &#8220;7&#8243;;&#8221;google&#8221;;&#8221;5&#8243;;&#8221;NA&#8221;<br /> &#8220;8&#8243;;&#8221;cool&#8221;;&#8221;2&#8243;;&#8221;NA&#8221;<br /> &#8220;9&#8243;;&#8221;orkut&#8221;;&#8221;3&#8243;;&#8221;NA&#8221;</p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2009/06/create-3d-tag-cloud-using-jstagcloud-jquery-plugin.html" title="Create 3D tag cloud using jsTagCloud jQuery plugin">Create 3D tag cloud using jsTagCloud jQuery plugin</a></li><li><a href="http://viralpatel.net/blogs/2009/06/twitter-like-n-min-sec-ago-timestamp-in-php-mysql.html" title="Twitter like N min/sec ago timestamp in PHP/MySQL">Twitter like N min/sec ago timestamp in PHP/MySQL</a></li><li><a href="http://viralpatel.net/blogs/2009/04/oracle-buying-sun-microsystems-mysql-future.html" title="Oracle buying Sun Microsystems: What will happen to MySQL!">Oracle buying Sun Microsystems: What will happen to MySQL!</a></li><li><a href="http://viralpatel.net/blogs/2011/12/reseting-mysql-autoincrement-column.html" title="How To Reset MySQL Autoincrement Column">How To Reset MySQL Autoincrement Column</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-annotation-mapping-tutorial.html" title="Hibernate Many To Many Annotation Mapping Tutorial">Hibernate Many To Many Annotation Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-xml-mapping-example.html" title="Hibernate Many To Many XML Mapping Tutorial">Hibernate Many To Many XML Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-xml-mapping-tutorial.html" title="Hibernate One To Many XML Mapping Tutorial">Hibernate One To Many XML Mapping Tutorial</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2009/03/generating-tag-cloud-with-php-mysql.html/feed</wfw:commentRss> <slash:comments>28</slash:comments> </item> <item><title>MARIA, An extended MyISAM engine for MySQL</title><link>http://viralpatel.net/blogs/2009/01/maria-extended-myisam-engine-mysql-myisam-maria-mysql.html</link> <comments>http://viralpatel.net/blogs/2009/01/maria-extended-myisam-engine-mysql-myisam-maria-mysql.html#comments</comments> <pubDate>Sat, 24 Jan 2009 12:30:07 +0000</pubDate> <dc:creator>Gaurav Patel</dc:creator> <category><![CDATA[Database]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[maria]]></category> <category><![CDATA[myisam]]></category> <category><![CDATA[storage engine]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=695</guid> <description><![CDATA[Let us talk about Maria.. no no not Maria Sharapova, its new version of MyISAM engine for MySQL which is claimed to be crash safe and provides more concurrency. It aims at becoming fully transactional (ACID). Following are the features of Maria. Features ACID (Atomicity, Consistency, Isolation, Durability) Commit/Rollback Concurrent selects (via MVCC) Row locking [...]]]></description> <content:encoded><![CDATA[<p><img src="http://img.viralpatel.net/maria-sharapova.jpg" alt="" title="maria-sharapova" width="295" height="420" class="alignright size-full wp-image-705" /><br /> Let us talk about Maria.. no no not Maria Sharapova, its new version of MyISAM engine for MySQL which is claimed to be crash safe and provides more concurrency. It aims at becoming fully transactional (ACID). Following are the features of Maria.</p><h2>Features</h2><style>ul.myPost
li{text-decoration:none;border:none;list-style-type:disc;margin-left:10px}</style><ul class="myPost"><li>ACID (Atomicity, Consistency, Isolation, Durability)</li><li>Commit/Rollback</li><li>Concurrent selects (via MVCC)</li><li>Row locking</li><li>Group commit</li></ul><p>Although Maria itselft is released, but not part of MySQL&#8217;s binaries yet.</p><p>There are some really good faqs on Monty&#8217;s blog (Developer of Maria), although the content is huge, I have taken few useful FAQ about Maria and copied here. Take a look.</p><h2>Frequently Asked Question (FAQ) about Maria.</h2><p><strong>1. How does Maria 1.0 Compare to MyISAM ?</strong></p><p>Maria 1.0 is basically a crash-safe non transactional version of MyISAM.</p><p>Maria supports all aspects of MyISAM, except as noted below. This includes external and internal check/repair/compressing of rows, different row formats, different index compress formats, maria_check etc. After a normal shutdown one can copy Maria files between servers.</p><h3>Advantages of Maria (Compared to MyISAM)</h3><ul class="myPost"><li>Data and indexes are crash safe.</li><li> On a crash, changes will be rolled back to state of the start of a statement or a last LOCK TABLES commands.</li><li>Maria can replay almost everything from the log. (Including create/drop/rename/truncate tables).  Therefore, you make a backup of Maria by just copying the log. The things that can&#8217;t be replayed (yet) are:</li></ul><ul class="myPost"><li> Batch INSERT into an empty table (This includes LOAD DATA INFILE,  SELECT &#8230; INSERT and INSERT (many rows))</li><li> ALTER TABLE. Note that .frm tables are NOT recreated!</li><li>LOAD INDEX can skip index blocks for unwanted indexes</li></ul><ul class="myPost"><li>Supports all MyISAM row formats + new  PAGE format where data is stored in pages. (default size is 8K)</li><li>When using  PAGE format (default) row data is cached by page cache.</li><li>Maria has unit tests of most parts</li><li>Supports both crash-safe (soon to be transactional) and not transactional tables. (Non-transactional tables are not logged and rows uses less space): CREATE TABLE foo (&#8230;) TRANSACTIONAL=0|1 ENGINE=Maria</li><li>PAGE is the only crash-safe/transactional row format.</li><li>PAGE format should give a notable speed improvement on systems which have bad data caching. (For example windows).</li></ul><h3>Differences between Maria and MyISAM:</h3><ul class="myPost"><li>Maria uses BIG (1G by default) log files.</li><li>Maria has a log control file (maria_log_control) and log files ( maria_log.???????). The log files can be automatically purged when not needed or purged on demand (after backup).</li><li>Maria uses 8K pages by default (MyISAM uses 1K). This makes Maria a bit faster when using keys of fixed size, but slower when using variable-length packed keys (until we add a directory to index pages)</li></ul><h3>Disadvantages of Maria (compared to MyISAM), that will be fixed soon</h3><ul class="myPost"><li>Maria 1.0 has one writer or many readers. (MyISAM can have one inserter and many readers when using concurrent inserts).</li><li>Maria doesn&#8217;t support INSERT DELAYED.</li><li>Maria does not support multiple key caches.</li></ul><h3>Disadvantages of Maria (compared to MyISAM), that will be fixed in later releases</h3><ul class="myPost"><li>Storage of very small rows.</li><li>MERGE tables don&#8217;t support Maria (should be very easy to add later).</li></ul><h3>Differences that are not likely to be fixed.</h3><ul class="myPost"><li>Maria data pages in block format have an overhead of 10 bytes/page and 5 bytes/row. Transaction and multiple concurrent-writer support will use an extra overhead of 7 bytes for new rows, 14 bytes for deleted rows and 0 bytes for old compacted rows.</li><li>No external locking (MyISAM has external locking, but is not much used)</li><li>Maria has one page size for both index and data (defined when Maria is used the first time). MyISAM supports different page sizes per index.</li><li>Index number requires one extra byte per index page.</li><li>Maria doesn&#8217;t support MySQL internal RAID (disabled in MyISAM too, it&#8217;s a deprecated feature)</li><li>Minimum data file size for PAGE format is 16K (with 8K pages)</li></ul><p><strong>2. What is the differences between the MySQL-5.1-Maria release and the normal MySQL-5.1 release ?</strong></p><ul class="myPost"><li>Maria is compiled in by default and required to be &#8216;in use&#8217; when mysqld is started.</li><li>Internal on-disk tables are in Maria table format instead of MyISAM table format. This should speed up some GROUP BY and DISTINCT queries because Maria has better caching than MyISAM.</li></ul><h3>New options to CREATE TABLE:</h3><ul class="myPost"><li> TRANSACTIONAL= 0 | 1         ; Transactional means crash-safe for Maria &lt;&gt;</li><li> PAGE_CHECKSUM= 0 | 1         ; If index and data should use page checksums for extra safety.</li><li> TABLE_CHECKSUM= 0 | 1        ; Same as CHECKSUM in MySQL 5.1</li><li> ROW_FORMAT=PAGE ; The new cacheable row format for Maria tables. Default row format for Maria tables and only row format that can be used if TRANSACTIONAL=1. To emulate MyISAM, use ROW_FORMAT=FIXED or ROW_FORMAT=DYNAMIC</li><li>CHECKSUM TABLE now ignores values in NULL fields. This makes CHECKSUM TABLE faster and fixes some cases where same table definition could give different checksum values depending on row format. The disadvantage is that the value is now different compared to other MySQL installations. The new checksum calculation is fixed for all table engines that uses the default way to calculate and MyISAM which does the calculation internally. <span>Note</span>: Old MyISAM tables with internal checksum will return the same checksum as before. To fix them to calculate according to new rules you have to do an ALTER TABLE. You can use the old ways to calculate checksums by using the option &#8211;old to mysqld or set the system variable &#8216;@@old&#8217; to 1 when you do CHECKSUM TABLE &#8230; EXTENDED;</li><li>At startup Maria will check the Maria logs and automatically recover the tables from last checkpoint if mysqld was not taken down correctly.</li><li>There  are some improvements to DBUG code to make its execution faster when debug is compiled in but not used.</li></ul><p><strong>3. Why is the engine called Maria ?</strong></p><p>A funny answer!! Monty, the creator of MySQL, named MySQL after his first child &#8216;My&#8217;. His second child, Max, gave his name to MaxDB and the MySQL-Max distributions. His third and youngest child is named Maria&#8230;!!!</p><p><strong>4. What is goal of Maria in current (MySQL 5.1-Maria) release ?<br /> </strong>To make a crash-safe alternative to MyISAM. That is, when mysqld restarts after a crash occurs, Maria will recover all tables to the state as of the start of a statement or at the start of a previous LOCK TABLES.</p><p><strong>5. What is ultimate goal of Maria?</strong></p><ul class="myPost"><li> To create a new, ACID and multi-version concurrency Control (MVCC), transactional storage engine that can function as the default non-transactional an the default transactional storage engine for MySQL.</li><li>To be a MyISAM replacement. This is possible because Maria can also be run in non-transactional mode, supports all row formats as MyISAM, and supports or will support all major features of MyISAM.</li><li>Maria to be standard part of MySQL 6.X</li></ul><p><strong>6</strong><strong>. Where can I find documentation and help about Maria ?</strong></p><p>Documentation about Maria can be found at: http://forge.mysql.com/wiki/Maria_Docs</p><p><strong>7. Why do you use the TRANSACTIONAL keyword now when Maria is not yet transactional ?</strong></p><p>In the current development phase Maria tables created with TRANSACTIONAL=1 are crashsafe and atomic but not transactional because changes in Maria tables can&#8217;t be rolled back with the ROLLBACK command. As we  will make Maria tables fully transactional in a relatively short time frame we think it&#8217;s better to use  the TRANSACTIONAL keyword already now so that applications don&#8217;t need to be changed later.</p><p>Tables marked with TRANSACTIONAL=1 will for each Maria release get more and more transactional aspects and when we reach Maria 2.0 they will be fully transactional in the traditional sense.</p><p><strong>8. How can I create a MyISAM like (non-transactional) table in Maria ?</strong><br /> Example:</p><pre class="brush: sql; title: ; notranslate">

CREATE TABLE t1 (a int) ROW_FORMAT=FIXED TRANSACTIONAL=0 PAGE_CHECKSUM=0;
CREATE TABLE t2 (a int) ROW_FORMAT=DYNAMIC TRANSACTIONAL=0 PAGE_CHECKSUM=0;
SHOW CREATE TABLE t1;
SHOW CREATE TABLE t2;
</pre><p>Note that the rows are not cached in the page cache for FIXED or DYNAMIC format. If you want to have the data cached (something MyISAM doesn&#8217;t support) you should use ROW_FORMAT=PAGE:</p><pre class="brush: sql; title: ; notranslate">
CREATE TABLE t3 (a int) ROW_FORMAT=PAGE TRANSACTIONAL=0 PAGE_CHECKSUM=0;
SHOW CREATE TABLE t1;
</pre><p>You can use PAGE_CHECKSUM=1 also for non-transactional tables; This puts a page checksums on all index pages. It also puts a checksum on data pages if you use ROW_FORMAT=PAGE.</p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2009/04/full-text-search-using-mysql-full-text-search-capabilities.html" title="Full-Text Search using MySQL: Full-Text Search Capabilities">Full-Text Search using MySQL: Full-Text Search Capabilities</a></li><li><a href="http://viralpatel.net/blogs/2011/12/reseting-mysql-autoincrement-column.html" title="How To Reset MySQL Autoincrement Column">How To Reset MySQL Autoincrement Column</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-annotation-mapping-tutorial.html" title="Hibernate Many To Many Annotation Mapping Tutorial">Hibernate Many To Many Annotation Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-xml-mapping-example.html" title="Hibernate Many To Many XML Mapping Tutorial">Hibernate Many To Many XML Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-xml-mapping-tutorial.html" title="Hibernate One To Many XML Mapping Tutorial">Hibernate One To Many XML Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2214/hibernate-one-to-one-mapping-tutorial-using-annotation" title="Hibernate One To One Annotation Mapping Tutorial">Hibernate One To One Annotation Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-one-to-one-mapping-tutorial-xml-mapping.html" title="Hibernate One To One Mapping Tutorial (XML Mapping)">Hibernate One To One Mapping Tutorial (XML Mapping)</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2009/01/maria-extended-myisam-engine-mysql-myisam-maria-mysql.html/feed</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>MySQL Database Backup using mysqldump command.</title><link>http://viralpatel.net/blogs/2009/01/mysql-database-backup-mysql-mysqldump-backup-command.html</link> <comments>http://viralpatel.net/blogs/2009/01/mysql-database-backup-mysql-mysqldump-backup-command.html#comments</comments> <pubDate>Tue, 20 Jan 2009 07:28:03 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Database]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[How-To]]></category> <category><![CDATA[mysqldump]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=663</guid> <description><![CDATA[Since its release in 1995, MySQL has became one of the most commonly used database in Internet world. A lot of small and medium businesses uses MySQL as their backend db.  Its popularity for use with web applications is closely tied to the popularity of PHP, which is often combined with MySQL. Wikipedia runs on [...]]]></description> <content:encoded><![CDATA[<p><img class="alignright size-full wp-image-669" title="mysql-logo" src="http://img.viralpatel.net/mysql-logo.png" alt="mysql logo" width="187" height="118" />Since its release in 1995, MySQL has became one of the most commonly used database in Internet world. A lot of small and medium businesses uses MySQL as their backend db.  Its popularity for use with web applications is closely tied to the popularity of PHP, which is often combined with MySQL. Wikipedia runs on MediaWiki software, which is written in PHP and uses a MySQL database. Several high-traffic web sites use MySQL for its data storage and logging of user data, including Flickr, Facebook, Wikipedia, Google, Nokia and YouTube.</p><p>MySQL provide a great command line utility to take backup of your MySQL database and restore it. <strong>mysqldump </strong>command line utility is available with MySQL installation (bin directory) that can be used to achieve this.</p><h2>1. Getting backup of a MySQL database using mysqldump.</h2><p>Use following command line for taking backup of your MySQL database using mysqldump utility.</p><pre class="brush: sql; title: ; notranslate">

mysqldump –-user [user name] –-password=[password] [database name] &gt; [dump file]

or

mysqldump –u[user name] –p[password] [database name] &gt; [dump file]
</pre><p>Example:</p><pre class="brush: sql; title: ; notranslate">

mysqldump –-user root –-password=myrootpassword db_test &gt; db_test.sql

or

mysqldump –uroot –pmyrootpassword db_test &gt; db_test.sql
</pre><h2>2. Backup multiple databases in MySQL.</h2><pre class="brush: sql; title: ; notranslate">

mysqldump –u[user name] –p[password] [database name 1] [database name 2] .. &gt; [dump file]
</pre><p>Example:</p><pre class="brush: sql; title: ; notranslate">

mysqldump –-user root –-password=myrootpassword db_test db_second db_third &gt; db_test.sql
</pre><h2>3. Backup all databases in MySQL.</h2><pre class="brush: sql; title: ; notranslate">

shell&gt; mysqldump –u[user name] –p[password] –all-databases &gt; [dump file]
</pre><h2>4. Backup a specific table in MySQL.</h2><pre class="brush: sql; title: ; notranslate">

shell&gt; mysqldump --user [username] --password=[password] [database name] [table name] \
&gt; /tmp/sugarcrm_accounts_contacts.sql
</pre><p>Example:</p><pre class="brush: sql; title: ; notranslate">

shell&gt; mysqldump --user root --password=myrootpassword db_test customers \
&gt; db_test_customers.sql
</pre><h2>5. Restoring MySQL database.</h2><p>The mysqldump utility is used only to take the MySQL dump. To restore the database from the dump file that you created in previous step, use <strong>mysql</strong> command.</p><pre class="brush: sql; title: ; notranslate">

shell&gt; mysql --u [username] --password=[password] [database name] &lt; [dump file]
</pre><p>Example:</p><pre class="brush: sql; title: ; notranslate">

shell&gt; mysql --user root --password=myrootpassword new_db &lt; db_test.sql
</pre><p>Do you know the other uses of mysqldump utility? Comment on this post.</p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2011/12/reseting-mysql-autoincrement-column.html" title="How To Reset MySQL Autoincrement Column">How To Reset MySQL Autoincrement Column</a></li><li><a href="http://viralpatel.net/blogs/2008/12/how-to-reset-mysql-root-password.html" title="How to: Reset MySQL root password">How to: Reset MySQL root password</a></li><li><a href="http://viralpatel.net/blogs/2008/12/get-autoincrement-value-after-insert-query-in-mysql.html" title="Get Autoincrement value after INSERT query in MySQL">Get Autoincrement value after INSERT query in MySQL</a></li><li><a href="http://viralpatel.net/blogs/2008/11/mysql-change-root-password.html" title="MySQL Change root Password">MySQL Change root Password</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-annotation-mapping-tutorial.html" title="Hibernate Many To Many Annotation Mapping Tutorial">Hibernate Many To Many Annotation Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-xml-mapping-example.html" title="Hibernate Many To Many XML Mapping Tutorial">Hibernate Many To Many XML Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-xml-mapping-tutorial.html" title="Hibernate One To Many XML Mapping Tutorial">Hibernate One To Many XML Mapping Tutorial</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2009/01/mysql-database-backup-mysql-mysqldump-backup-command.html/feed</wfw:commentRss> <slash:comments>16</slash:comments> </item> <item><title>How to: Reset MySQL root password</title><link>http://viralpatel.net/blogs/2008/12/how-to-reset-mysql-root-password.html</link> <comments>http://viralpatel.net/blogs/2008/12/how-to-reset-mysql-root-password.html#comments</comments> <pubDate>Fri, 19 Dec 2008 03:52:44 +0000</pubDate> <dc:creator>Gaurav Patel</dc:creator> <category><![CDATA[Database]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[How-To]]></category> <category><![CDATA[root password]]></category> <category><![CDATA[shell]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=404</guid> <description><![CDATA[Resetting the root password of a MySQL database is trivial if you know the current password if you don&#8217;t it is a little trickier. Thankfully it isn&#8217;t too difficult to fix, and here we&#8217;ll show one possible way of doing so. If you&#8217;ve got access to the root account already, because you know the password, [...]]]></description> <content:encoded><![CDATA[<p>Resetting the <strong>root password</strong> of a <strong>MySQL</strong> database is trivial if you know the current password if you don&#8217;t it is a little trickier. Thankfully it isn&#8217;t too difficult to fix, and here we&#8217;ll show one possible way of doing so.</p><p>If you&#8217;ve got access to the root account already, because you know the password, you can change it easily:</p><pre class="brush: java; title: ; notranslate">
gaurav@gaurav:~$ mysql --user=root --pass mysql
Enter password:

mysql&gt; update user set Password=PASSWORD('new-password-here') WHERE User='root';
Query OK, 2 rows affected (0.04 sec)
Rows matched: 2  Changed: 2  Warnings: 0

mysql&gt; flush privileges;
Query OK, 0 rows affected (0.02 sec)

mysql&gt; exit
Bye
</pre><h3>Forget the MySQL root password?</h3><p>However if you don&#8217;t know the current password this approach will not work &#8211; you need to login to run any commands and without the password you&#8217;ll not be able to login!</p><p>Thankfully there is a simple solution to this problem also, we just need to <strong>start MySQL</strong> with a flag to tell it to ignore any username/password restrictions which might be in place. Once that is done you can successfully update the stored details.</p><p>First of all you will need to ensure that your <strong>database</strong> is stopped:</p><pre class="brush: java; title: ; notranslate">
root@gaurav:~# /etc/init.d/mysql stop

Now you should start up the database in the background, via the mysqld_safe command:

root@gaurav:~# /usr/bin/mysqld_safe --skip-grant-tables &amp;
[1] 4271
Starting mysqld daemon with databases from /var/lib/mysql
mysqld_safe[6763]: started
</pre><p>Here you can see the new job (number &#8220;1&#8243;) has started and the server is running with the process ID (PID) of 4271.</p><p>Now that the server is running with the &#8211;skip-grant-tables flag you can connect to it without a password and complete the job:</p><pre class="brush: java; title: ; notranslate">

root@gaurav:~$ mysql --user=root mysql
Enter password:

mysql&gt; update user set Password=PASSWORD('new-password-here') WHERE User='root';
Query OK, 2 rows affected (0.04 sec)
Rows matched: 2  Changed: 2  Warnings: 0

mysql&gt; flush privileges;
Query OK, 0 rows affected (0.02 sec)

mysql&gt; exit
Bye
</pre><p>Now that you&#8217;ve done that you just need to stop the server, so that you can go back to running a secure MySQL server with password restrictions in place. First of all bring the server you started into the foreground by typing &#8220;fg&#8221;, then kill it by pressing &#8220;Ctrl+C&#8221; afterward.</p><p>This will now allow you to start the server:</p><pre class="brush: java; title: ; notranslate">

root@gaurav:~# /etc/init.d/mysql start
Starting MySQL database server: mysqld.
Checking for corrupt, not cleanly closed and upgrade needing tables..
</pre><p>Now everything should be done and you should have regained access to your MySQL database(s); you should verify this by connecting with your new password:</p><pre class="brush: java; title: ; notranslate">
root@gaurav:~# mysql --user=root --pass=new-password-here
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 5 to server version: 5.0.24a-Debian_4-log

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql&gt; exit
Bye
</pre><p>That was easy <img src='http://viralpatel.net/blogs/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> Isn&#8217;t it?</p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2011/12/reseting-mysql-autoincrement-column.html" title="How To Reset MySQL Autoincrement Column">How To Reset MySQL Autoincrement Column</a></li><li><a href="http://viralpatel.net/blogs/2009/05/how-to-execute-command-prompt-command-view-output-java.html" title="How to execute a command prompt command &#038; view output in Java">How to execute a command prompt command &#038; view output in Java</a></li><li><a href="http://viralpatel.net/blogs/2009/01/mysql-database-backup-mysql-mysqldump-backup-command.html" title="MySQL Database Backup using mysqldump command.">MySQL Database Backup using mysqldump command.</a></li><li><a href="http://viralpatel.net/blogs/2008/12/get-autoincrement-value-after-insert-query-in-mysql.html" title="Get Autoincrement value after INSERT query in MySQL">Get Autoincrement value after INSERT query in MySQL</a></li><li><a href="http://viralpatel.net/blogs/2008/11/mysql-change-root-password.html" title="MySQL Change root Password">MySQL Change root Password</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-annotation-mapping-tutorial.html" title="Hibernate Many To Many Annotation Mapping Tutorial">Hibernate Many To Many Annotation Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-xml-mapping-example.html" title="Hibernate Many To Many XML Mapping Tutorial">Hibernate Many To Many XML Mapping Tutorial</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2008/12/how-to-reset-mysql-root-password.html/feed</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Problem with comparison of float or double column in MySQL</title><link>http://viralpatel.net/blogs/2008/12/problem-with-comparison-of-float-or-double-column-in-mysql.html</link> <comments>http://viralpatel.net/blogs/2008/12/problem-with-comparison-of-float-or-double-column-in-mysql.html#comments</comments> <pubDate>Sun, 07 Dec 2008 07:14:56 +0000</pubDate> <dc:creator>Gaurav Patel</dc:creator> <category><![CDATA[Database]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[floating point unit]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=343</guid> <description><![CDATA[Problem with comparison of float or double column in MySQL I had a problem in comparing the number with decimal point with a float column in MySql. After some investigation I came to know that, in most of the computer architecture, the value of floating point numbers is stored as approximation. So if you compare [...]]]></description> <content:encoded><![CDATA[<h1>Problem with comparison of float or double column in MySQL</h1><p>I had a problem in <strong>comparing the number with decimal point with a float column</strong> in <strong>MySql</strong>. After some investigation I came to know that, in most of the computer architecture, the value of <strong>floating point numbers</strong> is stored as approximation. So if you compare the 21.40 with the given column, it actually compare the value with 21.3999999999999986 !! So, if you are comparing FLOAT or DOUBLE columns with numbers that have decimals, you can&#8217;t use <strong>equality (=) comparisons</strong> of <strong>MySql</strong>.</p><p>Converting the float to double also won&#8217;t solve the problem. Then I tried to use &#8216;like&#8217; of <strong>MySql</strong> to comparison and it worked for some case. But, in <strong>MySql</strong> if you use &#8216;like&#8217;, it <strong>converts (or cast)</strong> the values in string, it won&#8217;t match the 21.4 with 21.40 .</p><p>Then I converted the column type to &#8216;<strong>Decimal&#8217;</strong> and that was worked for me. As <strong>Decimal type</strong>, in <strong>MySql</strong>, doesn&#8217;t use the <strong>floating point unit</strong> of CPU, the arithmetic calculation might take more time compare to the <strong>Float </strong>or<strong> Double</strong>. Here you have to compromise with the speed to get accuracy.</p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2011/12/reseting-mysql-autoincrement-column.html" title="How To Reset MySQL Autoincrement Column">How To Reset MySQL Autoincrement Column</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-annotation-mapping-tutorial.html" title="Hibernate Many To Many Annotation Mapping Tutorial">Hibernate Many To Many Annotation Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-many-to-many-xml-mapping-example.html" title="Hibernate Many To Many XML Mapping Tutorial">Hibernate Many To Many XML Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/12/hibernate-one-to-many-xml-mapping-tutorial.html" title="Hibernate One To Many XML Mapping Tutorial">Hibernate One To Many XML Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2214/hibernate-one-to-one-mapping-tutorial-using-annotation" title="Hibernate One To One Annotation Mapping Tutorial">Hibernate One To One Annotation Mapping Tutorial</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-one-to-one-mapping-tutorial-xml-mapping.html" title="Hibernate One To One Mapping Tutorial (XML Mapping)">Hibernate One To One Mapping Tutorial (XML Mapping)</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-hello-world-example-annotation.html" title="Hibernate Hello World example using Annotation">Hibernate Hello World example using Annotation</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2008/12/problem-with-comparison-of-float-or-double-column-in-mysql.html/feed</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>Get Autoincrement value after INSERT query in MySQL</title><link>http://viralpatel.net/blogs/2008/12/get-autoincrement-value-after-insert-query-in-mysql.html</link> <comments>http://viralpatel.net/blogs/2008/12/get-autoincrement-value-after-insert-query-in-mysql.html#comments</comments> <pubDate>Tue, 02 Dec 2008 11:24:17 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Database]]></category> <category><![CDATA[MySQL]]></category> <category><![CDATA[How-To]]></category> <category><![CDATA[Tutorial]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=275</guid> <description><![CDATA[Lot of time we have requirement to update two tables simultaneously. Say for example, we have two tables CUSTOMER_DETAILS and CUSTOMER_ADDRESS. While adding a row in CUSTOMER_DETAILS, few details like address is first written in CUSTOMER_ADDRESS and its reference is added in CUSTOMER_DETAILS table. Now if ADD_ID is a primary key in CUSTOMER_ADDRESS table and [...]]]></description> <content:encoded><![CDATA[<p>Lot of time we have requirement to update two tables simultaneously. Say for example, we have two tables CUSTOMER_DETAILS and CUSTOMER_ADDRESS. While adding a row in CUSTOMER_DETAILS, few details like address is first written in CUSTOMER_ADDRESS and its reference is added in CUSTOMER_DETAILS table. Now if ADD_ID is a primary key in CUSTOMER_ADDRESS table and if it is an auto increment field than how to add this key as a foreign key in CUSTOMER_DETAILS table?</p><p>Well, check following queries:</p><pre class="brush: sql; title: ; notranslate">
INSERT INTO CUSTOMER_ADDRESS (ADD_ID, ADD_TEXT) VALUES(NULL, 'some address value');

INSERT INTO CUSTOMER_DETAILS (NAME, ADD_ID, GENDER, PHONE_NO)
VALUES ('James Bond', LAST_INSERT_ID(), 'MALE', 007);
</pre><p>Now when the first query will get executed, address details will be added in CUSTOMER_ADDRESS table and the ADD_ID will be updated based on autoincrement field as we passed NULL in its place. Just after the completion of first query, we want to add custormer details in CUSTOMER_DETAILS table where we will need the ADD_ID that we just added in CUSTOMER_ADDRESS. Now note that we have used <strong>LAST_INSERT_ID()</strong> function to retrieve the latest autoincrement ID that was used in CUSTOMER_ADDRESS table.</p><p>Thus, LAST_INSERT_ID() can be used to fetch latest autoincrement id being used in any INSERT query that was just got executed.</p><p>Also, you can fetch the recently added autoincrement ID by using following SELECT query:</p><pre class="brush: sql; title: ; notranslate">
SELECT LAST_INSERT_ID();
</pre><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2011/12/reseting-mysql-autoincrement-column.html" title="How To Reset MySQL Autoincrement Column">How To Reset MySQL Autoincrement Column</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-hello-world-example-annotation.html" title="Hibernate Hello World example using Annotation">Hibernate Hello World example using Annotation</a></li><li><a href="http://viralpatel.net/blogs/2009/01/mysql-database-backup-mysql-mysqldump-backup-command.html" title="MySQL Database Backup using mysqldump command.">MySQL Database Backup using mysqldump command.</a></li><li><a href="http://viralpatel.net/blogs/2008/12/how-to-reset-mysql-root-password.html" title="How to: Reset MySQL root password">How to: Reset MySQL root password</a></li><li><a href="http://viralpatel.net/blogs/2008/12/creating-orkut-style-status-update-div-textbox-using-jquery.html" title="Creating orkut style status update div-textbox using jQuery.">Creating orkut style status update div-textbox using jQuery.</a></li><li><a href="http://viralpatel.net/blogs/2008/11/creating-zip-and-jar-files-in-java.html" title="Creating ZIP and JAR Files in Java">Creating ZIP and JAR Files in Java</a></li><li><a href="http://viralpatel.net/blogs/2008/11/mysql-change-root-password.html" title="MySQL Change root Password">MySQL Change root Password</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2008/12/get-autoincrement-value-after-insert-query-in-mysql.html/feed</wfw:commentRss> <slash:comments>12</slash:comments> </item> </channel> </rss>
<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic
Page Caching using disk: enhanced

Served from: viralpatel.net @ 2012-02-09 03:55:03 -->
