mybaits-入门

目录

什么是mybatis

MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。2013年11月迁移到Github。
iBATIS一词来源于“internet”和“abatis”的组合,是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAOs)
中文文档:https://mybatis.net.cn/

环境

mybaits-入门
mybatis.jar:https://github.com/mybatis/mybatis-3/releases
mybaits-入门

入门案例

/*
 Navicat Premium Data Transfer

 Source Server         : school
 Source Server Type    : MySQL
 Source Server Version : 80022
 Source Host           : localhost:3306
 Source Schema         : school

 Target Server Type    : MySQL
 Target Server Version : 80022
 File Encoding         : 65001

 Date: 10/11/2021 15:02:04
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for grade
-- ----------------------------
DROP TABLE IF EXISTS `grade`;
CREATE TABLE `grade`  (
  `gradeId` int(0) NOT NULL AUTO_INCREMENT,
  `gradeName` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  PRIMARY KEY (`gradeId`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of grade
-- ----------------------------
INSERT INTO `grade` VALUES (1, 'S1');
INSERT INTO `grade` VALUES (2, 'Y1');

SET FOREIGN_KEY_CHECKS = 1;

package com.fly.entity;

/**
 * @author 26414
 */
public class Grade {
  
  private Integer gradeId;
  private String gradeName;

  @Override
  public String toString() {
    return "Grade{" +
            "gradeId=" + gradeId +
            ", gradeName='" + gradeName + '\'' +
            '}';
  }

  public Integer getGradeId() {
    return gradeId;
  }

  public void setGradeId(Integer gradeId) {
    this.gradeId = gradeId;
  }

  public String getGradeName() {
    return gradeName;
  }

  public void setGradeName(String gradeName) {
    this.gradeName = gradeName;
  }
}

通过名称调用

mybaits-入门
在src下建立mybatis的配置文件

<?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.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/school?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false&amp;serverTimezone=GMT%2B8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--这里填sql映射文件的位置-->
        <mapper resource="org/mybatis/example/BlogMapper.xml"/>
    </mappers>
</configuration>

mybaits-入门
mybaits-入门
创建sql映射文件

<?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.fly">
    <!--
    id:唯一标识
    resultType:返回值类型
    -->
    <select id="selectGradeById" resultType="com.fly.entity.Grade">
        select * from grade where gradeId = #{gradeId}
    </select>
</mapper>

修改mybaits配置文件
mybaits-入门

测试

mybaits-入门
mybaits-入门

  @Test
  public void test1() throws IOException {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //第一个参数的值通常为sql映射文件的命名空间加上方法对应的标签的id值
    Grade grade = sqlSession.selectOne("com.fly.selectGradeById", 1);
    System.out.println("grade = " + grade);
    sqlSession.close();
  }

mybaits-入门

通过接口调用语句

package com.fly.dao;

import com.fly.entity.Grade;

/**
 * @author 26414
 */
public interface GradeMapper {

  /**
   * 根据id查询年级
   * @param gradeId 年级id
   * @return gradeId对应的年级
   */
  Grade getGradeById(Integer gradeId);
  
}

修改sql映射文件
mybaits-入门
mybaits-入门

测试

  @Test
  public void test2() throws IOException {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //通过反射得到代理对象
    GradeMapper mapper = sqlSession.getMapper(GradeMapper.class);
    Grade grade = mapper.getGradeById(1);
    System.out.println("mapper = " + mapper);
    System.out.println("grade = " + grade);
    sqlSession.close();
  }

mybaits-入门

上一篇:艾伟_转载:学习 ASP.NET MVC (第二回)实战篇


下一篇:mybaits头文件