Mybatis Tutorial
Mybatis Tutorial
MyBatis
Audience
This tutorial is designed for Java programmers who would like to understand the
MYBATIS framework in detail along with its architecture and actual usage.
Prerequisites
Before proceeding with this tutorial, you should have a good understanding of Java
programming language. As you are going to deal with SQL mapping, it is required
that you have adequate exposure to SQL and Database concepts.
MyBatis
Table of Contents
About the Tutorial .................................................................................................................................... i
Audience .................................................................................................................................................. i
Prerequisites ............................................................................................................................................ i
Copyright & Disclaimer............................................................................................................................. i
Table of Contents .................................................................................................................................... ii
1.
MYBATIS - OVERVIEW.......................................................................................................... 1
MYBATIS Design Features ....................................................................................................................... 1
Advantages of MYBATIS .......................................................................................................................... 1
2.
MYBATIS - ENVIRONMENT................................................................................................... 3
MyBatis Installation ................................................................................................................................ 3
Database Setup ....................................................................................................................................... 3
MBatis Eclipse Setup ............................................................................................................................... 3
3.
4.
ii
MyBatis
5.
6.
7.
8.
9.
iii
MyBatis
iv
1. MYBATIS - OVERVIEW
MYBATIS
Advantages of MYBATIS
MYBATIS offers the following advantages:
MyBatis
Supports
O/RM
Advantages
of MyBatis
Supports
inline SQL
Supports
dynamic
SQL
2. MYBATIS - ENVIRONMENT
MyBatis
You would have to set up a proper environment for MyBatis before starting off
with the actual development work. This chapter explains how to set up a working
environment for MyBatis.
MyBatis Installation
Carry out the following simple steps to install MyBatis on your machine:
Database Setup
Create an EMPLOYEE table in any MySQL database using the following syntax:
mysql> DROP TABLE IF EXISTS details.student;
CREATE TABLE
details.student(
MyBatis
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>mybatisfinalexamples</groupId>
<artifactId>mybatisfinalexamples</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.3.0</version>
</dependency>
4
MyBatis
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
</dependencies>
/project>
MyBatis
In the previous chapter, we have seen how to install MyBatis. This chapter
discusses how to configure MyBatis using XML file.
Since we are communicating with the database, we have to configure the details
of the database. Configuration XML is the file used for the XML-based
configuration. By using this file, you can configure various elements.
The following programing is a typical structure of MyBatis configuration file.
<configuration>
<typeAliases>
<typeAlias alias="class_alias_Name" type="absolute_clas_Name"/>
</typeAliases>
<mappers>
<mapper resource="path of the configuration XML file"/>
</mappers>
</configuration>
MyBatis
Let us discuss the important elements (tags) of the configuration XML file one by
one.
environments tag
Within the environments element, we configure the environment of the database
that we use in our application. In MyBatis, you can connect to multiple databases
by configuring multiple environment elements. To configure the environment, we
are provided with two sub tags namely transactionManager and dataSource.
transactionManager tag
MyBatis supports two transaction managers namely JDBC and MANAGED
dataSource tag
It is used to configure the connection properties of the database, such as drivername, url, user-name, and password of the database that we want to connect. It
is of three types namely:
MyBatis
typeAliases tag
Instead of specifying the absolute class name everywhere, we can use typeAliases,
a shorter name for a Java type. Suppose, we have a class Student in Student.java
file within the package named tutorials_point.com.mybatis_examples, then the
absolute
class
name
will
be
tutorials_point.com.mybatis_examples.Student. Instead of using this name to
address the class every time, you can declare an alias to that class as shown
below:
<typeAliases>
<typeAlias alias="Student" type="mybatis.Student"/>
</typeAliases>
mappers tag
Mapper XML file is the important file, which contains the mapped SQL statements.
Mappers element is used to configure the location of these mappers xml files in
the configuration file of MyBatis (this element contains four attributes namely
resources, url, class, and name).
For example, the name of the mapper xml file is Student.xml and it resides in
the package named as mybatis, then you can configure the mapper tag as shown
below.
<mappers>
<mapper resource="mybatis/Student.xml"/>
</mappers>
MyBatis
In addition to these, there are other elements that can be used in the configuration
file of MyBatis documentation. Refer MyBatis documentation for the complete
details.
Property
Name
Value
driver
com.mysql.jdbc.Driver
url
username
root
password
password
We use the transaction manager of type JDBC, means we have to perform the
operations, such as commit and roll-back manually, within the application.
We use the dataSource of type UNPOOLED, which means new connection is
created for each database operation. Therefore, it is recommended to close the
connection manually after the completion of database operations.
SqlMapConfig.xml
Below given is the XML configuration for the examples used in this tutorial. Copy
the content given below in a text file and save it as SqlMapConfig.xml. We are
going to use this file in all the examples given in this tutorial.
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
MyBatis
<property name="url"
value="jdbc:mysql://localhost:3306/details"/>
<property name="username" value="root"/>
<property name="password" value="password"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mybatis/Student.xml"/>
</mappers>
</configuration>
10
MyBatis
In the previous chapter, we have seen how to configure MyBatis using an XML file.
This chapter discusses the Mapper XML file and various mapped SQL statements
provided by it.
Before proceeding to mapped statements, assume that the following table
named Student exists in the MYSQL database
+----+-------+--------+------------+-----------+---------------+
| ID |
PHONE
+----+-------+--------+------------+-----------+---------------+
|
1 | Shyam |
it
80
| 954788457 | mail@mail.com |
+----+-------+--------+------------+-----------+---------------+
Also assume that the POJO class also exists named Student with respect to the
above table as shown below
public class Student {
private int id;
private String name;
private String branch;
private int percentage;
private int phone;
private String email;
Mapped Statements
Mapper XML is an important file in MyBatis, which contains a set of statements to
configure various SQL statements such as select, insert, update, and delete. These
statements are known as Mapped Statements or Mapped SQL Statements.
All the statements have unique id. To execute any of these statements you
just need to pass the appropriate id to the methods in Java Application (this
is discussed clearly in later chapters).
11
MyBatis
mapper XML file prevents the burden of writing SQL statements repeatedly
in the application. In comparison to JDBC, almost 95% of the code is
reduced using Mapper XML file in MyBatis.
All these Mapped SQL statements are resided within the element
named<mapper>.
This
element
contains
an
attribute
called namespace.
Insert
In MyBatis, to insert values into the table, we have to configure the insert mapped
query. MyBatis provides various attributes for insert mapper, but largely we use
id and parameter type.
id is unique identifier used to identify the insert statement. On the other hand,
parametertype is the class name or the alias of the parameter that will be passed
into the statement. Below given is an example of insert mapped query
<insert id = "insert" parameterType = "Student">
INSERT INTO STUDENT1 (NAME, BRANCH, PERCENTAGE, PHONE, EMAIL )
VALUES (#{name}, #{branch}, #{percentage}, #{phone}, #{email});
</insert>
In the given example, we use the parameter of type Student (class). The class
student is a POJO class, which represents the Student record with name, branch,
percentage, phone, and email as parameters.
You can invoke the insert mapped query using Java API as shown below
//Assume session is an SqlSession object.
session.insert("Student.insert", student);
Update
To update the values of an existing record using MyBatis, the mapped query
update is configured. The attributes of update mapped query are same as the
insert mapped query. Following is the example of the update mapped query
12
MyBatis
Delete
To delete the values of an existing record using MyBatis, the mapped query delete
is configured. The attributes of delete mapped query are same as the insert and
update mapped queries. Following is the example of the delete mapped query
<delete id = "deleteById" parameterType = "int">
DELETE from STUDENT WHERE ID = #{id};
</delete>
You
can
invoke
the
delete
mapped
query
using
the
delete
method
Select
To retrieve data, select mapper statement is used. Following is the example of
select mapped query to retrieve all the records in a table
<select id = "getAll" resultMap = "result">
SELECT * FROM STUDENT;
</select>
You
can
retrieve
the
data
returned
by
the
select
query
using
the
method selectList(). This method returns the data of the selected record in the
form of List as shown below
13
MyBatis
resultMaps
It is the most important and powerful elements in MyBatis. The results of SQL
SELECT statements are mapped to Java objects (beans/POJO). Once the result
map is defined, we can refer these from several SELECT statements. Following is
the example of result Map query; it maps the results of the select queries to the
Student class
<resultMap id = "result" type = "Student">
<result property = "id" column = "ID"/>
<result property = "name" column = "NAME"/>
<result property = "branch" column = "BRANCH"/>
<result property = "percentage" column="PERCENTAGE"/>
<result property = "phone" column = "PHONE"/>
<result property = "email" column = "EMAIL"/>
</resultMap>
14
MyBatis
To perform any Create, Read, Update, and Delete (CRUD) operation using
MyBatis, you would need to create a Plain Old Java Objects (POJO) class
corresponding to the table. This class describes the objects that will "model"
database table rows.
The POJO class would have implementation for all the methods required to perform
desired operations.
Create the STUDENT table in MySQL database as shown below:
mysql> CREATE TABLE details.student(
->
->
->
->
->
->
->
-> );
Query OK, 0 rows affected (0.37 sec)
super();
15
MyBatis
this.name = name;
this.branch = branch;
this.percentage = percentage;
this.phone = phone;
this.email = email;
}
}
You can define methods to set individual fields in the table. The next chapter
explains how to get the values of individual fields.
Student.xml File
To define SQL mapping statement using MyBatis, we would use <insert> tag.
Inside this tag definition, we would define an "id." Further, the id will be used in
the mybatisInsert.java file for executing SQL INSERT query on database. Create
student.xml file as shown below:
<?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="Student">
</mapper>
Here, parameteType could take a value as string, int, float, double, or any
class object based on requirement. In this example, we would pass Student object
as a parameter, while calling insert method of SqlSession class.
If your database table uses an IDENTITY, AUTO_INCREMENT, or SERIAL column,
or you have defined a SEQUENCE/GENERATOR, you can use the <selectKey>
16
MyBatis
mybatisInsert.java File
This file would have application level logic to insert records in the Student table.
Create and save mybatisInsert.java file as shown below:
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;
}
}
17
MyBatis
Create
SqlMapConfig.xml as
shown
in
You would get the following result, and a record would be created in the STUDENT
table.
$java mybatisInsert
Record Inserted Successfully
If you check the STUDENT table, it should display the following result
mysql> select * from student;
+----+----------+--------+------------+-----------+--------------------+
| ID | NAME
+----+----------+--------+------------+-----------+--------------------+
|
1 | Mohammad | It
80 | 984803322 | Mohammad@gmail.com |
+----+----------+--------+------------+-----------+--------------------+
1 row in set (0.00 sec)
18
MyBatis
We discussed in the last chapter, how to insert values into the STUDENT table
using MyBatis by performing CREATE operation. This chapter explains how to read
the data in a table using MyBatis.
We have the following STUDENT table in MySQL:
CREATE TABLE details.student(
ID int(10) NOT NULL AUTO_INCREMENT,
NAME varchar(100) NOT NULL,
BRANCH varchar(255) NOT NULL,
PERCENTAGE int(3) NOT NULL,
PHONE int(11) NOT NULL,
EMAIL varchar(255) NOT NULL,
PRIMARY KEY (`ID`)
);
Assume, this table has two record as:
+----+----------+--------+------------+-----------+--------------------+
| ID | NAME
+----+----------+--------+------------+-----------+--------------------+
|
1 | Mohammad | It
80 | 984803322 | Mohammad@gmail.com |
2 | shyam
75 | 984800000 | shyam@gmail.com
| It
+----+----------+--------+------------+-----------+--------------------+
MyBatis
super();
this.id = id;
this.name = name;
this.branch = branch;
this.percentage = percentage;
this.phone = phone;
this.email = email;
}
public Student() {}
MyBatis
Student.xml File
To define SQL mapping statement using MyBatis, we would add <select> tag in
Student.xml file and inside this tag definition, we would define an "id" which will
be used in mybatisRead.java file for executing SQL SELECT query on database.
While reading the records, we can get all the records at once or we can get a
particular record using the where clause. In the XML given below, you can observe
both the queries.
To retrieve a particular record, we need a unique key to represent that record.
Therefore, we have also defined the resultmap "id" (unique key) of type Student
to map the result of the select query with the variable of Student class.
<?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="Student">
</mapper>
21
MyBatis
mybatisRead_ALL.java File
This file has application level logic to read all the records from the Student table.
Create and save mybatisRead_ALL.java file as shown below:
import java.io.IOException;
import java.io.Reader;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
for(Student st : student ){
System.out.println(st.getId());
System.out.println(st.getName());
System.out.println(st.getBranch());
System.out.println(st.getPercentage());
System.out.println(st.getEmail());
System.out.println(st.getPhone());
}
System.out.println("Records Read Successfully ");
session.commit();
22
MyBatis
session.close();
}
}
:1
1
Mohammad
It
80
Mohammad@gmail.com
984803322
++++++++++++++ details of the student who's id is
+++++++++++++++++++
:2
2
shyam
It
75
shyam@gmail.com
984800000
Records Read Successfully
MyBatis
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
int i=1;
Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new
SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
by
id
24
MyBatis
25
MyBatis
We discussed, in the last chapter, how to perform READ operation on a table using
MyBatis. This chapter explains how you can update records in a table using it.
We have the following STUDENT table in MySQL:
CREATE TABLE details.student(
ID int(10) NOT NULL AUTO_INCREMENT,
NAME varchar(100) NOT NULL,
BRANCH varchar(255) NOT NULL,
PERCENTAGE int(3) NOT NULL,
PHONE int(11) NOT NULL,
EMAIL varchar(255) NOT NULL,
PRIMARY KEY (`ID`)
);
Assume this table has two record as follows:
mysql> select * from STUDENT;
+----+----------+--------+------------+-----------+--------------------+
| ID | NAME
+----+----------+--------+------------+-----------+--------------------+
|
1 | Mohammad | It
80 | 984803322 | Mohammad@gmail.com |
2 | shyam
75 | 984800000 | shyam@gmail.com
| It
+----+----------+--------+------------+-----------+--------------------+
MyBatis
super();
this.id = id;
this.name = name;
this.setBranch(branch);
this.setPercentage(percentage);
this.phone = phone;
this.email = email;
}
public Student() {}
MyBatis
MyBatis
Student.xml File
To define SQL mapping statement using MyBatis, we would add <update> tag in
Student.xml and inside this tag definition, we would define an "id" which will be
used in mybatisUpdate.java file for executing SQL UPDATE query on database.
<?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="Student">
<resultMap id="result" type="Student">
<result property="id" column="ID"/>
<result property="name" column="NAME"/>
<result property="branch" column="BRANCH"/>
<result property="percentage" column="PERCENTAGE"/>
<result property="phone" column="PHONE"/>
<result property="email" column="EMAIL"/>
</resultMap>
MyBatis
PERCENTAGE = #{percentage},
PHONE = #{phone},
EMAIL = #{email}
WHERE ID = #{id};
</update>
</mapper>
mybatisUpdate.java File
This file has application level logic to update records into the Student table:
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;
//Set new values to the mail and phone number of the student
30
MyBatis
student.setEmail("mohamad123@yahoo.com");
student.setPhone(90000000);
}
}
MyBatis
+----+----------+--------+------------+-----------+---------------------+
|
|
1 | Mohammad | It
80 |
|
|
2 | shyam
75 | 984800000 | shyam@gmail.com
| It
90000000 | mohamad123@yahoo.com
+----+----------+--------+------------+-----------+---------------------+
2 rows in set (0.00 sec)
32
MyBatis
This chapter describes how to delete records from a table using MyBatis.
We have the following STUDENT table in MySQL:
CREATE TABLE details.student(
ID int(10) NOT NULL AUTO_INCREMENT,
NAME varchar(100) NOT NULL,
BRANCH varchar(255) NOT NULL,
PERCENTAGE int(3) NOT NULL,
PHONE int(11) NOT NULL,
EMAIL varchar(255) NOT NULL,
PRIMARY KEY (`ID`)
);
Assume, this table has two records as:
mysql> select * from STUDENT;
+----+----------+--------+------------+-----------+---------------------+
| ID | NAME
|
+----+----------+--------+------------+-----------+---------------------+
|
|
1 | Mohammad | It
80 | 900000000| mohamad123@yahoo.com
|
|
2 | shyam
75 | 984800000 | shyam@gmail.com
| It
+----+----------+--------+------------+-----------+---------------------+
2 rows in set (0.00 sec)
33
MyBatis
super();
this.id = id;
this.name = name;
this.setBranch(branch);
this.setPercentage(percentage);
this.phone = phone;
this.email = email;
}
public Student() {}
MyBatis
this.name = name;
}
MyBatis
Student.xml File
To define SQL mapping statement using MyBatis, we would use <delete> tag in
Student.xml and inside this tag definition, we would define an "id" which will be
used in mybatisDelete.java file for executing SQL DELETE query on database.
<?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="Student">
<resultMap id="result" type="Student">
<result property="id" column="ID"/>
</resultMap>
</mapper>
36
MyBatis
MyBatisDelete.java File
This file has application level logic to delete records from the Student table:
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;
//Delete operation
session.delete("Student.deleteById", 2);
session.commit();
session.close();
System.out.println("Record deleted successfully");
MyBatis
+----+----------+--------+------------+----------+---------------------+
|
|
1 | Mohammad | It
80 | 90000000 | mohamad123@yahoo.com
+----+----------+--------+------------+----------+---------------------+
1 row in set (0.00 sec)
38
9. MYBATIS - ANNOTATIONS
MyBatis
In the previous chapters, we have seen how to perform curd operations using
MyBatis. There we used a Mapper XML file to store mapped SQL statements and
a configuration XML file to configure MyBatis.
To map SQL statements, MyBatis also provides annotations. So, this chapter
discusses how to use MyBatis annotations.
While working with annotations, instead of configuration XML file, we can use a
java mapper interface to map and execute SQL queries.
Assume, we have the following employee table in MySQL:
CREATE TABLE details.student(
ID int(10) NOT NULL AUTO_INCREMENT,
NAME varchar(100) NOT NULL,
BRANCH varchar(255) NOT NULL,
PERCENTAGE int(3) NOT NULL,
PHONE int(11) NOT NULL,
EMAIL varchar(255) NOT NULL,
PRIMARY KEY (`ID`)
);
Query OK, 0 rows affected (0.37 sec)
Assume, this table has two records as:
mysql> select * from STUDENT;
+----+----------+--------+------------+-----------+--------------------+
| ID | NAME
+----+----------+--------+------------+-----------+--------------------+
|
1 | Mohammad | It
80 | 984803322 | Mohammad@gmail.com |
2 | Shyam
75 | 984800000 | shyam@gmail.com
| It
+----+----------+--------+------------+-----------+--------------------+
MyBatis
super();
this.id = id;
this.name = name;
this.branch=branch;
this.percentage=percentage;
this.phone = phone;
this.email = email;
}
public Student() {}
MyBatis
MyBatis
this.percentage = percentage;
}
Student_mapper.java
This is the file, which contains the mapper interface where we declare the mapped
statements using annotations instead of XML tags. For almost all of the XML-based
mapper elements, MyBatis provides annotations. The following file named
Student_mapper.java, contains a mapper interface. Within this file, you can see
the annotations to perform CURD operations on the STUDENT table.
import java.util.List;
import org.apache.ibatis.annotations.*;
@Select(getAll)
@Results(value = {
@Result(property="id", column="ID"),
@Result(property="name", column="NAME"),
@Result(property="branch", column="BRANCH"),
@Result(property="percentage", column="PERCENTAGE"),
@Result(property="phone", column="PHONE"),
@Result(property="email", column="EMAIL")
})
42
MyBatis
List getAll();
@Select(getById)
@Results(value = {
@Result(property="id", column="ID"),
@Result(property="name", column="NAME"),
@Result(property="branch", column="BRANCH"),
@Result(property="percentage", column="PERCENTAGE"),
@Result(property="phone", column="PHONE"),
@Result(property="email", column="EMAIL")
})
Student getById(int id);
@Update(update)
void update(Student student);
@Delete(deleteById)
void delete(int id);
@Insert(insert)
@Options(useGeneratedKeys = true, keyProperty = "id")
void insert(Student student);
}
Annotations_Example.java File
This file would have application level logic to insert records in the Student table.
Create and save mybatisInsert.java file as shown below:
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;
43
MyBatis
44
MyBatis
+----+----------+--------+------------+-----------+---------------------+
|
|
1 | Mohammad | It
80 | 900000000 | mohamad123@yahoo.com
|
|
2 | Shyam
| It
75 | 984800000 | shyam@gmail.com
|
|
3 | Zara
| EEE
90 | 123412341 | zara@gmail.com
+----+----------+--------+------------+-----------+---------------------+
3 rows in set (0.08 sec)
In the same way, we can perform update, delete, and read operations using
annotations by replacing the content of Annotations_Example.java with the
respective snippets mentioned below:
45
MyBatis
Update
public static void main(String args[]) throws IOException{
//Set new values to the mail and phone number of the student
student.setEmail("Shyam123@yahoo.com");
student.setPhone(984802233);
Read
public static void main(String args[]) throws IOException{
MyBatis
Delete
public static void main(String args[]) throws IOException{
47
MyBatis
You can call a stored procedure using MyBatis. First of all, let us understand how
to create a stored procedure in MySQL.
We have the following EMPLOYEE table in MySQL:
CREATE TABLE details.student(
ID int(10) NOT NULL AUTO_INCREMENT,
NAME varchar(100) NOT NULL,
BRANCH varchar(255) NOT NULL,
PERCENTAGE int(3) NOT NULL,
PHONE int(11) NOT NULL,
EMAIL varchar(255) NOT NULL,
PRIMARY KEY (`ID`)
);
Let us create the following stored procedure in MySQL database:
DELIMITER //
DROP PROCEDURE IF EXISTS details.read_recordById //
CREATE PROCEDURE details.read_recordById (IN emp_id INT)
BEGIN
SELECT * FROM STUDENT WHERE ID = emp_id;
END//
DELIMITER ;
Assume the table named STUDENT has two records as:
mysql> select * from STUDENT;
+----+----------+--------+------------+-----------+---------------------+
| ID | NAME
|
+----+----------+--------+------------+-----------+---------------------+
| 1 | Mohammad | It
mohamad123@yahoo.com |
80 |
900000000 |
48
MyBatis
|
|
2 | Shyam
| It
75 | 984800000 | shyam@gmail.com
+----+----------+--------+------------+-----------+---------------------+
2 rows in set (0.00 sec)
super();
this.id = id;
this.name = name;
this.setBranch(branch);
this.setPercentage(percentage);
this.phone = phone;
this.email = email;
}
public Student() {}
MyBatis
MyBatis
Student.xml File
Unlike IBATIS, there is no <procedure> tag in MyBatis. To map the results of
the procedures, we have created a resultmap named Student and to call the stored
procedure named read_recordById. We have defined a select tag with id callById,
and we use the same id in the application to call the procedure.
<?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="Student">
MyBatis
</mapper>
mybatisSP.java File
This file has application level logic to read the names of the employees from the
Employee table using ResultMap:
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;
MyBatis
by
id
MyBatis
Branch :It
Percentage :75
Email :shyam@gmail.com
hone :984800000
54
MyBatis
if
choose (when, otherwise)
trim (where, set)
foreach
The if Statement
The most common thing to do in dynamic SQL is conditionally include a part of a
where clause. For example:
<select id="getRecByName" parameterType="Student" resultType="Student">
MyBatis
</choose>
</select>
MyBatis
WHERE
This would fail, but MyBatis has a simple solution with one simple change,
everything works fine:
<select id="getName_Id_phone" parameterType="Student"
resultType="Student">
SELECT * FROM STUDENT
<where>
<if test="id != null">
id = #{id}
</if>
MyBatis
</select>
+----+----------+--------+------------+-----------+---------------------+
|
|
1 | Mohammad | It
80 | 900000000 | mohamad123@yahoo.com
|
|
2 | Shyam
75 | 984800000 | shyam@gmail.com
| It
+----+----------+--------+------------+-----------+---------------------+
2 rows in set (0.00 sec)
MyBatis
super();
this.id = id;
this.name = name;
this.branch=branch;
this.percentage=percentage;
this.phone = phone;
this.email = email;
}
public Student() {}
MyBatis
60
MyBatis
Student.xml File
This file contains the result map named Student, to map the results of the SELECT
Query. We will define an "id" which will be used in mybatisRead.java for executing
Dynamic SQL SELECT query on database.
<?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="Student">
GetRecordByName.java File
This file has application level logic to read conditional records from the Student
table:
61
MyBatis
import java.io.IOException;
import java.io.Reader;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
String req_name="Mohammad";
Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new
SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
Student stud=new Student();
stud.setName(req_name);
stud.setId(1);
List student = session.selectList("getRecByName_Id",stud);
for(Student st : student ){
"+st.getId());
System.out.println("Name :
"+st.getName());
System.out.println("Branch :
"+st.getBranch());
System.out.println("Percentage :
"+st.getPercentage());
62
MyBatis
System.out.println("Email :
"+st.getEmail());
System.out.println("Phone :
"+st.getPhone());
Name :
Branch :
Mohammad
It
Percentage :
80
Email :
mohamad123@yahoo.com
Phone :
90000000
63
MyBatis
There are major differences between MyBatis and Hibernate. Both the
technologies work well, given their specific domain. MyBatis is suggested in case:
You want to create your own SQL's and you are willing to maintain them.
Your environment is driven by relational data model.
You have to work on existing and complex schemas.
Use Hibernate, if the environment is driven by object model and needs to generate
SQL automatically.
Hibernate
Hibernate and MyBatis both are compatible with the SPRING framework, so it
should not be a problem to choose one of them.
64