mybatis环境的搭建

Posted 沙弥

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mybatis环境的搭建相关的知识,希望对你有一定的参考价值。

项目模型:

 

一、创建一个web项目ssm001

1、1准备数据

在数据创建表并添加数据

user表:

dept表:

/*
Navicat mysql Data Transfer

Source Server         : ybt
Source Server Version : 50137
Source Host           : 127.0.0.1:3306
Source Database       : ssm001

Target Server Type    : MYSQL
Target Server Version : 50137
File Encoding         : 65001

Date: 2016-11-16 22:35:47
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for dept
-- ----------------------------
DROP TABLE IF EXISTS `dept`;
CREATE TABLE `dept` (
  `DEPTNO` decimal(4,0) DEFAULT NULL,
  `DNAME` varchar(14) DEFAULT NULL,
  `LOC` varchar(13) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of dept
-- ----------------------------
INSERT INTO `dept` VALUES (\'10\', \'ACCOUNTING\', \'NEW YORK\');
INSERT INTO `dept` VALUES (\'20\', \'RESEARCH\', \'DALLAS\');
INSERT INTO `dept` VALUES (\'30\', \'SALES\', \'CHICAGO\');
INSERT INTO `dept` VALUES (\'40\', \'OPERATIONS\', \'BOSTON\');

emp表:

/*
Navicat MySQL Data Transfer

Source Server         : ybt
Source Server Version : 50137
Source Host           : 127.0.0.1:3306
Source Database       : ssm001

Target Server Type    : MYSQL
Target Server Version : 50137
File Encoding         : 65001

Date: 2016-11-16 22:36:14
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for emp
-- ----------------------------
DROP TABLE IF EXISTS `emp`;
CREATE TABLE `emp` (
  `EMPNO` decimal(4,0) NOT NULL,
  `ENAME` varchar(10) DEFAULT NULL,
  `JOB` varchar(9) DEFAULT NULL,
  `MGR` decimal(4,0) DEFAULT NULL,
  `HIREDATE` date DEFAULT NULL,
  `SAL` decimal(7,2) DEFAULT NULL,
  `COMM` decimal(7,2) DEFAULT NULL,
  `DEPNO` decimal(4,0) DEFAULT NULL,
  PRIMARY KEY (`EMPNO`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of emp
-- ----------------------------
INSERT INTO `emp` VALUES (\'7369\', \'SMITH\', \'CLERK\', \'7902\', \'1980-12-17\', \'1800.00\', null, \'20\');
INSERT INTO `emp` VALUES (\'7499\', \'ALLEN\', \'SALESMAN\', \'7698\', \'1981-02-20\', \'1600.00\', \'300.00\', \'30\');
INSERT INTO `emp` VALUES (\'7521\', \'WARD\', \'SALESMAN\', \'7698\', \'1981-02-22\', \'1250.00\', \'500.00\', \'30\');
INSERT INTO `emp` VALUES (\'7566\', \'JONES\', \'MANAGER\', \'7839\', \'1981-04-02\', \'2975.00\', null, \'20\');
INSERT INTO `emp` VALUES (\'7654\', \'MARTIN\', \'SALESMAN\', \'7698\', \'1981-09-28\', \'1250.00\', \'1400.00\', \'30\');
INSERT INTO `emp` VALUES (\'7698\', \'BLAKE\', \'MANAGER\', \'7839\', \'1981-05-01\', \'2850.00\', null, \'30\');
INSERT INTO `emp` VALUES (\'7782\', \'CLARK\', \'MANAGER\', \'7839\', \'1981-06-09\', \'2450.00\', null, \'10\');
INSERT INTO `emp` VALUES (\'7839\', \'KING\', \'PRESIDENT\', null, \'1981-11-17\', \'5000.00\', null, \'10\');
INSERT INTO `emp` VALUES (\'7844\', \'TURNER\', \'SALESMAN\', \'7698\', \'1981-09-08\', \'1500.00\', \'0.00\', \'30\');
INSERT INTO `emp` VALUES (\'7900\', \'JAMES\', \'CLERK\', \'7698\', \'1981-12-03\', \'950.00\', null, \'30\');
INSERT INTO `emp` VALUES (\'7902\', \'FORD\', \'ANALYST\', \'7566\', \'1981-12-03\', \'3000.00\', null, \'20\');
INSERT INTO `emp` VALUES (\'7934\', \'MILLER\', \'CLERK\', \'7782\', \'1982-01-23\', \'1300.00\', null, \'10\');
INSERT INTO `emp` VALUES (\'7987\', \'KING\', null, null, null, null, null, null);

 

1、2在web-INF下lib加入mybatis所需jar包:

1、3在项目src下配置mybatis配置文件config.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://www.mybatis.org/dtd/mybatis-3-config.dtd">
<!--    configuration根标签             -->
<configuration>
    <!--    二、(1)定义实体bean名和数据库列名相对应  type:实体的路径   alias:实体的别名         -->
    <typeAliases>
        <typeAlias type="com.ckx.entity.User" alias="User" />
    </typeAliases>
    
    <!--    一、    配置环境信息          -->
    <environments default="development">
        <environment id="development">
            <!--    指定事务管理机制          -->
            <transactionManager type="JDBC"></transactionManager>
            <!--    配置数据源   POOLED: 连接池         -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/ssm001?useUnicode=true&amp;characterEncoding=utf8" />
                <property name="username" value="root" />
                <property name="password" value="123456" />
            </dataSource>
        </environment> 
    </environments>
    <!--     二、 (2)引入关系映射文件!!!这里有严格顺序!不能放在数据源配置前    -->
    <mappers>
        <mapper resource="com/ckx/entityMapper/User.xml" />
    </mappers>
    

</configuration>

请注意注释  “二、 (2)引入关系映射文件!!!这里有严格顺序!不能放在数据源配置前 ”,lz当时人为一个映射地址放在那里斗舞所谓,

结果报错,莫名其妙的找了好久的错,关于原因请参考:http://www.cnblogs.com/ckxlovejava/p/6059960.html

二、创建实体与映射文件:

2、1创建和数据库对应的实体user类,注意变量和数据库字段的对应

 

package com.ckx.entity;

public class User {
    private int userId;
    private String userName;
    private String passWord;
    
    
    public int getUserId() {
        return userId;
    }
    public void setUserId(int userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassWord() {
        return passWord;
    }
    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

}

 

2.2配置与实体相对的映射文件用于存放sql语句(user.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.ckx.entityMapper.User">
    
    <select id="selectRoolByuserId" parameterType="int" resultType="User">
        select * from ckx_user where UserId=#{UserId}
    </select>
    
    
</mapper>

三、测试

3.1创建测试类UserlTest.java:

package com.ckx.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 com.ckx.entity.User;

public class UserlTest {
    //获取org.apache.ibatis.session.SqlSessionFactory很重要
    static SqlSessionFactory sessionFactory;
    static Reader reader;
    public User user;
    
    static{
        try {
            //获取org.apache.ibatis.io.Resources从config.xml的读入流
            reader= Resources.getResourceAsReader("config.xml");
            sessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    //从数据库读取一条信息
    private void selectRoolByuserId() {
        SqlSession session = sessionFactory.openSession();
        user= session.selectOne("com.ckx.entityMapper.User.selectRoolByuserId",1 );
        System.out.println(user.getUserName());
    }
    
    
    public static void main(String[] args) {
        UserlTest ut = new UserlTest();
        ut.selectRoolByuserId();

    }

}

运行:ckx

综合说明:

3.2查询一个结果集,例如:查询一个部门下的所有员工:

在emp表配置:

<!--    定义结果集 type:指定数据类型 id:标识结果集  -->
    <resultMap type="Emp" id="empList">
        <!--        column:数据库字段别名  property:实体bean属性名称-->
        <result column="EMPNO" property="empno" />
        <result column="ENAME" property="ename" />
        <result column="JOB" property="job" />
        <result column="MGR" property="mgr" />
        <result column="HIREDATE" property="hiredate" />
        <result column="SAL" property="sal" />
        <result column="COMM" property="comm" />
        <result column="DEPNO" property="depno" />
    </resultMap>

    
    <!--通过部门编号查询该部门的员工信息 这里返回的是一个结果集-->
    <select id="selectEmps" parameterType="int" resultMap ="empList">
        select * from emp where depno=#{depno}
    </select>

因为我们查询的是一个部门下的所有人,因此查询返回结果我们用一个emplist,但是程勋不知道这个emplist是什么?这时候我们就要对他进行定义,

定义一个返回resultMap,并把sql查询的返回结果emplist赋给resultMap做ID,当然resultMap里放的数据肯定是实体emp,在resultMap里我们在对

数据库和实体进行一一指定,column:数据库字段别名 property:实体bean属性名称。

定义一个测试类进行测试:

package com.ckx.test;

import java.io.IOException;
import java.io.Reader;
import java.util.Iterator;
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.ckx.entity.Emp;
import com.ckx.entity.User;

public class Emptest {
    //获取org.apache.ibatis.session.SqlSessionFactory很重要
    static SqlSessionFactory sessionFactory;
    static Reader reader;
        
    static{
        try {
            //获取org.apache.ibatis.io.Resources从config.xml的读入流
            reader= Resources.getResourceAsReader("config.xml");
            sessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }//从数据库读取一个list集合    
    public void selectEmps(){
        SqlSession session = sessionFactory.openSession();
        List<Emp> emps = session.selectList("com.ckx.entityMapper.Emp.selectEmps", 20);
        //迭代器遍历
        Iterator it = emps.iterator();
        while (it.hasNext()) {
            Emp e= (Emp) it.next();
            System.out.println(e.getEname());;
        }
        //FOREACH循环迭代
        for (Emp emp : emps) {
            System.out.println(emp.getEname());
        }
    }public static void main(String[] args) {
        Emptest et = new Emptest();
        et.selectEmps();
    }

}

测试结果(文中用了两种遍历方式):

SMITH
JONES
FORD
SMITH
JONES
FORD

完成。

 

以上是关于mybatis环境的搭建的主要内容,如果未能解决你的问题,请参考以下文章

Mybatis关于复杂的SQL查询的处理&Mybatis的缓存机制

MyBatis——环境搭建

MyBatis环境搭建

MyBatis(一) —— 环境搭建

Mybatis的环境的搭建和使用

MyBatis下载和环境搭建