Tuesday 24 November 2015

MyBatis

MyBatis is a first class persistence framework with support for custom SQL, stored procedures and advanced mappings. MyBatis eliminates almost all of the JDBC code and manual setting of parameters and retrieval of results. MyBatis can use simple XML or Annotations for configuration and map primitives, Map interfaces and Java POJOs (Plain Old Java Objects) to database records.

Simple example:

1. database.properties

db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/mydb
db.username= ************
db.password= ************


2. configuration.xml

<configuration>
    <properties resource="database.properties"/>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${db.driver}"/>
                <property name="url" value="${db.url}"/>
                <property name="username" value="${db.username}"/>
                <property name="password" value="${db.password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/mybatis/demo/user/UserMapper.xml"/>
    </mappers>
</configuration>

3. UserMapper.xml

<?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.mybatis.my.user.dao.UserDAO"></mapper>

4. ConnectionFactory Class

package com.mybatis.my.util;

import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class ConnectionFactory {
    private static SqlSessionFactory sqlMapper;
    private static Reader reader;
    static{
        try{
            reader    = Resources.getResourceAsReader("configuration.xml");
            sqlMapper = new SqlSessionFactoryBuilder().build(reader);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    public static SqlSessionFactory getSession(){
        return sqlMapper;
    }
}

5. UserVO Class

package com.mybatis.my.user.vo;

import java.io.Serializable;


public class UserVO implements Serializable {
    
    private static final long serialVersionUID = 4872640461000241018L;
    private long id;
    private String fullName;
    private String address;
    private String email;
    private String mobile;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getFullName() {
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
    
     @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        UserVO other = (UserVO) obj;
        if (fullName == null) {
            if (other.fullName != null)
                return false;
        } else if (!fullName.equals(other.fullName))
            return false;
        if (id != other.id)
            return false;
        return true;
    }

}


6. UserDAO Interface


package com.mybatis.my.user.dao;

import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.mybatis.my.user.vo.UserVO;

public interface UserDAO {
    String MQL_GET_ALL_USERS  = "select * from users";
    String MQL_GET_USER_BY_ID = "select * from users where id = #{id}";
    String MQL_CREATE_USER    = "insert into users (fullName, email, address, mobile) values (#{fullName},#{email},#{address},#{mobile})";
    String MQL_UPDATE_USER    = "update users set fullName=#{fullName}, email=#{email}, address=#{address}, mobile=#{mobile} where id=#{id}";
    String MQL_DELETE_USER    = "delete from users where id=#{id}";
    @Select(MQL_GET_ALL_USERS)
    public List<uservo> getAllUsers() throws Exception;
    @Select(MQL_GET_USER_BY_ID)
    public UserVO getUserById(long id) throws Exception;
    @Insert(MQL_CREATE_USER)
    public int doCreateUser(UserVO vo) throws Exception;
    @Update(MQL_UPDATE_USER)
    public int doUpdateUser(UserVO vo) throws Exception;
    @Delete(MQL_DELETE_USER)
    public int doDeleteUser(UserVO vo) throws Exception; 
}



7. UserBO Class

package com.mybatis.my.user.bo;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import com.mybatis.my.util.ConnectionFactory;
import com.mybatis.my.user.dao.UserDAO;
import com.mybatis.my.user.vo.UserVO;

public class UserBO {
    public List<uservo> getUsers() throws Exception{
        SqlSession session = ConnectionFactory.getSession().openSession();
            UserDAO dao =session.getMapper(UserDAO.class);
            List<uservo> users= dao.getAllUsers();
        session.close();
        return users;
    }
    public UserVO getUserById(long id) throws Exception{
        SqlSession session = ConnectionFactory.getSession().openSession();
            UserDAO dao =session.getMapper(UserDAO.class);
            UserVO user =dao.getUserById(id);
        session.close();
        return user;
    }
    public UserVO createUser(UserVO vo) throws Exception{
        SqlSession session = ConnectionFactory.getSession().openSession();
            UserDAO dao =session.getMapper(UserDAO.class);
            dao.doCreateUser(vo);
        session.commit();
        session.close();
        return vo;
    }
    public UserVO updateUser(UserVO vo) throws Exception{
        SqlSession session = ConnectionFactory.getSession().openSession();
            UserDAO dao =session.getMapper(UserDAO.class);
            dao.doUpdateUser(vo);
        session.commit();
        session.close();
        return vo;
    }
    public int deleteUser(UserVO vo) throws Exception{
        SqlSession session = ConnectionFactory.getSession().openSession();
            UserDAO dao =session.getMapper(UserDAO.class);
            int cnt= dao.doDeleteUser(vo);
        session.commit();
        session.close();
        return cnt;
    }
    public static void main(String a[])throws Exception{
        UserBO bo = new UserBO();
        UserVO vo= new UserVO();
        vo.setAddress("Test");
        vo.setEmail("test@gmail.com");
        vo.setFullName("Full Name");
        vo.setMobile("12411515");
        System.out.println(bo.createUser(vo));
        System.out.println(bo.getUsers());
        vo= bo.getUserById(1);
        vo.setAddress("Test Updated11 Address");
        vo.setEmail("testupdated@gmail.com");
        vo.setFullName("Full Name Test");
        vo.setMobile("1241151511");
        bo.updateUser(vo);
        vo=bo.getUserById(1);
        System.out.println(vo);
        bo.deleteUser(vo);
    }

}

No comments:

Post a Comment