Mybatis基础

Mybatis基础

1.结构图

Mybatis基础

2.配置文件

  1. jdbc

    driver=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/db1
    username=root
    password=root
    
  2. log4j(不是必须)

    # Global logging configuration
    # ERROR WARN INFO DEBUG
    log4j.rootLogger=DEBUG, stdout
    # Console output...
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
    
  3. MyBatisConfig

    <?xml version="1.0" encoding="UTF-8" ?>
    <!--MyBatis的DTD约束-->
    <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
    
    <!--configuration 核心根标签-->
    <configuration>
    
        <!--引入数据库连接的配置文件-->
        <properties resource="jdbc.properties"/>
    
        <!--配置LOG4J-->
        <settings>
            <setting name="logImpl" value="log4j"/>
        </settings>
    
        <!--起别名-->
        <typeAliases>
            <typeAlias type="com.ding.bean.Student" alias="student"/>
            <!--<package name="com.ding.bean"/>-->
        </typeAliases>
    
        <!--environments配置数据库环境,环境可以有多个。default属性指定使用的是哪个-->
        <environments default="mysql">
            <!--environment配置数据库环境  id属性唯一标识-->
            <environment id="mysql">
                <!-- transactionManager事务管理。  type属性,采用JDBC默认的事务-->
                <transactionManager type="JDBC"></transactionManager>
                <!-- dataSource数据源信息   type属性 连接池-->
                <dataSource type="POOLED">
                    <!-- property获取数据库连接的配置信息 -->
                    <property name="driver" value="${driver}" />
                    <property name="url" value="${url}" />
                    <property name="username" value="${username}" />
                    <property name="password" value="${password}" />
                </dataSource>
            </environment>
        </environments>
    
        <!-- mappers引入映射配置文件 -->
        <mappers>
            <!-- mapper 引入指定的映射配置文件   resource属性指定映射配置文件的名称 -->
            <mapper resource="StudentMapper.xml"/>
        </mappers>
    </configuration>
    
  4. StudentMapper

    <?xml version="1.0" encoding="UTF-8" ?>
    <!--MyBatis的DTD约束-->
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <!--
        mapper:核心根标签
        namespace属性:名称空间
    -->
    <mapper namespace="StudentMapper">
        <!--
            select:查询功能的标签
            id属性:唯一标识
            resultType属性:指定结果映射对象类型
            parameterType属性:指定参数映射对象类型
        -->
        <select id="selectAll" resultType="student">
            select * from student
        </select>
    
        <select id="selectById" resultType="student" parameterType="int">
            select * from student where id=#{id}
        </select>
    
        <insert id="insert" parameterType="student">
            insert into student values(#{id},#{name},#{age})
        </insert>
    
        <update id="update" parameterType="student">
            update student set name=#{name},age=#{age} where id=#{id}
        </update>
    
        <delete id="delete" parameterType="int">
            delete from student where id=#{id}
        </delete>
    </mapper>
    

3.实体类

package com.ding.bean;

public class Student {
    private Integer id;
    private String name;
    private Integer age;

    public Student() {
    }

    public Student(Integer id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    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 Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name=‘" + name + ‘\‘‘ +
                ", age=" + age +
                ‘}‘;
    }
}

4.测试类

package com.ding.dao;

import com.ding.bean.Student;
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.InputStream;
import java.util.List;

/**
 * @Description TODO
 * @Author 丁帅帅
 * @Date 21/07/17 14:57
 * @Version 1.0
 */
public class StudentTest01 {


    /**
     * 查询全部
    */
    @Test
    public void selectAll() throws Exception{
        //1.加载核心配置文件
        //InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
        InputStream is = StudentTest01.class.getClassLoader().getResourceAsStream("MyBatisConfig.xml");

        //2.获取SqlSession工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

        //3.通过SqlSession工厂对象获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //4.执行映射配置文件中的sql语句,并接收结果
        List<Student> list = sqlSession.selectList("StudentMapper.selectAll");

        //5.处理结果
        for (Student stu : list) {
            System.out.println(stu);
        }

        //6.释放资源
        sqlSession.close();
        is.close();
    }

    /*
        根据id查询
     */
    @Test
    public void selectById() throws Exception{

        //1.加载核心配置文件
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");

        //2.获取SqlSession工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

        //3.通过工厂对象获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //4.执行映射配置文件中的sql语句,并接收结果
        Student stu = sqlSession.selectOne("StudentMapper.selectById", 3);

        //5.处理结果
        System.out.println(stu);

        //6.释放资源
        sqlSession.close();
        is.close();

    }

    /**
     * 新增功能
     */
    @Test
    public void insert() throws Exception{

        //1.加载核心配置文件
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");

        //2,获取SqlSession工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

        //3.通过工厂对象获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //4.执行映射配置文件中的sql语句,并接收结果
        Student student = new Student(4, "周琦", 27);
        int result = sqlSession.insert("StudentMapper.insert", student);

        //5.提交事务
        sqlSession.commit();

        //6.处理结果
        System.out.println(result);

        //7.释放资源
        sqlSession.close();
        is.close();

    }

    /*
    修改功能
     */
    @Test
    public void update() throws Exception{

        //1.加载核心配置文件
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");

        //2.获取SqlSession工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

        //3.通过工厂对象获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);

        //4.执行映射配置文件中的sql语句,并接收结果
        Student student = new Student(4, "周七", 47);
        int result = sqlSession.update("StudentMapper.update", student);

        //5.处理结果
        System.out.println(result);

        //6.释放资源
        sqlSession.close();
        is.close();
    }
    /*
    删除功能
     */
    @Test
    public void delete() throws Exception{
        //1.加载核心配置文件
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");

        //2.获取SqlSession工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

        //3.通过工厂对象获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);

        //4.执行映射配置文件中的sql语句,并接收结果
        int result = sqlSession.delete("StudentMapper.delete", 4);

        //5.处理结果
        System.out.println(result);

        //6.释放资源
        sqlSession.close();
        is.close();
    }
}

Mybatis基础

上一篇:PMP过程组与知识领域


下一篇:复现及理解