Monday, July 18, 2011

Working with MyBatis 3

The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor or annotations. Simplicity is the biggest advantage of the MyBatis data mapper over object relational mapping tools.

To use the MyBatis data mapper, you rely on your own objects, XML, and SQL. There is little to learn that you don't already know. With the MyBatis data mapper, you have the full power of both SQL and stored procedures at your fingertips.

The MyBatis project is developed and maintained by a team that includes the original creators of the "iBATIS" data mapper.

In this section we will download MyBatis, required JdbC driver jar, create new project in Eclipse IDE and then write some code to get member detail from a member table in database. We will finally run the application in the Eclipse IDE.

In this section you will learn how to download, create a new project in Eclipse IDE, add required jars files , the write simple program. Finally we will test the example code in Eclipse IDE.

Step 1:

Download all the required jars to run a simple MyBatis application
http://www.mediafire.com/?cnpr0nfwa45vr

Step 2:
Now we will create a new project in Eclipse IDE and then add the library files.

Click next. Give any name to the project, say "myBatisDummy" and then click on the "Finish" button.

Eclipse will create a new project.

Step 3:

Create a new folder "lib" in the project space to hold the myBatis 3 required libraries. Right click on the "myBatisDummy" in the project explorer and then select new folder option as shown below:


Then in the next screen enter "lib" next to the "Folder name" text field and click on the "Finish" button.
Step 4:
Now we will add the mybatis 3 libraries to the project. Select all the jars and then copy all the jar files (Ctrl+C) and paste on the lib directory (of our project) in the Eclipse IDE.

Step 5:
Now add all the libraries to "Java Build Path". Right click on the "myBatisDummy" in project explorer and then select properties. Then select "Java Build Path" --> Libraries and then click on the "Add JARs" button. And add all the libraries to Java Build Path.
Step 6:
Create a new package to the src folder named as com.vaibhav.mybatis.xml to hold the xml files. Right click on the src folder of "myBatisDummy" project and then select New --> Package. Then provide the package name as com.vaibahv.mybatis.xml and click on the "Finish" button. Add two more packages in the same src folder named as
  • com.vaibhav.mybatis.action
  • com.vaibhav.mybatis.dao
Step 7:

now add batisConfig.xml file to the package com.vaibhav.mybatis.xml. This is the file which contain the required information to connect with the database and all the mapper.xml entries too.

xml version="1.0" encoding="UTF-8" ?>
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="org.gjt.mm.mysql.Driver" />
<property name="url" value="url of your database?autoReconnect=true&characterEncoding=UTF-8" />
<property name="username" value="username of db" />
<property name="password" value="password of db" />
dataSource>
environment>
environments>
configuration>


In the above xml file, you have to provide properties like driver of your database, the URL of your database and username password.

Step 8:
Now add another xml file to the com.vaibhav.mybatis.xml package named as demoMapper.xml
which contains the query part of mybatis.

xml version="1.0" encoding="UTF-8" ?>
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.vaibhav.mybatis.dao.DemoMapper">
<select id="selectMember" parameterType="int" resultType="Member">
select * from Member where MemberId = #{id}
select>
mapper>
Step 9:
Now create an POJO java class which will use as a return type of the query written in xml file or Mapper class.
Create Member.java (as we are having a member table in database, this class name could be anything).

/*
* Copyright 2011 http://java-easy-tutorial.blogspot.com/
*/
package com.vaibhav.mybatis.dao;
/**
* POJO class (refer to a Pojo to Member Table)
*
* @author Vaibhav Bansal
*/
public class Member {
private int gender;
private String firstName;
private String lastName;
private String email1;
public int getGender() {
return gender;
}
public void setGender(int gender) {
this.gender = gender;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public String getEmail1() {
return email1;
}
public void setEmail1(String email1) {
this.email1 = email1;
}
}
Step 10:
Create an Interface DemoMapper.java in com.vaibhav.mybatis.dao package.
If you want to write query part in xml file then this would be an empty interface but if you would like to do your query part in a java file then this is the class in which you will write your db related queries.

package com.vaibhav.mybatis.dao;
import org.apache.ibatis.annotations.Select;
/**
* @author Vaibhav Bansal
* Mapper interface. where we would write our query and create function
*/
public interface DemoMapper {
@Select("SELECT * FROM Member WHERE MemberID = #{id}")
Member selectMember(int id);// creating a function selectMember which takes an int param and return member. query for this function is written just above the method by @select annotation
}

Step 11:

Now create an action class in com.vaibhav.mybatis.action package named as MyBatisAction.java.
This class would contain the main method to run the project and from here we will call the function defined in either DemoMapper.java or demoMapper.xml to retrieve the data from database.

package com.vaibhav.mybatis.action;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.vaibhav.mybatis.dao.DemoMapper;
import com.vaibhav.mybatis.dao.Member;
public class MyBatisAction {
public static void main(String args[]) {
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();// getting the sqlSessionFactory object
// add mappers here
// if you are using .java way to write query then we have to add the Mapper class(the class in which we will write our query) to sqlSessionFactory configuration
sqlSessionFactory.getConfiguration().addMapper(DemoMapper.class);
SqlSession session = sqlSessionFactory.openSession();// open the session
try {
DemoMapper mapper = session.getMapper(DemoMapper.class);// creating a DemoMapper object through session
Member member = mapper.selectMember(123);// calling function defined in DemoMapper class to get the Member data
System.out.println(member.getFirstName());// print member first name
} finally {
session.close(); // session closed
}
}
/** Function to create connection with database and to read the xml files used for mapping.
*/
public static SqlSessionFactory getSqlSessionFactory() {
SqlSessionFactory sqlSessionFactory = null;
try {
String resource = "com/vaibhav/mybatis/xml/batisConfig.xml";// path of the mybatis configuration file.
Reader reader = Resources.getResourceAsReader(resource);// read the mybatis confiuguration xml file
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); //getting the sqlSessionFactory obj
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return sqlSessionFactory;
}
}

Above class will create a sqlsession by the help of batisConfig.xml file and then call the function defined to retrieve the data from database. Please read the comment for more details.

Step 12:

All the configuration of your project are done and now you are able to launch your project.
To run the code in Eclipse open MyBatisAction.java in the editor and then right click and select Run as --> Java Application. This execute the Spring3HelloWorldTest.java file and following output will be displayed in the console.

You can even download the complete project from the link below :
http://www.mediafire.com/?3i78b0m98n9sti9

Please Post comment if you require any

4 comments:

  1. i do every thing as u say but when i run this i get....this type of error...how to solve this type of error...?

    Exception in thread "main" org.apache.ibatis.exceptions.PersistenceException:
    ### Error building SqlSession.
    Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.lang.RuntimeException: Error parsing Mapper XML. Cause: org.apache.ibatis.builder.BuilderException: Error resolving class . Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias 'Member'. Cause: java.lang.ClassNotFoundException: Cannot find class: Member
    at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:8)
    at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:32)
    at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:16)
    at com.kp.mybatis.action.MyBatisAction.getSqlSessionFactory(MyBatisAction.java:44)
    at com.kp.mybatis.action.MyBatisAction.main(MyBatisAction.java:18)
    Caused by: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.lang.RuntimeException: Error parsing Mapper XML. Cause: org.apache.ibatis.builder.BuilderException: Error resolving class . Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias 'Member'. Cause: java.lang.ClassNotFoundException: Cannot find class: Member
    at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:85)
    at org.apache.ibatis.builder.xml.XMLConfigBuilder.parse(XMLConfigBuilder.java:69)
    at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:30)
    ... 3 more
    Caused by: java.lang.RuntimeException: Error parsing Mapper XML. Cause: org.apache.ibatis.builder.BuilderException: Error resolving class . Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias 'Member'. Cause: java.lang.ClassNotFoundException: Cannot find class: Member
    at org.apache.ibatis.builder.xml.XMLMapperBuilder.configurationElement(XMLMapperBuilder.java:97)
    at org.apache.ibatis.builder.xml.XMLMapperBuilder.parse(XMLMapperBuilder.java:73)
    at org.apache.ibatis.builder.xml.XMLConfigBuilder.mapperElement(XMLConfigBuilder.java:255)
    at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:83)
    ... 5 more
    Caused by: org.apache.ibatis.builder.BuilderException: Error resolving class . Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias 'Member'. Cause: java.lang.ClassNotFoundException: Cannot find class: Member
    at org.apache.ibatis.builder.BaseBuilder.resolveClass(BaseBuilder.java:69)
    at org.apache.ibatis.builder.xml.XMLStatementBuilder.parseStatementNode(XMLStatementBuilder.java:40)
    at org.apache.ibatis.builder.xml.XMLMapperBuilder.buildStatementFromContext(XMLMapperBuilder.java:105)
    at org.apache.ibatis.builder.xml.XMLMapperBuilder.configurationElement(XMLMapperBuilder.java:95)
    ... 8 more
    Caused by: org.apache.ibatis.type.TypeException: Could not resolve type alias 'Member'. Cause: java.lang.ClassNotFoundException: Cannot find class: Member
    at org.apache.ibatis.type.TypeAliasRegistry.resolveAlias(TypeAliasRegistry.java:92)
    at org.apache.ibatis.builder.BaseBuilder.resolveAlias(BaseBuilder.java:93)
    at org.apache.ibatis.builder.BaseBuilder.resolveClass(BaseBuilder.java:67)
    ... 11 more
    Caused by: java.lang.ClassNotFoundException: Cannot find class: Member
    at org.apache.ibatis.io.ClassLoaderWrapper.classForName(ClassLoaderWrapper.java:173)
    at org.apache.ibatis.io.ClassLoaderWrapper.classForName(ClassLoaderWrapper.java:72)
    at org.apache.ibatis.io.Resources.classForName(Resources.java:235)
    at org.apache.ibatis.type.TypeAliasRegistry.resolveAlias(TypeAliasRegistry.java:88)
    ... 13 more

    ReplyDelete