MyBatis3入门一(简单查询、插入)

1. 环境

mybatis-3.2版本,jdk1.6版本,Oracle数据库

2. 功能

实现基本的数据单条插入、单条查询功能。

3. 准备工作

3.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   

3.2 项目的目录结构

src\com\clzhang\sample\struts2\mapper           
  MemberUserMapper.java               mybatis的mapper处理类 src\com\clzhang\sample\struts2\mapper\entity
  MemberUserBean.java                mybatis的entity类 src\com\clzhang\sample\struts2\test
  MyBatisTest.java                  测试类,最终应该是在service的package中调用mapper中的方法。 resources\config
  mybatis
-config.xml mybatis的配置文件
resources\com\clzhang\sample\struts2\mapper
  MemberUserMapper.xml mybatis的mapper配置文件

3.3 假定数据库已经创建,表结构也已经创建,并且有测试数据

这里数据库为Oracle,表名:MEMBER_USER,数据结构如下(假设已经存在测试数据):

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

4. 具体步骤

4.1 创建entity类

package com.clzhang.sample.struts2.mapper.entity;

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

    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;
    }

}

4.2 创建mapper类

package com.clzhang.sample.struts2.mapper;

import com.clzhang.sample.struts2.mapper.entity.MemberUserBean;

public interface MemberUserMapper {
    public void insertUser(MemberUserBean user);    
    public MemberUserBean getUser(int id); 
}

4.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.sample.struts2.mapper.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:@192.168.2.136:1521:jingdu"/> 
              <property name="username" value="jingdu"/> 
              <property name="password" value="jingdu"/> 
           </dataSource> 
       </environment> 
    </environments> 
    <mappers> 
        <mapper resource="com/clzhang/sample/struts2/mapper/MemberUserMapper.xml" /> 
    </mappers> 
</configuration>

4.4 创建MemberUserMapper.xml配置文件,位置于:resources\com\clzhang\sample\struts2\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.sample.struts2.mapper.MemberUserMapper">

  <cache />

  <select id="getUser" resultType="MemberUser" parameterType="int">
    select
      ID,
      NAME,
      PERSONMOBILE,
      PERSONREMARK,
      ADDRESS
    FROM MEMBER_USER
    WHERE ID = #{id}
  </select>

  <insert id="insertUser" parameterType="MemberUser">
    INSERT INTO MEMBER_USER (ID, NAME, PERSONMOBILE, ADDRESS)
    VALUES(#{id}, #{name}, #{personMobile}, #{address})
  </insert>

</mapper>

 4.5 创建测试类 

package com.clzhang.sample.struts2.test;

import java.io.IOException;
import java.io.Reader;

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.sample.struts2.mapper.MemberUserMapper;
import com.clzhang.sample.struts2.mapper.entity.MemberUserBean;

/**
 * mybatis的测试类,真正的应用,应该在service包中调用。
 * @author Administrator
 *
 */
public class MyBatisTest {
    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 testAdd() {
        // SqlSession 的实例不能被共享,也是线程不安全的。因此最佳的范围是请求或方法范围。
        SqlSession sqlSession = getSqlSessionFactory().openSession();
        try {
            // 从技术上来说,当被请求时,任意映射器实例的最宽范围和 SqlSession 是相同的。最佳范围是方法范围。
            MemberUserMapper mapper = sqlSession
                    .getMapper(MemberUserMapper.class);
            
            MemberUserBean memberUser = new MemberUserBean();
            memberUser.setId(1003);
            memberUser.setName("张三");
            memberUser.setPersonMobile("18387887878");
            memberUser.setAddress("北京丰台某公司");
            
            mapper.insertUser(memberUser);
            sqlSession.commit();
        } finally {
            sqlSession.close();
        }
    }

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

}

测试输出:

name:吴经理 mobile:13695769533 address:浙江省乐清市北白象金炉工业区

posted @ 2013-03-08 11:55  那些年的事儿  阅读(780)  评论(0编辑  收藏  举报