Mapper XML

student table:

+----+-------+--------+------------+-----------+---------------+
| ID |  NAME | BRANCH | PERCENTAGE |   PHONE   |     EMAIL     |
+----+-------+--------+------------+-----------+---------------+
|  1 | Shyam |   it   |     80     | 954788457 | [email protected] |
+----+-------+--------+------------+-----------+---------------+

Student POJO:

public class Student {
   private int id;
   private String name;
   private String branch;
   private int percentage;
   private int phone;
   private String email;

   //Setters and getters   
}

Mapped 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.

  • 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’.

<mapper namespace = "Student">
   //mapped statements and result maps
<mapper>

Insert

<insert id = "insert" parameterType = "Student">
   INSERT INTO STUDENT1 (NAME, BRANCH, PERCENTAGE, PHONE, EMAIL ) 
   VALUES (#{name}, #{branch}, #{percentage}, #{phone}, #{email});    
</insert>

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.

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

<update id = "update" parameterType = "Student">
   UPDATE STUDENT SET EMAIL = #{email}, NAME = #{name}, BRANCH = #{branch}, PERCENTAGE = #{percentage}, PHONE = #{phone} WHERE ID = #{id};
</update>
//Assume session is an SqlSession object.  
session.update("Student.update",student);

Delete

<delete id = "deleteById" parameterType = "int">
   DELETE from STUDENT WHERE ID = #{id};
</delete>
//Assume session is an SqlSession object.  
session.delete("Student.deleteById", 18);

Select

<select id = "getAll" resultMap = "result">
   SELECT * FROM STUDENT; 
</select>
List<Student> list = session.selectList("Student.getAll");

resultMaps

<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>

<select id = "getAll" resultMap = "result">
   SELECT * FROM STUDENT; 
</select>

<select id = "getById" parameterType = "int" resultMap = "result">
   SELECT * FROM STUDENT WHERE ID = #{id};
</select>

results matching ""

    No results matching ""