Mybatis简介及入门代码

Mybatis

前言


前言:mybatis是一个非常优秀的存储过程和高级映射的优秀"持久层框架"。大大简化了,数据库操作中的常用操作。下面将介绍mybatis的一些概念和在eclipse上的实际项目搭建使用。


Mybatis是什么?


官方解释: MyBatis 是一款优秀的"持久层框架",它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生类型、接口和 Java 的 POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。


MyBatis的基本构成


四大组成:
  • SqlSessionFactoryBuilder: (构造器),根据xml配置信息或代码来生成SqlSessionFactory对象;

  • SqlSessionFactory: 通过openSession()生成SqlSession;

  • SqlSession: 执行SQL并返回结果,它可以直接通过select,update,insert,delete方法去操作数据库得到xml映射器

  • SQLMapping: 由一个java接口和xml(或者注解)构成;

使用步骤

准备好数据库资源

DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `gender` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4;

INSERT INTO `student` VALUES ('1', '张三', '18', '男');
INSERT INTO `student` VALUES ('2', '李四', '20', '男');
INSERT INTO `student` VALUES ('3', '小红', '30', '女');
INSERT INTO `student` VALUES ('4', '李红', '28', '女');

创建一个Maven项目,添加包的依赖

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.dahua</groupId>
  <artifactId>Mybatis</artifactId>
  <version>1.0-SNAPSHOT</version>


  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <dependencies>
  	<!--测试Junit-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <!-- mybatis的jar-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.1</version>
    </dependency>

    <!-- JDBC-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.9</version>
    </dependency>
  </dependencies>

</project>

创建实体类 Student , 和数据库要对应

package com.dahua.entity;

public class Student {

    private Integer id;
    private String name;
    private Integer age;
    private String gender;

    public Student() {
    }

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

    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;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

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

在resources下 创建mybatis.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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                //支持中文
                <property name="url" value="jdbc:mysql://localhost:3306/ssm?useUnicode=true&amp;characterEncoding=utf8"/>
                <property name="username" value="root"/>
                <property name="password" value="qwer0650"/>
            </dataSource>
        </environment>
    </environments>
</configuration>

创建一个工具类MybatisUtils,可以和JDBC工具类一样去理解

package com.dahua.common;

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 java.io.IOException;
import java.io.InputStream;

public class MybatisUtil {
    static SqlSessionFactory sqlSessionFactory;
    static {
        //读取配置文件
        String mybatis = "mybatis.xml";
        //通过流的方式读取配置文件
        InputStream resourceAsStream = null;
            try {
                 resourceAsStream = Resources.getResourceAsStream(mybatis);
                //创建出SqlSessionFactory 工厂
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);

            } catch (IOException e) {
                e.printStackTrace();
                sqlSessionFactory = null;
            }
    }

    public static SqlSession getSqlSession() {
        if (sqlSessionFactory != null) {
            return sqlSessionFactory.openSession(true);
        }
        return null;
    }
}

写接口

package com.dahua.dao;

import com.dahua.entity.Student;

import java.util.List;

public interface StudentDao {
    List<Student> selectStudents();

    Student selectStudentByID(Student student);

    //增加
    int insertStudent(Student student);

    //删除
    int deleteStudent(Student student);

    //更新
    int updateStudent(Student student);
}

Mybatis里的实体类接口不用写实现类,只需要编写StudentDao对应的xml配置文件StudentDao.xml,一般来说,将该文件和StudentDao接口放在同一级目录下:

<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!--唯一字符串-->
<!--namespace:绑定一个对应的Dao接口,可以理解为这里就是实现这个接口的-->
<mapper namespace="com.dahua.dao.StudentDao">
    <!-- id 接口中的方法名   resultType 返回值类型(全限定类名)-->
    <select id="selectStudents" resultType="com.dahua.entity.Student">
        select id, name, age, gender
        from student
    </select>

    <select id="selectStudentByID" resultType="com.dahua.entity.Student">
        select *
        from student
        where id = #{id}
    </select>

    <delete id="deleteStudent">
        delete
        from student
        where id = #{id}
    </delete>

    <update id="updateStudent">
        update student
        set name=#{name}
        where id = #{id}
    </update>

    <insert id="insertStudent">

        insert into student (id, name, age, gender)
        values (#{id}, #{name}, #{age}, #{gender})
    </insert>
</mapper>

然后在配置文件mybatis.xm里边添加映射

<mappers>
        <mapper resource="com/dahua/dao/StudentDao.xml"/>
    </mappers>

测试其中的selectStudents()

package com.dahua;

import com.dahua.common.MybatisUtil;
import com.dahua.dao.StudentDao;
import com.dahua.entity.Student;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class TestStudent {

    @Test
    public void testSelectStudent() throws IOException {

        //获取sqlSession的实例
        SqlSession sqlSession = MybatisUtil.getSqlSession();

        StudentDao studentDaoImpl = sqlSession.getMapper(StudentDao.class);
        List<Student> students = studentDaoImpl.selectStudents();

//        System.out.println(students.size());

        //遍历
        for (Student stu: students) {
            System.out.println(stu);
        }

        //关闭sqlSession
        sqlSession.close();
    }
}

可能会报错

在这里插入图片描述
我们只需要在pom.xml配置一下

<build>
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>

最终运行结果如下

在这里插入图片描述


这是我的项目目录
controller包和service包以后才用得到

在这里插入图片描述

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值