1. 程式人生 > 其它 >重新整理,MyBatis3之初步,實體的增加、修改、刪除、查詢

重新整理,MyBatis3之初步,實體的增加、修改、刪除、查詢

一、環境

mybatis-3.2版本,jdk1.8版本,Oracle資料庫

二、準備工作

1. 下載mybatis-3.2,需要引用其中的若干包

mybatis-3.2.0.jar
    lib/asm-3.3.1.jar
    lib/cglib-2.2.2.jar
    lib/commons-logging-1.1.1.jar
    lib/javassist-3.17.1-GA.jar
    lib/log4j-1.2.17.jar
    lib/slf4j-api-1.7.2.jar
    lib/slf4j-log4j12-1.7.2.jar

2 專案的目錄結構

com.clzhang.mybatis.mapper      MemberUserMapper.java          MyBatis的mapper處理類
com.clzhang.mybatis.entity      MemberUserBean.java           MyBatis的entity類
com.clzhang.test                MyBatisTest1.java            測試類,最終應該是在service的package中呼叫mapper中的方法。


resources\config  mybatis
-config.xml MyBatis的配置檔案 resources\com\clzhang\mybatis\mapper  MemberUserMapper.xml MyBatis的mapper配置檔案

3.假定資料庫已經建立,表結構也已經建立,並且有測試資料

CREATE TABLE MEMBER_USER (
ID NUMBER NOT NULL PRIMARY KEY,
NAME VARCHAR2(30),
PERSONMOBILE VARCHAR2(20),
ADDRESS VARCHAR2(255),
AGE NUMBER);

CREATE SEQUENCE SEQ_MEMBER_USER;

三、具體步驟

1. 建立entity類

package com.clzhang.mybatis.entity;

public class MemberUserBean {
    private int id;
    private String name;
    private String personMobile;
    private String address;
    private int age;

    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 String getPersonMobile() { return personMobile; } public void setPersonMobile(String personMobile) { this.personMobile = personMobile; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
View Code

2.建立mapper類

package com.clzhang.mybatis.mapper;

import java.util.*;
import com.clzhang.mybatis.entity.MemberUserBean;

public interface MemberUserMapper {
    public void insertUser(MemberUserBean user);    
    public void updateUser(MemberUserBean user);    
    public void deleteUser(int id);    
    public MemberUserBean getUser(int id); 
    public HashMap getUserHashMap(int id); 
    public List getUsersByAge(int startAge, int endAge); 
}
View Code

3.建立mybatis-config.xml的配置檔案,位置於resources/config目錄

<?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> 
        <setting name="cacheEnabled" value="false" /> 
        <setting name="useGeneratedKeys" value="true" /> 
        <setting name="defaultExecutorType" value="REUSE" /> 
    </settings> 
    <typeAliases> 
       <typeAlias alias="MemberUser" type="com.clzhang.mybatis.entity.MemberUserBean"/> 
    </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="mytest"/> 
              <property name="password" value="test001"/> 
           </dataSource> 
       </environment> 
    </environments> 
    <mappers> 
        <mapper resource="com/clzhang/mybatis/mapper/MemberUserMapper.xml" /> 
    </mappers> 
</configuration>

4.建立MemberUserMapper.xml配置檔案,位置於:resources\com\clzhang\mybatis\mapper\

<?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.clzhang.mybatis.mapper.MemberUserMapper">
    <!--
    預設情況下是沒有開啟快取的,下條程式碼是開啟二級快取的,作用如下:
    1.•對映語句檔案中的所有 select 語句將會被快取。
    2.•對映語句檔案中的所有 insert,update 和 delete 語句會重新整理快取。
    3.•快取會使用 Least Recently Used(LRU,最近最少使用的)演算法來收回。
    ......
    -->
    <cache />
    
    <!--以單個物件方式返回-->
    <select id="getUser" resultType="MemberUser" parameterType="int">
    select
      ID,
      NAME,
      PERSONMOBILE,
      ADDRESS,
      AGE
      FROM MEMBER_USER
    WHERE ID = #{id}
    </select>

    <!--以HashMap方式返回單個例項,包含列名與值的對映-->
    <select id="getUserHashMap" resultType="hashmap" parameterType="int">
    select
      ID,
      NAME,
      PERSONMOBILE,
      ADDRESS,
      AGE
      FROM MEMBER_USER
    WHERE ID = #{id}
    </select>

    <resultMap type="MemberUser" id="userAgeMap">  
        <id property="id" column="id"/>  
        <!--有需要做資料庫到實體類名稱轉換的,可以寫在這裡-->
        <!--
        <result property="objname" column="dbname"/>
        -->
    </resultMap>  

    <!--以List方式返回多個結果-->
    <!--引數名稱目前不可以自行指定(無法與Mapper中保持一致),待查-->
    <select id="getUsersByAge" resultMap="userAgeMap" parameterType="int">
    <![CDATA[
    select
      ID,
      NAME,
      PERSONMOBILE,
      ADDRESS,
      AGE
      FROM MEMBER_USER
    WHERE AGE > #{param1} AND AGE < #{param2}
    ]]>
    </select>
    
    <!--Oracle的實現自增長主鍵的方式-->
    <insert id="insertUser" parameterType="MemberUser">
    <selectKey keyProperty="id" resultType="int" order="BEFORE">
      select SEQ_MEMBER_USER.nextval from DUAL
    </selectKey>
      INSERT INTO MEMBER_USER (ID, NAME, PERSONMOBILE, ADDRESS, AGE)
      VALUES(#{id}, #{name}, #{personMobile}, #{address}, #{age})
    </insert>

    <update id="updateUser" parameterType="MemberUser">
      update MEMBER_USER set
        NAME = #{name},
        PERSONMOBILE = #{personMobile},
        ADDRESS = #{address},
        AGE = #{age}
      where id = #{id}
    </update>

    <delete id="deleteUser" parameterType="int">
      delete from MEMBER_USER where ID = #{id}
    </delete>
</mapper>

5.建立測試類

package com.clzhang.test;

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

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 org.junit.Test;

import com.clzhang.mybatis.mapper.MemberUserMapper;
import com.clzhang.mybatis.entity.MemberUserBean;

/**
 * mybatis的測試類,真正的應用,應該在service包中呼叫。
 * @author Administrator
 *
 */
public class MyBatisTest1 {
    private static final String MYBATIS_CONFIG_FILENAME = "config/mybatis-config.xml";
    private static SqlSessionFactory sqlSessionFactory;
    
    static {
        Reader reader = null;
        try {
            reader = Resources.getResourceAsReader(MYBATIS_CONFIG_FILENAME);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        // 一旦你建立了 SqlSessionFactory 後,SqlSessionFactoryBuilder這個類就不需要存在了。
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
    }
    
    /**
     * SqlSessionFactory 應該在你的應用執行期間都存在。沒有理由來處理或重新建立它。
     * @return
     */
    public static SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }

//    @Test
    public void testInert() {
        // SqlSession 的例項不能被共享,也是執行緒不安全的。因此最佳的範圍是請求或方法範圍。
        SqlSession sqlSession = getSqlSessionFactory().openSession();
        try {
            // 從技術上來說,當被請求時,任意對映器例項的最寬範圍和 SqlSession 是相同的。最佳範圍是方法範圍。
            MemberUserMapper mapper = sqlSession
                    .getMapper(MemberUserMapper.class);
            
            MemberUserBean memberUser = new MemberUserBean();
            // 因為ID為自增長欄位,所以此處不需要設定
            memberUser.setName("李勇");
            memberUser.setPersonMobile("998877");
            memberUser.setAddress("江蘇某地方");
            memberUser.setAge(38);
            
            mapper.insertUser(memberUser);
            sqlSession.commit();
            
            // 檢視新加的物件主鍵
            System.out.println("新加物件的id:" + memberUser.getId());
        } finally {
            sqlSession.close();
        }
    }

//  @Test
  public void testUpdate() {
      SqlSession sqlSession = getSqlSessionFactory().openSession();
      try {
          MemberUserMapper mapper = sqlSession
                  .getMapper(MemberUserMapper.class);
          
          // 先查詢,後更新
          MemberUserBean memberUser = mapper.getUser(8);
          memberUser.setName("趙五副本");
          memberUser.setPersonMobile("12345");
          memberUser.setAddress("天津上地某公司");
          memberUser.setAge(29);
          
          mapper.updateUser(memberUser);
          sqlSession.commit();
      } finally {
          sqlSession.close();
      }
      }
  
//    @Test
    public void testDelete() {
        SqlSession sqlSession = getSqlSessionFactory().openSession();
        try {
            MemberUserMapper mapper = sqlSession.getMapper(MemberUserMapper.class);

            // 直接設定ID主鍵,然後刪除
            mapper.deleteUser(2);
            sqlSession.commit();
        } finally {
            sqlSession.close();
        }
    }

//    @Test
    public void getUser() {
        SqlSession sqlSession = getSqlSessionFactory().openSession();
        try {
            MemberUserMapper mapper = sqlSession
                    .getMapper(MemberUserMapper.class);
            MemberUserBean memberUser = mapper.getUser(5);
            
            System.out.println("name:" + memberUser.getName() + "\tmobile:"
                    + memberUser.getPersonMobile() + "\taddress:" + memberUser.getAddress());
        } finally {
            sqlSession.close();
        }
    }

//    @Test
    public void getUserHashMap() {
        SqlSession sqlSession = getSqlSessionFactory().openSession();
        try {
            MemberUserMapper mapper = sqlSession
                    .getMapper(MemberUserMapper.class);
            HashMap<String, Object> hashMap = mapper.getUserHashMap(5);
            for (Map.Entry<String, Object> entry : hashMap.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                
                System.out.println(key + ":" + value);
            }
        } finally {
            sqlSession.close();
        }
    }

    @Test
    public void getUserByAge() {
        SqlSession sqlSession = getSqlSessionFactory().openSession();
        try {
            MemberUserMapper mapper = sqlSession
                    .getMapper(MemberUserMapper.class);
            List<MemberUserBean> myList = mapper.getUsersByAge(20, 40);
            for (MemberUserBean entry : myList) {
                int key = entry.getId();
                String value = entry.getAddress();

                System.out.println(key + ":" + value);
            }
        } finally {
            sqlSession.close();
        }
    }    
}

四、單獨測試各個模組

解除註釋JUnit各單元,然後鍵盤輸入:alt+shift+X,T,分別進行測試。