简单的Mybatis程序示例

1. 引入Mybatis组件

参考官网:https://mybatis.org/mybatis-3/zh/getting-started.html 下载mybatis组件:
在工程pom中引入:

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

引入jdbc和junit依赖

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.32</version>
        </dependency>

在项目工程resources路径下创建Mybatis基础配置文件mybatis-config.xml
image

内容如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "https://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?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper class="com.wcj.dao.UserMapper" />
  </mappers>
</configuration>

(可选)项目工程resources路径下创建db.properties文件,用于配置数据库信息,也可直接写死到mybatis的配置文件中

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8
username=root
password=123456
2. Mybatis工具类
package com.wcj.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.InputStream;

public class MybatisUtil {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public SqlSession getConnect() {
        return sqlSessionFactory.openSession();
    }
}
3. Mapper文件(sql接口文件)
public interface UserMapper {
    List<User> getUser();

    User getUserById(int id);

    int insertUser(User user);

    int updateUser(User user);

    int delUser(int id);
}
4. Mapper.xml文件(sql文件)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wcj.dao.UserMapper">
    <select id="getUser" resultType="com.wcj.pojo.User">
        select * from mybatis.user
    </select>

    <select id="getUserById" parameterType="int" resultType="com.wcj.pojo.User" >
        select * from mybatis.user where id = #{id}
    </select>

    <insert id="insertUser" parameterType="com.wcj.pojo.User" >
        insert into mybatis.user (`id`,`name`,`age`) values (#{id},#{name},#{age})
    </insert>

    <update id="updateUser" parameterType="com.wcj.pojo.User" >
        update mybatis.user set `name` = #{name} where id = #{id}
    </update>

    <delete id="delUser" parameterType="int" >
        delete from mybatis.user where id = #{id}
    </delete>
</mapper>
5. Junit测试
public class Mytest {
    @Test
    public void test_getUser() {
        SqlSession connect = MybatisUtil.getConnect();
        UserMapper mapper = connect.getMapper(UserMapper.class);
        List<User> users = mapper.getUser();

        for (User user : users) {
            System.out.println(user);
        }
        connect.close();
    }

    @Test
    public void test_getUserById() {
        SqlSession connect = MybatisUtil.getConnect();
        UserMapper mapper = connect.getMapper(UserMapper.class);
        User user = mapper.getUserById(1);

        System.out.println(user);
        connect.close();
    }

    @Test
    public void test_insertUser() {
        SqlSession connect = MybatisUtil.getConnect();
        UserMapper mapper = connect.getMapper(UserMapper.class);

        User user = new User(6, "大王", 35);
        mapper.insertUser(user);

        // 需要显示提交
        connect.commit();
        connect.close();
    }

    @Test
    public void test_updateUser() {
        SqlSession connect = MybatisUtil.getConnect();
        UserMapper mapper = connect.getMapper(UserMapper.class);

        User user = new User(5, "www", 18);
        mapper.updateUser(user);

        // 需要显示提交
        connect.commit();
        connect.close();
    }

    @Test
    public void test_delUser() {
        SqlSession connect = MybatisUtil.getConnect();
        UserMapper mapper = connect.getMapper(UserMapper.class);

        mapper.delUser(5);


        // 需要显示提交
        connect.commit();
        connect.close();
    }
}

截图:
image

常见错误和补充

1. xxxMapper.xml文件没有在mybatis配置文件mybatis-config.xml中注册:

image

解决办法
在mybatis配置文件中注册对应的mapper.xml文件:
image
注意:
当使用class标签绑定mapper文件时,需要满足以下条件:
1.接口和对应的mapper文件必须同名
2.接口和对应的mapper文件必须在同一个包下

参考:https://mybatis.net.cn/configuration.html#mappers
image

2. mapper.xml绑定异常或者找不到mapper.xml文件

image

排查和解决办法
1.排查mapper.xml的命名空间namespace是否和mapper接口文件的类名一致
2.排查mapper.xml的id和mapper接口文件中的方法名是否保持一致
3.查看mybatis配置文件中是否正确注册mapper.xml文件
4.排查maven打包导出mapper.xml是否正常
image

需要在pom文件中显示打包xml或者properties文件:

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

增加以上代码后能正常出包:

3. 当对象属性或者表字段太多时,可以适当使用map来传递参数

示例如下:

int insertUser2(Map userMap);
    <insert id="insertUser2" parameterType="map" >
        insert into mybatis.user (`name`,`age`) values (#{mapName},#{mapAge})
    </insert>
    @Test
    public void test_insertUser2() {
        SqlSession connect = MybatisUtil.getConnect();
        UserMapper mapper = connect.getMapper(UserMapper.class);

        Map<String, String> map = new HashMap<>();
        map.put("mapName", "map名字");
        map.put("mapAge", "555");
        mapper.insertUser2(map);

        // 需要显示提交
        connect.commit();
        connect.close();
    }
4. 模糊查询
List<User> getUser2(String key);
    <select id="getUser2" resultType="com.wcj.pojo.User" parameterType="String">
        select * from mybatis.user where name like #{key}
    </select>
    @Test
    public void test_getUser2() {
        SqlSession connect = MybatisUtil.getConnect();
        UserMapper mapper = connect.getMapper(UserMapper.class);
        List<User> users = mapper.getUser2("%王%");

        for (User user : users) {
            System.out.println(user);
        }
        connect.close();
    }

image

posted @ 2023-07-13 01:22  遥遥领先  阅读(26)  评论(0编辑  收藏  举报