Creating CRUD service using MyBatis 3 Mapping Framework – Part 1

In first step of our tutorial series, Spring MVC 3 CRUD example with MyBatis 3, we will define a MyBatis service that will help us to perform CRUD operation on database. We have a domain class for User and a database table to store the User information on database. We will use xml configuration model for our example to define SQL commands that will perform CRUD operation.

Our Domain class


package com.raistudies.domain;

import java.io.Serializable;

public class User implements Serializable{

    private static final long serialVersionUID = 3647233284813657927L;

    private String id;
    private String name = null;
    private String standard = null;
    private String age;
    private String sex = null;

    //setter and getter have been omitted to make the code short

    @Override
    public String toString() {
        return "User [name=" + name + ", standard=" + standard + ", age=" + age
        + ", sex=" + sex + "]";
    }
}

We have five properties in our domain class called User for which have to provide database services.

Our Database Table

Following is our database table:


CREATE TABLE `user` (
    `id` varchar(36) NOT NULL,
    `name` varchar(45) DEFAULT NULL,
    `standard` varchar(45) DEFAULT NULL,
    `age` varchar(45) DEFAULT NULL,
    `sex` varchar(45) DEFAULT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

Creating interface for CRUD operations

For defining the CRUD database operation using MyBatis 3, we have to specify the methods that will be used to perform CRUD operation. Following is the interface for our example:


package com.raistudies.persistence;

import java.util.List;

import com.raistudies.domain.User;

public interface UserService {

    public void saveUser(User user);
    public void updateUser(User user);
    public void deleteUser(String id);
    public List<User> getAllUser();
}

We have four methods here to perform operations create,update , delete and get from database.

XML Mapping file for UserService interface


<?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.raistudies.persistence.UserService">

    <resultMap id="result" type="user">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="standard" column="standard"/>
        <result property="age" column="age"/>
        <result property="sex" column="sex"/>
    </resultMap>

    <select id="getAllUser" parameterType="int" resultMap="result">
        SELECT id,name,standard,age,sex
        FROM user;
    </select>

    <insert id="saveUser" parameterType="user">
        INSERT INTO user (id,name,standard,age,sex)
        VALUE (#{id},#{name},#{standard},#{age},#{sex})
    </insert>

    <update id="updateUser" parameterType="user">
        UPDATE user
        SET
        name = #{name},
        standard = #{standard},
        age = #{age},
        sex = #{sex}
        where id = #{id}
    </update>

    <delete id="deleteUser" parameterType="int">
        DELETE FROM user
        WHERE id = #{id}
    </delete>
</mapper>

You will see a lot of things new here:

The mapping file will contain element <mapper/> to define the SQL statement for the services. Here the property namespace defines the interface for which this mapping file has been defined.

<insert/> tag defines that the operation is of type insert. The value of id property specifies the function name for which the SQL statement is been defined. Here it is “saveUser“. The property parameterType defines the parameter of the method is of which type. We have used alias for the class User here. The alias will be configured in MyBatis Configuration file later. Then, we have to define the SQL Statement. #{id} defines that the property id of class User will be passed as a parameter to the SQL query.

<resultMap/> tag is used to specify the mapping between the User class and user table. id of <resultMap/> is a unique name to the mapping definition. Under this tag, we define the different properties and which column is bounded to which property.

<select/> tag is used to specify a select SQL statement. The value of id property specifies the function name for which the SQL statement is been defined.

The attribute resultMap is used to define the return type of the SQL statement as a collection.

MyBatis 3 Configuration file

Following is our configuration file for MyBatis:


<?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>
    <settings>
        <!-- changes from the defaults -->
       <setting name="lazyLoadingEnabled" value="false" />
    </settings>
    <typeAliases>
        <typeAlias type="com.raistudies.domain.User" alias="user"/>
    </typeAliases>
</configuration>

You can see, we have not defined some very important properties here:

  1. Database connection properties.
  2. Transaction related properties.
  3. And also have not defined mappers configuration.

All these properties will be provided by Spring Framework later when we will integrate it with the Spring.

Related Posts:

Leave a comment ?

1 Comments.

  1. It’s a really great and helpful job.
    Thank u a lot and keep on writing buddy 😆

Leave a Comment Cancel reply

NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>