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 [Link];
CREATE TABLE
[Link](
MyBatis
<project xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
<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>[Link]</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 [Link]
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="[Link]"/>
</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 [Link] and it resides in
the package named as mybatis, then you can configure the mapper tag as shown
below.
<mappers>
<mapper resource="mybatis/[Link]"/>
</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
[Link]
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.
[Link]
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 [Link]. 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="[Link]"/>
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/[Link]"/>
</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@[Link] |
+----+-------+--------+------------+-----------+---------------+
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.
[Link]("[Link]", 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 [Link](
->
->
->
->
->
->
->
-> );
Query OK, 0 rows affected (0.37 sec)
super();
15
MyBatis
[Link] = name;
[Link] = branch;
[Link] = percentage;
[Link] = phone;
[Link] = email;
}
}
You can define methods to set individual fields in the table. The next chapter
explains how to get the values of individual fields.
[Link] 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 [Link] file for executing SQL INSERT query on database. Create
[Link] file as shown below:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//[Link]//DTD Mapper 3.0//EN"
"[Link]
<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
[Link] File
This file would have application level logic to insert records in the Student table.
Create and save [Link] file as shown below:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
}
}
17
MyBatis
Create
[Link] 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@[Link] |
+----+----------+--------+------------+-----------+--------------------+
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 [Link](
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@[Link] |
2 | shyam
75 | 984800000 | shyam@[Link]
| It
+----+----------+--------+------------+-----------+--------------------+
MyBatis
super();
[Link] = id;
[Link] = name;
[Link] = branch;
[Link] = percentage;
[Link] = phone;
[Link] = email;
}
public Student() {}
MyBatis
[Link] File
To define SQL mapping statement using MyBatis, we would add <select> tag in
[Link] file and inside this tag definition, we would define an "id" which will
be used in [Link] 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 "-//[Link]//DTD Mapper 3.0//EN"
"[Link]
<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 [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
for(Student st : student ){
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
}
[Link]("Records Read Successfully ");
[Link]();
22
MyBatis
[Link]();
}
}
:1
1
Mohammad
It
80
Mohammad@[Link]
984803322
++++++++++++++ details of the student who's id is
+++++++++++++++++++
:2
2
shyam
It
75
shyam@[Link]
984800000
Records Read Successfully
MyBatis
import [Link];
import [Link];
import [Link];
import [Link];
int i=1;
Reader reader = [Link]("[Link]");
SqlSessionFactory sqlSessionFactory = new
SqlSessionFactoryBuilder().build(reader);
SqlSession session = [Link]();
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 [Link](
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@[Link] |
2 | shyam
75 | 984800000 | shyam@[Link]
| It
+----+----------+--------+------------+-----------+--------------------+
MyBatis
super();
[Link] = id;
[Link] = name;
[Link](branch);
[Link](percentage);
[Link] = phone;
[Link] = email;
}
public Student() {}
MyBatis
MyBatis
[Link] File
To define SQL mapping statement using MyBatis, we would add <update> tag in
[Link] and inside this tag definition, we would define an "id" which will be
used in [Link] file for executing SQL UPDATE query on database.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//[Link]//DTD Mapper 3.0//EN"
"[Link]
<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>
[Link] File
This file has application level logic to update records into the Student table:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
//Set new values to the mail and phone number of the student
30
MyBatis
[Link]("mohamad123@[Link]");
[Link](90000000);
}
}
MyBatis
+----+----------+--------+------------+-----------+---------------------+
|
|
1 | Mohammad | It
80 |
|
|
2 | shyam
75 | 984800000 | shyam@[Link]
| It
90000000 | mohamad123@[Link]
+----+----------+--------+------------+-----------+---------------------+
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 [Link](
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@[Link]
|
|
2 | shyam
75 | 984800000 | shyam@[Link]
| It
+----+----------+--------+------------+-----------+---------------------+
2 rows in set (0.00 sec)
33
MyBatis
super();
[Link] = id;
[Link] = name;
[Link](branch);
[Link](percentage);
[Link] = phone;
[Link] = email;
}
public Student() {}
MyBatis
[Link] = name;
}
MyBatis
[Link] File
To define SQL mapping statement using MyBatis, we would use <delete> tag in
[Link] and inside this tag definition, we would define an "id" which will be
used in [Link] file for executing SQL DELETE query on database.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//[Link]//DTD Mapper 3.0//EN"
"[Link]
<mapper namespace="Student">
<resultMap id="result" type="Student">
<result property="id" column="ID"/>
</resultMap>
</mapper>
36
MyBatis
[Link] File
This file has application level logic to delete records from the Student table:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
//Delete operation
[Link]("[Link]", 2);
[Link]();
[Link]();
[Link]("Record deleted successfully");
MyBatis
+----+----------+--------+------------+----------+---------------------+
|
|
1 | Mohammad | It
80 | 90000000 | mohamad123@[Link]
+----+----------+--------+------------+----------+---------------------+
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 [Link](
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@[Link] |
2 | Shyam
75 | 984800000 | shyam@[Link]
| It
+----+----------+--------+------------+-----------+--------------------+
MyBatis
super();
[Link] = id;
[Link] = name;
[Link]=branch;
[Link]=percentage;
[Link] = phone;
[Link] = email;
}
public Student() {}
MyBatis
MyBatis
[Link] = 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 [Link];
import [Link].*;
@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 [Link] file as shown below:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
43
MyBatis
44
MyBatis
+----+----------+--------+------------+-----------+---------------------+
|
|
1 | Mohammad | It
80 | 900000000 | mohamad123@[Link]
|
|
2 | Shyam
| It
75 | 984800000 | shyam@[Link]
|
|
3 | Zara
| EEE
90 | 123412341 | zara@[Link]
+----+----------+--------+------------+-----------+---------------------+
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
[Link]("Shyam123@[Link]");
[Link](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 [Link](
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@[Link] |
80 |
900000000 |
48
MyBatis
|
|
2 | Shyam
| It
75 | 984800000 | shyam@[Link]
+----+----------+--------+------------+-----------+---------------------+
2 rows in set (0.00 sec)
super();
[Link] = id;
[Link] = name;
[Link](branch);
[Link](percentage);
[Link] = phone;
[Link] = email;
}
public Student() {}
MyBatis
MyBatis
[Link] 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 "-//[Link]//DTD Mapper 3.0//EN"
"[Link]
<mapper namespace="Student">
MyBatis
</mapper>
[Link] File
This file has application level logic to read the names of the employees from the
Employee table using ResultMap:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
MyBatis
by
id
MyBatis
Branch :It
Percentage :75
Email :shyam@[Link]
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@[Link]
|
|
2 | Shyam
75 | 984800000 | shyam@[Link]
| It
+----+----------+--------+------------+-----------+---------------------+
2 rows in set (0.00 sec)
MyBatis
super();
[Link] = id;
[Link] = name;
[Link]=branch;
[Link]=percentage;
[Link] = phone;
[Link] = email;
}
public Student() {}
MyBatis
60
MyBatis
[Link] 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 [Link] for executing
Dynamic SQL SELECT query on database.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//[Link]//DTD Mapper 3.0//EN"
"[Link]
<mapper namespace="Student">
[Link] File
This file has application level logic to read conditional records from the Student
table:
61
MyBatis
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
String req_name="Mohammad";
Reader reader = [Link]("[Link]");
SqlSessionFactory sqlSessionFactory = new
SqlSessionFactoryBuilder().build(reader);
SqlSession session = [Link]();
Student stud=new Student();
[Link](req_name);
[Link](1);
List student = [Link]("getRecByName_Id",stud);
for(Student st : student ){
"+[Link]());
[Link]("Name :
"+[Link]());
[Link]("Branch :
"+[Link]());
[Link]("Percentage :
"+[Link]());
62
MyBatis
[Link]("Email :
"+[Link]());
[Link]("Phone :
"+[Link]());
Name :
Branch :
Mohammad
It
Percentage :
80
Email :
mohamad123@[Link]
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
In MyBatis, XML configuration provides a clear separation of SQL logic from the Java code, offering a more organized and decoupled approach. It is advantageous for large projects where SQL queries may change without requiring recompilation of Java classes. However, it can lead to verbosity due to the need for extensive XML configuration files. On the other hand, Annotations allow embedding SQL directly in Java code, enabling rapid development and reduced boilerplate code, beneficial for simple applications. The downside is the potential cluttering of business logic with SQL and reduced flexibility since changes to queries require recompiling the Java source code .
MyBatis provides significant abstraction over traditional JDBC database connections and transaction management. With MyBatis, connection properties like driver name, URL, username, and password are configured in XML files, making them separate from application logic. It supports transaction management through JDBC and MANAGED types, where in JDBC, the application manages commits and rollbacks, and in MANAGED, the application server handles lifecycle management. MyBatis offers POOLED and UNPOOLED connection management, reducing the overhead of opening and closing connections anew for every transaction, unlike traditional JDBC where every connection has to be managed manually, which can be error-prone and less efficient .
MyBatis is distinguished by its simplistic design approach, hyper-fast development facilitation, and portability across different programming languages such as Java, Ruby, and C#. It emphasizes SQL usage, allowing developers to maintain control over SQL executions, contrary to frameworks like Hibernate, which rely on custom query languages like HQL. MyBatis abstracts JDBC code, automates object and SQL database mapping, and separates SQL statements within XML files, enhancing both flexibility and decoupling of code. Additionally, it supports stored procedures, inline SQL, dynamic SQL, and O/RM .
Type aliases in MyBatis provide a means to simplify large, fully-qualified class names by assigning a shorter, easier-to-read alias. This is particularly useful in projects with complex object hierarchies or when using many classes throughout SQL mapping files. By using type aliases, development becomes easier and more maintainable, reducing the chance of errors due to incorrect class name entries and improving readability, especially in large-scale projects where class names might be long and cumbersome .
Dynamic SQL in MyBatis is implemented using specific tags such as <if>, <choose>, <when>, <otherwise>, and <foreach>. These constructs allow SQL queries to be dynamically built at runtime, enhancing the flexibility of query formation based on varying parameters. This approach benefits the application by reducing hard-coded SQL in the codebase, allowing adaptive SQL command creation, which suits disparate conditions or inputs. Consequently, it aids in keeping the application logic clean and scalable while optimizing SQL performance .
Developers using dynamic SQL in MyBatis may encounter challenges such as increased complexity in query structure due to numerous conditional branches, which might lead to more difficult maintenance and debugging. Furthermore, improper management of parameters can lead to SQL injection risks. These challenges can be mitigated by carefully organizing and commenting on dynamic queries within XML, using strong parameter validation checks, and implementing thorough testing of conditions to ensure robustness and security of SQL statements .
MyBatis supports object-relational mapping (O/RM) but with a different focus than frameworks like Hibernate. MyBatis emphasizes using SQL directly, allowing for manual control over SQL execution, while Hibernate abstracts database interaction through HQL, providing a high-level object-oriented query language. This distinction means MyBatis offers greater flexibility and control for developers who prefer writing detailed SQL queries. In contrast, Hibernate provides automatic SQL generation, which can simplify development but at times reduce control over precise SQL optimizations. MyBatis is less intrusive and allows SQL logic modification without recompiling Java code, unlike Hibernate's stronger coupling with Java classes .
MyBatis supports stored procedures by allowing encapsulation of SQL within callable statements and procedures, which abstracts SQL layers from the application code. This approach enables developers to maintain complex SQL logic within the database, ensuring that business logic processing is efficient by leveraging database capabilities directly. The potential advantages of using stored procedures in MyBatis include improved performance through better database optimization, enhanced security by protecting SQL logic from exposure, and reduced application code complexity since business logic is centralized within the database .
MyBatis manages multiple data sources through the use of the 'environments' tag in the configuration XML file. Each environment specifies distinct properties such as transaction manager type and data source configurations. Developers can define multiple 'environment' elements within the 'environments' tag, each configured for a different database setup. This allows applications to switch between databases or modes (e.g., development, production) easily by specifying a default environment. Effective management involves ensuring consistency in naming conventions and maintaining detailed documentation of each environment's purpose and configuration details to prevent misconfigurations .
Mapper XML files in MyBatis facilitate the definition of mapped SQL statements separately from the main application logic. This separation of concerns allows for precise mapping of SQL commands, such as select, insert, update, and delete, each with unique identifiers to interface with the Java code. The advantage of using mapper XML files includes easier maintenance and testing, as SQL queries are centrally managed. They also enhance reusability and reduce duplication of SQL across the application, contributing to a streamlined and efficient workflow .









