MyBatis基本操作

MyBatis 是一款优秀的半自动的轻量级的持久层框架。

创建Maven项目

pom.xml 导入相关依赖

  • org.mybatis -> mybatis
  • mysql-connection-java -> mysql
  • org.projectlombok -> lombok
  • log4j -> log4j
<?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>org.example</groupId>
    <artifactId>MyBatis</artifactId>
    <version>1.0-SNAPSHOT</version>


    <dependencies>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.20</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

    </dependencies>

</project>
  • 配置 mapper 读取位置 ,解决Mapper配置文件读取不到的关键
<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
        </resource>
    </resources>
</build>

resources/config.xml

通过 config.xml 进行数据库的配置和相关Mapper的导入。

  • 约束
<?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>
    	<!-- SQL配置 -->
    	<!-- 连接配置 -->
    	<!-- 注册Mapper -->
    </configuration>
  • SQL 的相关配置
<settings>
	<!-- 打印SQL语句 -->
	<setting name="logImpl" value="STDOUT_LOGGING" />
</settings>
  • 连接配置
<environments default="mysql">
    <environment id="mysql">
        <transactionManager type="JDBC" />
        <dataSource type="POOLED">
            <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
            <property name="username" value="root"/>
            <property name="password" value="root"/>
            <property name="url" value="jdbc:mysql://localhost:3306/JavaWeb?userSSL=false&amp;allowPublicKeyRetrieval=true"/>
        </dataSource>
    </environment>
</environments>
  • 注册Mapper
<mappers>
   <!-- 注解形式注册 -->
   <mapper class="com.kawyang.repository.IClass" />
   <!-- 配置文件方式注册 -->
   <mapper resource="com/kawyang/mapper/IClassesMapper.xml" />
   <mapper resource="com/kawyang/mapper/IStudentMapper.xml" />
</mappers>

entity

创建实体类对象。

lombok 会通过以下注解快速

上一篇:YOLOV3目标检测框架搭建和训练自己模型的流程


下一篇:Excel新建报错注册表修复