1. 程式人生 > 其它 >mybatis-配置檔案

mybatis-配置檔案

目錄

標籤順序

configuration (properties?, settings?, typeAliases?, typeHandlers?, objectFactory?, objectWrapperFactory?, reflectorFactory?, plugins?, environments?, databaseIdProvider?, mappers?)

環境

/*
 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;
  }
}
<?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&amp;allowPublicKeyRetrieval=true"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--這裡填sql對映檔案的位置-->
        <mapper resource="mapper/GradeMapper.xml"/>
    </mappers>
</configuration>
package com.fly.dao;

import com.fly.entity.Grade;

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

  /**
   * 根據id查詢年級
   * @param gradeId 年級id
   * @return gradeId對應的年級
   */
  Grade getGradeById(Integer gradeId);

}

properties


在類路徑下建立dbconfig.properties檔案

db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
db.username=root
db.password=123456
#這裡不能有空格

測試

 @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();
  }


由於mybatis和spring整合後,資料庫的配置都交給spring管理,這個標籤瞭解即可

settings


typeAliases

給單個Java 型別設定別名

<!-- mybatis-config.xml -->
  <typeAliases>
        <!--預設是類名首字母小寫,不區分大小寫-->
        <typeAlias type="com.fly.entity.Grade"/>
    </typeAliases>

測試

  @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();
  }

也可以使用alias屬性自定義別名

<!-- mybatis-config.xml -->
 <typeAliases>
        <typeAlias type="com.fly.entity.Grade" alias="gra"/>
    </typeAliases>


執行test2方法測試

給整個包下的類設定別名

<!-- mybatis-config.xml -->
 <typeAliases>
        <!--不區分大小寫-->
        <package name="com.fly.entity"/>
    </typeAliases>

對映檔案不用改,執行test2

@Alias


假如entity包下面有Grade類,entity包的子包也有Grade類,給entity包起別名就會報錯,可以用@Alias單獨設定別名

已經有的別名

environments


transactionManager

dataSource




databaseIdProvider

mappers

class屬性

 <mappers>
        <!--這裡填sql對映檔案的位置-->
        <!--
            resource:引用類路徑下的對映檔案
            url:引用網路路徑或者磁碟路徑的檔案
        -->
<!--        <mapper resource="mapper/GradeMapper.xml"/>-->
        <!--
            介面和對映檔案必須在同一個包下面,並且名字相同
        -->
        <mapper class="com.fly.dao.GradeMapper"/>
    </mappers>


執行test2方法測試

或者將sql語句寫在方法上面

package com.fly.dao;

import com.fly.entity.Grade;
import org.apache.ibatis.annotations.Select;

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

  /**
   * 根據id查詢年級
   * @param gradeId 年級id
   * @return gradeId對應的年級
   */
  @Select("select * from grade where gradeId = #{gradeId}")
  Grade getGradeById(Integer gradeId);

}

 <mappers>
        <!--mybatis-config.xml-->
        <mapper class="com.fly.dao.GradeMapper2"/>
    </mappers>

測試

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