欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Mybatis使用手册

程序员文章站 2024-03-15 18:49:54
...

一、Mybatis环境搭建

1.数据库的准备

(1) 数据库SQL脚本


DROP TABLE IF EXISTS `employee_basic`;
CREATE TABLE `employee_basic`  (
  `emp_no` varchar(8) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '员工号',
  `emp_name` varchar(12) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '',
  `dept_id` varchar(3) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '所在的部门号(外键),指向部门信息表的dept_id',
  `emp_gender` varchar(6) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `emp_email` varchar(28) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `emp_nation` varchar(16) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '民族',
  `emp_marriage` varchar(6) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `emp_health` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `emp_zzmm` varchar(8) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '政治面貌',
  `emp_blood` varchar(6) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '血型',
  `emp_state` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '员工状态',
  PRIMARY KEY USING BTREE (`emp_no`)
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

INSERT INTO `employee_basic` VALUES ('HW9801', '张丹枫', '101', '男', 'aaa@qq.com', '汉族', '已婚', '良好', '党员', 'O型', '在职');
INSERT INTO `employee_basic` VALUES ('HW9802', '史密斯', '101', '男', 'aaa@qq.com', '满族', '已婚', '良好', '群众', 'A型', '在职');
INSERT INTO `employee_basic` VALUES ('HW9803', '余小男', '101', '女', 'aaa@qq.com', '汉族', '未婚', '良好', '群众', 'B型', '在职');
INSERT INTO `employee_basic` VALUES ('HW9804', '李莉莉', '102', '女', 'aaa@qq.com', '回族', '未婚', '良好', '团员', 'B型', '在职');
INSERT INTO `employee_basic` VALUES ('HW9805', 'Marry', '102', '女', 'aaa@qq.com', '汉族', '未婚', '良好', '群众', 'O型', '在职');
INSERT INTO `employee_basic` VALUES ('HW9806', '郭靖', '103', '男', 'aaa@qq.com', '汉族', '已婚', '良好', '党员', 'O型', '在职');
INSERT INTO `employee_basic` VALUES ('HW9807', '王强', '103', '男', 'aaa@qq.com', '汉族', '已婚', '良好', '党员', 'O型', '在职');
INSERT INTO `employee_basic` VALUES ('HW9808', '李娜', '103', '女', 'aaa@qq.com', '汉族', '未婚', '良好', '群众', 'O型', '在职');
INSERT INTO `employee_basic` VALUES ('HW9809', '许天仪', '103', '男', 'aaa@qq.com', '汉', '已婚', '一般', '党员', 'O型', '退休');

2.导入依赖坐标

<dependencies>
     <!-- mybatis核心包-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.5</version>
    </dependency>
    <!--mysql驱动包-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.6</version>
    </dependency>
    <!--单元测试-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.10</version>
        <scope>test</scope>
    </dependency>
    <!--日志-->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
</dependencies>

3.log4j.properties内容

log4j.rootCategory=DEBUG,CONSOLE,LOGFILE
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%C %d{YYYY-MM-dd hh:mm:ss} %L %m %n
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=h://zhang.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%C %m %n  %L


4.Pojo层实体类

package com.zxf.pojo;

import java.io.Serializable;

public class Employee implements Serializable {
    private String emp_no;
    private String emp_name;
    private String emp_email;
    private String emp_nation;
    private String emp_zzmm;
    private String emp_blood;
    private String emp_state;

    public String getEmp_no() {
        return emp_no;
    }

    public void setEmp_no(String emp_no) {
        this.emp_no = emp_no;
    }

    public String getEmp_name() {
        return emp_name;
    }

    public void setEmp_name(String emp_name) {
        this.emp_name = emp_name;
    }

    public String getEmp_email() {
        return emp_email;
    }

    public void setEmp_email(String emp_email) {
        this.emp_email = emp_email;
    }

    public String getEmp_nation() {
        return emp_nation;
    }

    public void setEmp_nation(String emp_nation) {
        this.emp_nation = emp_nation;
    }

    public String getEmp_zzmm() {
        return emp_zzmm;
    }

    public void setEmp_zzmm(String emp_zzmm) {
        this.emp_zzmm = emp_zzmm;
    }

    public String getEmp_blood() {
        return emp_blood;
    }

    public void setEmp_blood(String emp_blood) {
        this.emp_blood = emp_blood;
    }

    public String getEmp_state() {
        return emp_state;
    }

    public void setEmp_state(String emp_state) {
        this.emp_state = emp_state;
    }
}


5.Mapper接口

package com.zxf.mapper;
import com.zxf.pojo.Employee;
import java.util.List;
/*
     映射接口  employee
 */
public interface EmployeeMapper {
    //查询所有
    public List<Employee>findAll();
}


6.Mapper接口的映射配置文件xml

在resources创建了一个文件夹,后期所有的配置接口映射文件都放在这
Mybatis使用手册
EmployeeMapper.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">
<!--
namespace   mapper接口的全路径
 -->
<mapper namespace="com.zxf.mapper.EmployeeMapper">
    <!--
        id属性 接口中方法名字一致
         resultType属性 包名+类名
    -->
    <select id="findAll" resultType="com.zxf.pojo.Employee">
        SELECT * from employee_basic
    </select>
</mapper>

7.编写mybatis的核心配置文件

mybatisConfig.xml
Mybatis使用手册

<?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>
    <!--环境配置-->
    <environments default="mysql_1">
        <environment id="mysql_1">
             <!-- 事务类型-->
       <transactionManager type="JDBC"></transactionManager>
            <!--是否使用连接池,内置的连接池 -->
            <dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://192.168.0.148:3306/test"/>
                <property name="username" value="root"/>
                <property name="password" value="abc"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 引入映射-->
    <mappers>
        <mapper resource="mappers/EmployeeMapper.xml"/>
    </mappers>
</configuration>

8.编写一个Junit测试类

package com.zxf.test;
import com.zxf.mapper.EmployeeMapper;
import com.zxf.pojo.Employee;
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 java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class Test1 {
    //通过调用配置文件的<select id="findAll" 来查询数据库
    @Test
    public void test1()throws IOException{
         //加载主配置文件
        InputStream is= Resources.getResourceAsStream("mybatisConfig.xml");
        //创建SqlSessionFactory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
        //通过工厂获取SqlSession
        SqlSession session=factory.openSession();
        List<Employee> findAll = session.selectList("findAll");
        for(Employee e:findAll){
            System.out.print(e.getEmp_no()+" ");
            System.out.print(e.getEmp_name()+" ");
            System.out.print(e.getEmp_email()+" ");
            System.out.print(e.getEmp_blood()+" ");
            System.out.print(e.getEmp_zzmm()+" ");
            System.out.print(e.getEmp_nation()+" ");
            System.out.println(e.getEmp_state());
        }
    }
    //通过调用Mapper接口的方法findAll 来查询数据库
    @Test
    public void test2()throws IOException{
        //加载主配置文件
        InputStream is= Resources.getResourceAsStream("mybatisConfig.xml");
        //创建SqlSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
        //通过工厂获取SqlSession
        SqlSession session=factory.openSession();
        EmployeeMapper employeeMapper=session.getMapper(EmployeeMapper.class);
         List<Employee> findAll_2 = employeeMapper.findAll();
        for(Employee e:findAll_2){
            System.out.print(e.getEmp_no()+" ");
            System.out.print(e.getEmp_name()+" ");
            System.out.print(e.getEmp_email()+" ");
            System.out.print(e.getEmp_blood()+" ");
            System.out.print(e.getEmp_zzmm()+" ");
            System.out.print(e.getEmp_nation()+" ");
            System.out.println(e.getEmp_state());
        }
        session.close();
        is.close();
    }
}


9.项目结构架构层次

Mybatis使用手册

10.运行结果

Mybatis使用手册
陆续更新中,敬请关注…

相关标签: Mybatis