mybatis学习之入门实例

测试版本

mybatis:3.2.8

数据库:mysql

项目结构

jar包准备

mybatis-3.2.8.jar

mysql-connector-java-5.1.39-bin.jar

junit-4.4.jar

log4j-1.2.17.jar

配置文件

1、jdbc.properties配置文件:

jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://127.1.0.1:3306/db_mybatis
jdbc.username=root
jdbc.password=root

2、mybatis主要配置文件,mybatis-config.xml:

<?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>
    
    <properties resource="jdbc.properties"></properties>
    <typeAliases>
        <typeAlias type="com.cz.model.Student" alias="Student"/>        <!-- 类型别名 -->
    </typeAliases>
    
    <environments default="development">        <!-- 默认开发环境 -->
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driverClassName}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    
    <mappers>
        <mapper resource="com/cz/mappers/StudentMapper.xml"/>
    </mappers>
    
</configuration>

其中typeAliases是为了指定类型别名,这样使用到com.cz.model.Student类时直接使用Student代替即可。

创建SqlSessionFactoryUtil工具类

该工具类主要是加载mybatis配置文件并通过相应的builder生成session工厂,再从工厂产生sql session对象,这里使用到了单例设计模式(懒汉式):

package com.cz.utill;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class SqlSessionFactoryUtil {

    private static SqlSessionFactory sqlSessionFactory;

    private SqlSessionFactoryUtil() {}

    private static SqlSessionFactory getSqlSessionFactory() {
        if (sqlSessionFactory == null) {
            // 读取mybatis配置
            InputStream inputStream = null;
            try {
                inputStream = Resources.getResourceAsStream("mybatis-config.xml");
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sqlSessionFactory;
    }
    
    public static SqlSession openSession(){
        return getSqlSessionFactory().openSession();
    }
}

创建实体映射类

实体类Student.java,这里只有三个属性:

package com.cz.model;

public class Student {
    
    private Integer id;
    private String name;
    private int age;
    
    public Student(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    
    public Student() {
        super();
    }
    
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
}

编写Dao接口

mybatis支持传统的类似hibernate的Dao层封装数据库操作,也支持面向mapper.xml映射文件的动态sql类型,如果使用传统的Dao数据库编程模型的话,需要在相应的Dao类中注入sql session工厂对象(一般通过构造注入),这里使用后一种方式即mapper配置:

package com.cz.mappers;

import java.util.List;

import com.cz.model.Student;

public interface StudentDao {
    /**
     * 新增
     * @param student
     * @return
     */
    public int add(Student student);
    /**
     * 修改
     * @param student
     * @return
     */
    public int update(Student student);
    /**
     * 删除
     * @param student
     * @return
     */
    public int delete(Integer id); 
    /**
     * 根据id查找 
     * @param id
     * @return
     */
    public Student findById(Integer id);
    /**
     * 查找 
     * @param id
     * @return
     */
    public List<Student> find();
}

mapper.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.cz.mappers.StudentDao">
    
    <resultMap type="Student" id="StudentResult">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="age" column="age"/>
    </resultMap>
    
    <!-- 插入 -->
    <insert id="add" parameterType="Student">
        insert into t_student values(null,#{name},#{age})
    </insert>
    
    <update id="update" parameterType="Student">
        update t_student set name = #{name},age = #{age} where id = #{id}
    </update>
    
    <delete id="delete" parameterType="Integer">
        delete from t_student where id = #{id}
    </delete>
    
    <select id="findById" resultMap="StudentResult" parameterType="Integer">
        select * from t_student where id = #{id}
    </select>
    
    <select id="find" resultMap="StudentResult">
        select * from t_student
    </select>
</mapper>

dao接口跟mapper文件的对应关系如下:

添加log4j日志记录

添加jar包:log4j-1.2.17.jar

编写测试类StudentServiceTest.java:

package com.cz.service;

import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;

import com.cz.mappers.StudentDao;
import com.cz.model.Student;
import com.cz.utill.SqlSessionFactoryUtil;

public class StudentServiceTest {
    
    public static Logger logger = Logger.getLogger(StudentServiceTest.class);
    
    public static void main(String[] args) {
        
        SqlSession sqlSession = SqlSessionFactoryUtil.openSession();
        StudentDao studentDao = sqlSession.getMapper(StudentDao.class);        //返回student dao接口
        int result = studentDao.add(new Student("张三", 20));
        sqlSession.commit();
        if (result > 0) {
            logger.info("测试成功");
        }
    }
    
}

使用junit单元测试

添加junit-4.4.jar,单元测试代码:

package com.cz.test;

import java.util.Iterator;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.cz.mappers.StudentDao;
import com.cz.model.Student;
import com.cz.utill.SqlSessionFactoryUtil;

public class StudentTest {

    public static Logger logger = Logger.getLogger(StudentTest.class);
    SqlSession sqlSession = null;
    StudentDao studentDao = null; // 返回student dao接口

    @Before
    public void setUp() throws Exception {
        sqlSession = SqlSessionFactoryUtil.openSession();
        studentDao = sqlSession.getMapper(StudentDao.class);
        logger.info("开始执行了");
    }

    @After
    public void tearDown() throws Exception {
        sqlSession.close();
        logger.info("执行结束了");
    }

    @Test
    public void testAdd() throws Exception {
        Student student = new Student("admin", 22);
        int result = studentDao.add(student);
        sqlSession.commit();
        if (result > 0) {
            logger.info("添加成功了");
        }
    }

    @Test
    public void testUpdate() throws Exception {
        Student student = new Student(24, "xxxxxxx", 21);
        int result = studentDao.update(student);
        sqlSession.commit();
        if (result > 0) {
            logger.info("修改成功了");
        }
    }

    @Test
    public void testDelete() throws Exception {
        int result = studentDao.delete(26);
        sqlSession.commit();
        if (result > 0) {
            logger.info("删除成功了");
        }
    }
    
    @Test
    public void testFindById() throws Exception {
        Student student = studentDao.findById(25);
        System.out.println(student.toString());
        sqlSession.commit();
    }

    @Test
    public void testFind() throws Exception {
        List<Student> students = studentDao.find();
        // Iterator<Student> iterator = students.iterator();
        // while (iterator.hasNext()) {
        // System.out.println(iterator.next());
        // }
        // for(Student s:students){
        // System.out.println(s.toString());
        // }
        Student student = null;
        for (int i = 0; i < students.size(); i++) {
            student = students.get(i);
            System.out.println(student.toString());
        }
        sqlSession.commit();
    }
}

测试结果:

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏成长道路

scala的maven项目读取配置文件

scala的maven项目读取src/main/resources目录下的资源文件该如何读取呢? 下面提供一种默认的和一种自定义的: ? 对于applicati...

3010
来自专栏码匠的流水账

reactor-netty中HttpClient对TcpClient的封装

本文主要研究一下reactor-netty中HttpClient对TcpClien的封装

1521
来自专栏知识分享

关于Http 传输二维json

然后就在想是不是   String str = jsonObject1.toString();    jsonObject.put("param",str); ...

874
来自专栏xingoo, 一个梦想做发明家的程序员

Java程序员的日常—— IOUtils总结

以前写文件的复制很麻烦,需要各种输入流,然后读取line,输出到输出流...其实apache.commons.io里面提供了输入流输出流的常用工具方法,非常方...

3139
来自专栏Java成神之路

Java钉钉开发_02_免登授权(身份验证)

将所有待签名参数按照字段名的ASCII 码从小到大排序(字典序)后,使用URL键值对的格式 (即 key1=value1&key2=value2…)拼接成字符串...

842
来自专栏GIS讲堂

Openlayers4+servlet实现切片的本地缓存

本文实现的是结合Openlayers4和java servlet实现公网资源切片的本地缓存。

723
来自专栏Java成神之路

Java微信公众平台开发_06_素材管理

1192
来自专栏Java成神之路

Java企业微信开发_02_通讯录同步

       登录企业微信—>管理工具—>通讯录同步助手—>开启“API接口同步”  ; 开启后,即可看到通讯录密钥,也可设置通讯录API的权限:读取或者编辑通...

2292
来自专栏码匠的流水账

聊聊flink的TextOutputFormat

flink-streaming-java_2.11-1.7.0-sources.jar!/org/apache/flink/streaming/api/data...

582
来自专栏龙首琴剑庐

Java微信支付快速入门&工具类

快速入门 1、微信支付官方在线API入口: https://pay.weixin.qq.com/wiki/doc/api/index.html 2、微信支付能力...

62712

扫码关注云+社区