MyBatis记录

题主使用的是Maven仓库

创建一个数据表

Mybatis原理

文件结构展示

resultType是返回类型,parameterType是当前类型

重点 属性,设置,别名

搭建环境

首先创建一个Maven仓库,导入依赖

分别导入mysql驱动依赖,mybatis依赖,junit测试工具依赖

<?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-v1.0</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>16</maven.compiler.source>
        <maven.compiler.target>16</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

创建一个pojo实体

创建一个持久化类

package com.mybatis.pojo;

public class User {
    private Integer user_id;
    private String user_name;
    private String pwd;

    public Integer getUser_id() {
        return user_id;
    }

    public void setUser_id(Integer user_id) {
        this.user_id = user_id;
    }

    public String getUser_name() {
        return user_name;
    }

    public void setUser_name(String user_name) {
        this.user_name = user_name;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    @Override
    public String toString() {
        return "User{" +
                "user_id=" + user_id +
                ", user_name='" + user_name + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}

创建核心配置文件

我们一般在resources资源文件夹中创建一个名为mybatis-config.xml的核心配置文件,一般我们命名核心配置文件名字为mybatis-config.xml

创建一个模块

创建一个核心配置文件,放置在resources文件夹里,一般核心配置文件名字都为mybatis-config.xml

关于一些对象方式:

SqlSession是数据库执行SQL命令的对象,相当于jdbc中的PreparedStatement

SqlSessionFactory 为工厂模式

SqlSessionFactoryBuilder 为创建者模式

  • 编写mybatis的核心配置文件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>
        <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/mybatis?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=utc"/>
                    <property name="username" value="root"/>
                    <property name="password" value="123456"/>
                </dataSource>
            </environment>
        </environments>
    </configuration>
    
  • 编写Mybatis工具类

    package com.hdt.utils;
    
    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;
    
    /**
     * @author Aity
     */
    public class MybatisUtils {
    
        private static SqlSessionFactory sqlSessionFactory;
        static {
            //1.获取Mybatis的SqlSessionFactory对象
            try {
                //配置文件的路径  resource资源文件夹中的文件不需要标准路径,只需要文件名即可
                String resource = "mybatis-config.xml";
                //字符流读取文件
                InputStream inputStream = Resources.getResourceAsStream(resource);
                //加载流
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //我们可以从中获得 SqlSession 的实例。SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。
        private static SqlSession getSqlSession(){
            SqlSession sqlSession = sqlSessionFactory.openSession();
            return sqlSession;
        }
    }
    

编写代码

  • 实体类

    package com.hdt.pojo;
    
    public class User {
        private int id;
        private String name;
        private String pwd;
    
        public User() {
        }
    
        public User(int id, String name, String pwd) {
            this.id = id;
            this.name = name;
            this.pwd = pwd;
        }
    
        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 String getPwd() {
            return pwd;
        }
    
        public void setPwd(String pwd) {
            this.pwd = pwd;
        }
    
        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", pwd='" + pwd + '\'' +
                    '}';
        }
    }
    
  • Dao接口

    public interface UserDao {
        List<User> getUserList();
    }
    
  • 接口实现类

    resultType为返回类型

    <?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">
    
    <!--namespace绑定一个Dao/Mapper接口-->
    <mapper namespace="com.hdt.dao.UserDao">
    <!--    id相当于JDBC中的String getUserList = select * from user-->
    <!--    resultType为返回类型,命名为全限定命名-->
        <select id="getUserList" resultType="com.hdt.pojo.User">
            select * from user
        </select>
    </mapper>
    

测试

注意点:

这个错误是因为Maven仓库约定大于配置,默认资源文件夹为resources,所以需要资源过滤设置

Caused by: org.apache.ibatis.exceptions.PersistenceException: 
### Error building SqlSession.
### The error may exist in com/hdt/dao/UserMapper.xml

解决方法,定义资源文件夹

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

可能会遇到的问题:

  1. 配置文件没有注册
  2. 绑定接口错误
  3. 方法名不对
  4. 放回类型不对
  5. Maven导入资源问题

${password} //为预加载

{password} //为占位符,相当于?如果没有输入占位,则结果为password

posted @ 2021-11-07 14:18  HeiDaotu  阅读(22)  评论(0编辑  收藏  举报