Tutorial: MyBatis using Java

Posted by Yan on March 4, 2015

MyBatis is a widely used light-weight ORM tool. MyBatis can use XML or Java Annotations for configure all Jdbc, sql mapping and POJOs to database.

mybatis

In this tutorial, I will create a simple program to demonstrate how to setup a java project with MyBatis.

Create a MyBaits project

The tools used:

  1. Create database:
    CREATE TABLE userinfo
    (
      uid serial NOT NULL,
      username character varying(100) NOT NULL,
      password character varying(500) NOT NULL,
      created date,
      CONSTRAINT user_pkey PRIMARY KEY (uid),
      CONSTRAINT unq_username UNIQUE (username)
    )
  2. Create a maven project and setup the dependencies:
    ...
     	<dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.2.8</version>
            </dependency>
    
            <dependency>
                <groupId>postgresql</groupId>
                <artifactId>postgresql</artifactId>
                <version>9.1-901.jdbc4</version>
            </dependency>
    ...
  3. Create the jdbc.properties in main/resources
    jdbc.driverClassName=org.postgresql.Driver
    jdbc.url=jdbc:postgresql://your_db_hosting_address/your_db_name
    jdbc.username=yourusername
    jdbc.password=userpassword
  4. Setup the mybatis configuration file mybatis-config.xml in main/resources
    Note: we have set a alias which map UserInfo.java to User.
    <?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>
        <properties resource='jdbc.properties'/>
        <typeAliases>
            <typeAlias type='com.learnBatis.UserInfo' alias='User'></typeAlias>
        </typeAliases>
        <environments default='development'>
            <environment id='development'>
                <transactionManager type='JDBC'/>
                <dataSource type='POOLED'>
                    <property name='driver' value='${jdbc.driverClassName}'/>
                    <property name='url' value='${jdbc.url}'/>
                    <property name='username' value='${jdbc.username}'/>
                    <property name='password' value='${jdbc.password}'/>
                </dataSource>
            </environment>
        </environments>
        <mappers>
            <mapper resource='mappers/UserMapper.xml'/>
        </mappers>
    </configuration>
  5. Setup the UserMapper.xml in main/resources/mappers (You can use Java Annotation instead of XML as well)
    <?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.learnBatis.UserMapper'>
    
        <select id='getUserById' parameterType='int' resultType='com.learnBatis.UserInfo'>
            SELECT uid, username, password, created from userinfo where uid = #{userid}
        </select>
        <resultMap type='User' id='UserResult'>
            <id property='uid' column='uid'/>
            <result property='username' column='username'/>
            <result property='password' column='password'/>
            <result property='created' column='created'/>
        </resultMap>
    
        <select id='getAllUsers' resultMap='UserResult'>
            SELECT * FROM USERINFO
        </select>
    
        <insert id='insertUser' parameterType='User' useGeneratedKeys='true' keyProperty='userId'>
            INSERT INTO USERINFO(uid, username, password, created)
            VALUES(#{uid}, #{username}, #{password}, #{created})
        </insert>
    
        <update id='updateUser' parameterType='User'>
            UPDATE USERINFO
            SET
            PASSWORD= #{password},
            USERNAME = #{username}
            CREATED = #{created},
            WHERE UID = #{uid}
        </update>
    
        <delete id='deleteUser' parameterType='int'>
            DELETE FROM USERINFO WHERE UID = #{userId}
        </delete>
    
    </mapper>
  6. Create the model Object UserInfo.class in main/java/com/learnBatis
    package com.learnBatis;
    
    public class UserInfo
    {
        private int uid;
        private String username;
        private String password;
        private String created;
    
        @Override
        public String toString()
        {
            return "user name: " + username + ", pwd: " + password + ", Created: " + created;
        }
    }
  7. Create the mapper interface UserMapper.interface in main/java/com/learnBatis
    package com.learnBatis;
    
    import java.util.List;
    
    public interface UserMapper
    {
        public void insertUser(UserInfo user);
        public UserInfo getUserById(Integer userid);
        public List<UserInfo> getAllUsers();
        public void updateUser(UserInfo user);
        public void deleteUser(Integer userid);
    }
  8. Now, we need setup the connection to the db by creating the MyBatisUtil.class in com.learnBatis package
    package com.learnBatis;
    
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    
    import java.io.IOException;
    import java.io.Reader;
    
    public class MyBatisUtil
    {
        private static SqlSessionFactory factory;
    
        private MyBatisUtil() {
        }
    
        static
        {
            Reader reader = null;
            try {
                reader = Resources.getResourceAsReader("mybatis-config.xml");
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage());
            }
            factory = new SqlSessionFactoryBuilder().build(reader);
        }
    
        public static SqlSessionFactory getSqlSessionFactory()
        {
            return factory;
        }
    
    }
  9. We need use the mapper to query the db, so we create a UserService.class in com.learnBatis
    package com.learnBatis;
    
    import org.apache.ibatis.session.SqlSession;
    
    import java.util.List;
    
    public class UserService
    {
    
        public void insertUser(UserInfo user)
        {
            SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
            try
            {
                UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
                userMapper.insertUser(user);
    
                sqlSession.commit();
            }
            finally
            {
                sqlSession.close();
            }
        }
    
        public UserInfo getUserById(Integer userid)
        {
        	...
        }
    
        public List<UserInfo> getAllUsers()
        {
            SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
            try
            {
                UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    
                return userMapper.getAllUsers();
            }
            finally
            {
                sqlSession.close();
            }
        }
    
        public void updateUser(UserInfo user)
        {
        	...
        }
    
        public void deleteUser(Integer userid)
        {
        	...
        }
    }

Use MyBatis SQLMapper

Here, we has completed all the tasks needed for setting up MyBatis to our psql database. To test our program, we can simply write a Main.class:

package com.learnBatis;

import java.util.List;

public class Main
{
    public static void main(String[] args)
    {
        UserService userService = new UserService();

        List<UserInfo> users = userService.getAllUsers();
        for (UserInfo u : users)
        {
            System.out.println(u.toString());
        }
    }
}

The output will be like:

user name: test0, pwd: testpwd, Created: 2015-02-09
user name: test1, pwd: testpwd2, Created: 2015-02-10