MyBatis数据库框架

创建数据库mybatis和表users

create database mybatis;
use mybatis;
CREATE TABLE users(id INT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(20), age INT);
INSERT INTO users(NAME, age) VALUES('孤傲苍狼', 19);
INSERT INTO users(NAME, age) VALUES('白虎神皇', 29);

添加mybatis框架jar包(核心包+驱动包+依赖包)

image-20210729144420878

创建数据库配置文件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>
    <!--1.配置环境 ,默认的环境id为mysql-->
    <environments default="mysql">
            <!--1.2.配置id为mysql的数据库环境 -->
             <environment id="mysql">
                <!-- 使用JDBC的事务管理 -->
                <transactionManager type="JDBC" />
                <!--数据库连接池 -->
                <dataSource type="POOLED">
                    <property name="driver"  value="com.mysql.jdbc.Driver" />
                    <property name="url"  value="jdbc:mysql://localhost:3306/mybatis" />
                    <property name="username" value="root" />
                    <property name="password" value="root" />
                </dataSource>
            </environment>
</environments>

</configuration>

定义数据库user,对应的实体类User

 package me.gacl.domain;

  /**
   * @author gacl
   * users表所对应的实体类
   */
  public class User {

      //实体类的属性和表User的字段名称一一对应
     private int id;
     private String name;
     private int age;

     public int getId() {
         return id;
     }

     public void setId(int 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;
     }

     @Override
     public String toString() {
         return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
     }
 }

MyBatis映射(新建一个包,专门用于存放sql映射文件)userMapper.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="me.gacl.mapping.userMapper">
     <select id="getUser" parameterType="int"  resultType="me.gacl.domain.User">
             select * from users where id=#{id}
     </select>
</mapper>

在mybatis-config.xml文件中注册userMapper.xml文件

    <!-- 注册userMapper.xml文件, userMapper.xml位于me.gacl.mapping这个包下,所以resource写成me/gacl/mapping/userMapper.xml -->
    <mappers>
        <mapper resource="me/gacl/mapping/userMapper.xml" />
    </mappers>

编写Test1测试类

package me.gacl.test;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import me.gacl.domain.User;
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 Test1 {
public static void main(String[] args) throws IOException {

        //mybatis的配置文件
         String resource = "mybatis-config.xml";

        //加载关联的映射文件
         InputStream is =Resources.getResourceAsStream(resource);

        //构建sqlSession的工厂
         SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);

        //创建能执行映射文件中sql的sqlSession
        SqlSession session = sessionFactory.openSession();

        /**
         * 映射sql的标识字符串,
         * me.gacl.mapping.userMapper是userMapper.xml文件中mapper标签的namespace属性的值,
         * getUser是select标签的id属性值,通过select标签的id属性值就可以找到要执行的SQL
         */
         String statement = "me.gacl.mapping.userMapper.getUser";//映射sql的标识字符串

        //执行查询返回一个唯一user对象的sql
        User user = session.selectOne(statement, 1);
        System.out.println(user);
    }
}

运行结果(查询id=1的信息)

image-20210729145533605

创建数据表,并实现增删改查

数据库mybatis student

create database mybatis character set utf8;
use mybatis;
CREATE TABLE student(
id INT PRIMARY KEY AUTO_INCREMENT, 
name VARCHAR(20), 
grade int,
department VARCHAR(20)
);
INSERT INTO student (name, grade,department) VALUES('孤傲苍狼', 2020, '抓鱼专业');
INSERT INTO student (name, grade,department) VALUES('王者', 2021, '游戏boss专业');
INSERT INTO student (name, grade,department) VALUES('孤傲苍狼2', 2022, '扫地专业');
INSERT INTO student (name, grade,department) VALUES('孤傲苍狼3', 2021, '航天狩猎专业');
INSERT INTO student (name, grade,department) VALUES('孤傲苍狼4', 2020, '抓鱼专业');

Student实体类(get and set + to string)

package me.gacl.domain;

public class Student {
    private Integer id;
    private String name;
    private Integer grade;
    private String department;

    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 getGrade() {
        return grade;
    }

    public void setGrade(Integer grade) {
        this.grade = grade;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", grade=" + grade + ", department=" + department + "]";
    }

}

studentMapper.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="me.gacl.mapping.studentMapper">
    <insert id="insertOneStudent"
        parameterType="me.gacl.domain.Student">
        insert into student
        (name,grade,department)values(#{name},#{grade},#{department} );
    </insert>

    <select id="getStudent" parameterType="int"
        resultType="me.gacl.domain.Student">
        select * from student where id=#{id}
    </select>

    <update id="updateStudent"
        parameterType="me.gacl.domain.Student">
        update student
        set department = "计算机" where name
        =#{name};
    </update>

    <delete id="deleteStudent" parameterType="String">
        delete from
        student
        where name=#{name};
    </delete>

</mapper>

在 mybatis-config.xml 中注册 studentMapper.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>
    <!--1.配置环境 ,默认的环境id为mysql -->
    <environments default="mysql">
        <!--1.2.配置id为mysql的数据库环境 -->
        <environment id="mysql">
            <!-- 使用JDBC的事务管理 -->
            <transactionManager type="JDBC" />
            <!--数据库连接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url"
                    value="jdbc:mysql://localhost:3306/mybatis" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>
    <!-- 注册userMapper.xml文件, userMapper.xml位于me.gacl.mapping这个包下,所以resource写成me/gacl/mapping/userMapper.xml -->
    <mappers>
        <mapper resource="me/gacl/mapping/userMapper.xml" />
        <mapper resource="me/gacl/mapping/studentMapper.xml" />
    </mappers>

</configuration>

创建Test1类,测试增删改查

package me.gacl.test;

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;

import me.gacl.domain.Student;

public class Test1 {
    public static void main(String[] args) throws IOException {
        // Student s1 = new Student();
        // s1.setDepartment("计算机应用技术");
        // s1.setGrade(2021);
        // s1.setName("张三");

        // mybatis的配置文件
        String resource = "mybatis-config.xml";

        // 加载关联的映射文件
        InputStream is = Resources.getResourceAsStream(resource);

        // 构建sqlSession的工厂
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);

        // 创建能执行映射文件中sql的sqlSession
        SqlSession session = sessionFactory.openSession();

        String statement = "me.gacl.mapping.studentMapper.deleteStudent";

        // int rows = session.insert(statement, s1);
        int rows = session.delete(statement, "张三");
        System.out.println("成功删除了" + rows + "条");
        session.commit();
        session.close();
    }

}

配置 studentMapper.xml ,修改 statement ,调用方法

运行结果(updateStudent)

image-20210730134802540

image-20210730134847025

Share