Mybatis使用(一)


mybitsベースのシンプルなCRUD機能:
   1.試験表の作成:
create table t_fruit(id number(8),name varchar2(50),price float(10));

   2.エンティティークラスの作成
package com.mybatistest.orm;

import java.io.Serializable;

public class Fruit implements Serializable {

    private static final long serialVersionUID = 1L;
    private int id;
    private String name;
    private Float price;

    public Fruit() {

    }

    public Fruit(int id, String name, Float price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Float getPrice() {
        return price;
    }

    public void setPrice(Float price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "    :" + name + "    :" + price +"/kg";
    }

}

   3.ソリッドマッピングインタフェースの作成
package com.mybatistest.orm;

import java.util.List;
import org.apache.ibatis.annotations.Param;

public interface FruitMapper {
    
    public int insertFruit(Fruit fruit);
    public int deleteFruit(int id);
    public int updateFruit(@Param(value = "fruit") Fruit fruit);
    public List<Fruit> queryList(@Param(value = "fruit") Fruit fruit);
}

   4.マッピングプロファイルの作成
<?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.mybatistest.orm.FruitMapper">

    <!--id      FruitMaper          -->
    <insert id="insertFruit" parameterType="Fruit">
        insert into
        t_fruit(id,name,price) values(#{id},#{name},#{price})
    </insert>
    <!--      -->
    <update id="updateFruit" parameterType="Fruit">
        update t_fruit
        <set>
            <if test="fruit.name != null and fruit.name !='' ">name=#{fruit.name},</if>
            <if test="fruit.price != null and fruit.price!='' ">price=#{fruit.price}</if>
        </set>
        where id=#{fruit.id}
    </update>
    <!--      -->
    <delete id="deleteFruit" parameterType="java.lang.Integer">
        delete from t_fruit where id=#{id}
    </delete>
    <!--      -->
    <select id="queryList" resultType="Fruit">
        select * from t_fruit where 1=1
        <if test="fruit.id!='' and fruit.id!=null ">
            and age=#{fruit.id}
        </if>
        <if test="fruit.name!='' and fruit.name!=null ">
            and name=#{fruit.name}
        </if>
        <if test="fruit.price!='' and fruit.price!=null ">
            and age=#{fruit.price}
        </if>
    </select>
</mapper>

   5.データベース接続ファイルを作成し、マッピングプロファイルを追加 
<?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>
    <typeAliases>
        <typeAlias alias="Fruit" type="com.mybatistest.orm.Fruit" />
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="oracle.jdbc.driver.OracleDriver" />
                <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl" />
                <property name="username" value="****" />
                <property name="password" value="*******" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/mybatistest/orm/FruitMapper.xml" />
    </mappers>
</configuration>

  6.javaテストクラスの作成
package com.mybatistest.test;

import java.io.IOException;
import java.io.Reader;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.mybatistest.orm.Fruit;
import com.mybatistest.orm.FruitMapper;


public class LauncherFruit {

    private final static SqlSessionFactory sqlSessionFactory;
    static {
        String resource = "com/mybatistest/test/mybatis-config.xml";
        Reader reader = null;
        try {
            reader = Resources.getResourceAsReader(resource);
        } catch (IOException e) {
            System.out.println("Msg:" + e.getMessage());

        }
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
    }

    /**
     *     
     */
    public static void addFruit() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            FruitMapper fruitMapper = sqlSession.getMapper(FruitMapper.class);
            Fruit fruit = new Fruit(3, "  ", new Float(1.3));
            int result = fruitMapper.insertFruit(fruit);
            sqlSession.commit();//       
            if (result > 0) {
                System.out.println("{'success:',true}");
            }
        } finally {
            sqlSession.close();
        }
    };

    /**
     *     
     */
    public static void updateFruit() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            FruitMapper fruitMapper = sqlSession.getMapper(FruitMapper.class);
            Fruit fruit = new Fruit(3, "  ", new Float(1.6));
            int result = fruitMapper.updateFruit(fruit);
            sqlSession.commit();
            if (result > 0) {
                System.out.println("{'success:',true}");
            }
        } finally {
            sqlSession.close();
        }
    };

    /**
     *     
     */
    public static void queryFruit() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            FruitMapper fruitMapper = sqlSession.getMapper(FruitMapper.class);
            Fruit fruit = new Fruit();
            List<Fruit> fruitList = fruitMapper.queryList(fruit);
            for (int i = 0; i < fruitList.size(); i++) {
                System.out.println(fruitList.get(i).toString());
            }

        } finally {
            sqlSession.close();
        }
    }

    /**
     *     
     */
    public static void deleteFruit() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            FruitMapper fruitMapper = sqlSession.getMapper(FruitMapper.class);
            int result = fruitMapper.deleteFruit(1);
            sqlSession.commit();
            if (result > 0) {
                System.out.println("{'success:',true}");
            }
        } finally {
            sqlSession.close();
        }
    }

    public static void main(String[] args) throws IOException {
        // addFruit();
         queryFruit();
        // updateFruit();
        // deleteFruit();
    }
}