mybatis学习之环境搭建&入门实例

Posted

tags:

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

mybatis:3.2.8

数据库:mysql

项目结构

技术分享

jar包准备:

mybatis-3.2.8.jar

mysql-connector-java-5.1.39-bin.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>

创建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 com.cz.model.Student;

public interface StudentDao {
    /**
     * 新增
     * @param student
     * @return
     */
    public int add(Student student);
    
}

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">
    
    <!-- 插入 -->
    <insert id="add" parameterType="Student">
        insert into t_student values(null,#{name},#{age})
    </insert>
    
</mapper>

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

技术分享

其中namespace只是为了简化parameterType的类型定义,如果未定义namespace的话,这里必须填写完整类名。

编写测试类StudentServiceTest.java:

package com.cz.service;

import org.apache.ibatis.session.SqlSession;

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

public class StudentServiceTest {
    
    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) {
            System.out.println("添加成功");
        }
    }
    
}

 

以上是关于mybatis学习之环境搭建&入门实例的主要内容,如果未能解决你的问题,请参考以下文章

Web开发学习目录

Gradle 学习之入门知识

Gradle 学习之入门知识

前端学习之Vue项目搭建

深度学习之30分钟快速入门PyTorch(附学习资源推荐)

Centos7.2 MQTT的学习之Mosquitto搭建&集群搭建&使用