一個使用MyBatis向Oracle數據庫中新增/批量新增數據的例子

個人電腦操做系統版本爲Win7旗艦版(ServicePack1),Oracle版本爲Oracle11gjava

程序使用的jar包有:mybatis-3.2.2.jar、ojdbc14-10.2.0.2.0.jarsql

本例中使用的配置文件mybatis-config.xml、PersonInfo類以及Oracle數據庫的表結構,能夠參見個人另外一篇Blog《一個簡單的MyBatis鏈接Oracle數據庫的例子》(http://my.oschina.net/Tsybius2014/blog/626206數據庫

PersonInfoMapper.java代碼以下:apache

import java.util.List;

public interface PersonInfoMapper {
    //獲取Sequence做爲插入數據庫中數據的主鍵
    Long getIdFromSequence();
    //插入一條數據
    void addPersonInfo(PersonInfo personInfo);
    //插入多條數據1
    void addPersonInfoBatch(List<PersonInfo> list);
    //插入多條數據2
    void addPersonInfoBatch2(List<PersonInfo> list);
}

對應的XML文件,PersonInfoMapper.xml代碼以下:session

<?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="PersonInfoMapper">

  <!-- 獲取Sequence做爲插入數據庫中數據的主鍵 -->
  <select id="getIdFromSequence" resultType="java.lang.Long" 
    flushCache="true" useCache="false">
    SELECT SEQ_PERSON_INFO.NEXTVAL FROM DUAL
  </select>
  
  <!-- 插入一條數據 -->
  <insert id="addPersonInfo" parameterType="PersonInfo" >
    INSERT INTO PERSON_INFO
      (ID, NAME, GENDER, REMARK, INPUT_DATE, INPUT_TIME)
    VALUES
      (SEQ_PERSON_INFO.NEXTVAL,
       #{name, jdbcType = VARCHAR},
       #{gender, jdbcType = CHAR},
       #{remark, jdbcType = VARCHAR},
       #{inputDate, jdbcType = DECIMAL},
       #{inputTime, jdbcType = DECIMAL})
  </insert>
  
  <!-- 插入多條數據1 -->
  <insert id="addPersonInfoBatch" parameterType="java.util.List" >
      INSERT INTO PERSON_INFO
      (ID, NAME, GENDER, REMARK, INPUT_DATE, INPUT_TIME)
    <foreach collection="list" index="index" item="item" separator="union all">
      (SELECT #{item.id, jdbcType = DECIMAL} AS ID,
              #{item.name, jdbcType = VARCHAR} AS NAME,
              #{item.gender, jdbcType = CHAR} AS GENDER,
              #{item.remark, jdbcType = VARCHAR} AS REMARK,
              #{item.inputDate, jdbcType = DECIMAL} AS INPUT_DATE,
              #{item.inputTime, jdbcType = DECIMAL} AS INPUT_TIME
       FROM DUAL)
    </foreach>
  </insert>
  
  <!-- 插入多條數據2 -->
  <insert id="addPersonInfoBatch2" parameterType="java.util.List" >
      INSERT INTO PERSON_INFO
      (ID, NAME, GENDER, REMARK, INPUT_DATE, INPUT_TIME)
    SELECT A.* FROM (
      <foreach collection="list" index="index" item="item" separator="union all">
        (SELECT #{item.id, jdbcType = DECIMAL} AS ID,
                #{item.name, jdbcType = VARCHAR} AS NAME,
                #{item.gender, jdbcType = CHAR} AS GENDER,
                #{item.remark, jdbcType = VARCHAR} AS REMARK,
                #{item.inputDate, jdbcType = DECIMAL} AS INPUT_DATE,
                #{item.inputTime, jdbcType = DECIMAL} AS INPUT_TIME
         FROM DUAL)
      </foreach>
    ) A
  </insert>
  
</mapper>

插入數據的Java代碼以下:mybatis

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
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;

/**
 * MyBatis 插入數據測試
 * @author Tsybius2014
 * @date 2016年3月4日
 * @time 下午6:18:43
 * @remark
 */
public class MyBatisTest {
    public static void main(String[] args) {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            SqlSession session = sqlSessionFactory.openSession();
            try {
                PersonInfoMapper mapper = session.getMapper(PersonInfoMapper.class);

                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                String currDateTime = simpleDateFormat.format(new Date());
                
                //新增一條數據
                PersonInfo personInfo = new PersonInfo();
                personInfo.setName("Tsybius");
                personInfo.setGender("m");
                personInfo.setRemark("ABCDEFG");
                personInfo.setInputDate(Long.parseLong(currDateTime.substring(0, 8)));
                personInfo.setInputTime(Long.parseLong(currDateTime.substring(8)));
                mapper.addPersonInfo(personInfo);
                System.out.println("插入了1條數據");
                
                //新增多條數據
                List<PersonInfo> personInfoList = new ArrayList<PersonInfo>();
                for (int i = 0; i < 5; i++) {
                    PersonInfo personInfoTmp = new PersonInfo();
                    Long id = mapper.getIdFromSequence();
                    personInfoTmp.setId(id);
                    personInfoTmp.setName("TestPerson" + i);
                    personInfoTmp.setGender("m");
                    personInfoTmp.setRemark("TestMyBatis");
                    personInfoTmp.setInputDate(Long.parseLong(currDateTime.substring(0, 8)));
                    personInfoTmp.setInputTime(Long.parseLong(currDateTime.substring(8)));
                    personInfoList.add(personInfoTmp);
                }
                mapper.addPersonInfoBatch(personInfoList);
                System.out.println("插入了5條數據");
                
                personInfoList.clear();
                for (int i = 0; i < 5; i++) {
                    PersonInfo personInfoTmp = new PersonInfo();
                    Long id = mapper.getIdFromSequence();
                    personInfoTmp.setId(id);
                    personInfoTmp.setName("TestPerson" + i);
                    personInfoTmp.setGender("m");
                    personInfoTmp.setRemark("TestMyBatis");
                    personInfoTmp.setInputDate(Long.parseLong(currDateTime.substring(0, 8)));
                    personInfoTmp.setInputTime(Long.parseLong(currDateTime.substring(8)));
                    personInfoList.add(personInfoTmp);
                }
                mapper.addPersonInfoBatch2(personInfoList);
                System.out.println("又插入了5條數據");
                
                personInfoList.clear();
                for (int i = 0; i < 1000; i++) {
                    PersonInfo personInfoTmp = new PersonInfo();
                    Long id = mapper.getIdFromSequence();
                    personInfoTmp.setId(id);
                    personInfoTmp.setName("TestPerson" + i);
                    personInfoTmp.setGender("m");
                    personInfoTmp.setRemark("TestMyBatis");
                    personInfoTmp.setInputDate(Long.parseLong(currDateTime.substring(0, 8)));
                    personInfoTmp.setInputTime(Long.parseLong(currDateTime.substring(8)));
                    personInfoList.add(personInfoTmp);
                }
                mapper.addPersonInfoBatch(personInfoList);
                System.out.println("插入了1000條數據");
                
            } finally {
                session.commit(); //提交事務,這個步驟必需要有
                session.close();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

程序執行完畢後,在PL/SQL中能夠看到插入的數據app

最後總結下須要注意的點:測試

一、在 PersonInfoMapper.xml 中配置的 getIdFromSequence 方法,必需要指定屬性 flushCache="true" 和 useCache="false",不然在取序列值時結果會出錯。ui

二、在使用MyBatis中的foreach標籤時,記住指定了item後,不要把「#{item.name, jdbcType = VARCHAR}」寫成「#{name, jdbcType = VARCHAR} 」,在這個地方我吃過好屢次虧了。spa

END

相關文章
相關標籤/搜索