Saturday, 23 April 2016

How to use Result Map in iBatis ?


The resultMap element is the most important and powerful in iBATIS.
It can reduce your iBatis code to minimum.

Example
EMPLOYEE table in MySQL
CREATE TABLE EMPLOYEE (
  id INT NOT NULL auto_increment,
  first_name VARCHAR(20) default NULL,
  last_name VARCHAR(20) default NULL,
  salary INT default NULL, PRIMARY KEY (id)
);

Employee POJO Class
public class Employee {
  private int id;
  private String first_name;
  private String last_name;
  private int salary;
  /* Getters and setters */
}


Employee.xml File
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN""http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMap namespace="Employee">
  <insert id="insert" parameterClass="Employee">
    insert into EMPLOYEE(first_name, last_name, salary) values (#first_name#, #last_name#, #salary#)
    <selectKey resultClass = "int" keyProperty="id">
        select last_insert_id() as id
     </selectKey>
  </insert>
  <select id="getAll" resultClass="Employee">
       SELECT * FROM EMPLOYEE
  </select>
  <update id="update" parameterClass="Employee">
      UPDATE EMPLOYEE SET first_name = #first_name# WHERE id = #id#
   </update>
   <delete id="delete" parameterClass="int">
      DELETE FROM EMPLOYEE WHERE id = #id#
   </delete>
   <!-- Using ResultMap -->
   <resultMap id="result" class="Employee">
    <result property="id" column="id"/>
    <result property="first_name" column="first_name"/>
    <result property="last_name" column="last_name"/>
    <result property="salary" column="salary"/>
   </resultMap>
   <select id="useResultMap" resultMap="result">
       SELECT * FROM EMPLOYEE WHERE id=#id#
    </select>
</sqlMap>


Java code to use Result Map
Reader rd = Resources.getResourceAsReader("SqlMapConfig.xml");
SqlMapClient smc = SqlMapClientBuilder.buildSqlMapClient(rd);
int id = 1;
System.out.println("Going to read record.....");
Employee e = (Employee) smc.queryForObject ("Employee.useResultMap", id);
System.out.println("ID: " + e.getId());
System.out.println("First Name: " + e.getFirstName());
System.out.println("Last Name: " + e.getLastName());
System.out.println("Salary: " + e.getSalary());
System.out.println("Record read Successfully ");

No comments:

Post a Comment

Note: only a member of this blog may post a comment.