Mybatis步骤分解实现一个增删改查程序

时间:2022-12-26

1.idea新建Maven项目Mybatis-study 将项目里的src文件夹删掉 依次将此项目作为父项目

2.在Mybatis-study中新建模块mybatis-01

在mybatis的pom文件中可以看到其父项目为ybatis-study

<parent>
    <artifactId>MyBatis-study</artifactId>
    <groupId>org.example</groupId>
    <version>1.0-SNAPSHOT</version>
</parent>

3. 在Mybatis-study的pom.xml中引入如下jar包

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.9</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.29</version>
    </dependency>
  </dependencies>

4.将IDEA和MySQL数据库建立连接:

根据实际情况填写user和password 填写之后点击Test Connection

测试成功之后点击Schemas选择你要链接的数据库

5.新建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/smbms?useSSL=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/kero/dao/UserMapper.xml" />
    </mappers>
</configuration>

6.创建实体类User 注意:实体类中成员变量名要和数据库表中字段名完全一致

package com.kero.pojo;
public class User {
    private int id;
    private String name;
    private String password;
    public User() {
    }
    public User(int id, String name, String password) {
        this.id = id;
        this.name = name;
        this.password = password;
    }
    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 getpassword() {
        return password;
    }
    public void setpassword(String pwd) {
        this.password = pwd;
    }
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd='" + password + '\'' +
                '}';
    }
}

7.编写工具类Utils

package com.kero.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;
//sqlSessionFactory
public class MyBatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            //使用Mybatis第一步 获取sqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
/*
既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。SqlSession
 提供了在数据库执行 SQL 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。例如:
 */
        public static SqlSession getSqlSession(){
            return sqlSessionFactory.openSession();
        }
}

8.定义接口

package com.kero.dao;
import com.kero.pojo.User;
import java.util.List;
public interface UserMapper {
  //查询全部用户
    List<User> getUserList();
    //根据ID查询用户
    User getUserByID(int id);
    //insert一个用户
    int addUser(User user);
  //修改一个用户
  int updateUser(User user);
  //删除一个用户
  int deleteUser(int id);
}

9.定义Mapper文件 这里的Mapper文件相当于原来传统方式中接口的实现类

<?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会绑定一个对应的Mapper接口-->
<mapper namespace="com.kero.dao.UserMapper">
    <select id="getUserList" resultType="com.kero.pojo.User">
        select * from smbms.user
    </select>
        <select id="getUserByID" parameterType="int" resultType="com.kero.pojo.User">
            select * from smbms.user where id = #{id}
        </select>
    <insert id="addUser" parameterType="com.kero.pojo.User">
        insert into smbms.user (id, name, password) VALUES (#{id},#{name},#{password})
    </insert>
    <update id="updateUser" parameterType="com.kero.pojo.User">
       update smbms.user set name=#{name},password=#{password} where id = #{id}
    </update>
    <delete id="deleteUser" parameterType="int">
        delete from smbms.user where id = #{id}
    </delete>
</mapper>

10.编写测试类

import com.kero.dao.UserMapper;
import com.kero.pojo.User;
import com.kero.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class test {
    @Test
    public void test(){
        SqlSession session = MyBatisUtils.getSqlSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        List<User> userList = mapper.getUserList();
        for (User l:userList) {
            System.out.println(l.toString());
        }
        session.close();
    }
    @Test
    public void testgetUserByID(){
        SqlSession session = MyBatisUtils.getSqlSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        User userByID = mapper.getUserByID(1);
        System.out.println(userByID);
        session.close();
    }
    //增删改需要提交事务
    @Test
    public void testaddUser(){
        SqlSession session = MyBatisUtils.getSqlSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        int zhhgf = mapper.addUser(new User(10, "zhhgf", "1k23jbjk"));
        System.out.println(zhhgf);
        session.commit();
        //提交事务
        session.close();
    }
    @Test
    public void testupdateUser(){
        SqlSession session = MyBatisUtils.getSqlSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        int i = mapper.updateUser(new User(8,"asdfsdf","234sdfs"));
        session.commit();
        //提交事务
        session.close();
    }
    @Test
    public void testdeleteUser(){
        SqlSession session = MyBatisUtils.getSqlSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        int i = mapper.deleteUser(8);
        session.commit();
        //提交事务
        session.close();
    }
}

11.测试查询功能 : 输出结果与数据库表中数据

User{id=1, name='Sugawara Ryota', pwd='8X8Jq7HVNs'}

User{id=2, name='Shawn Mills', pwd='R78IHGDSXr'}

User{id=3, name='Matsuda Hina', pwd='mUi3CVA7mc'}

User{id=4, name='Cynthia Hawkins', pwd='NO1EwWbOs9'}

User{id=5, name='Rachel Bennett', pwd='YefuPVxzb9'}

tips:

如果一切配置正常但出现java.lang.ExceptionInInitializerError

Caused by org.apache.ibatis.execeptions.PersistenceExecepyion错误

是因为:maven由于它的约定大于配置 我们写的配置文件可能会出现无法被导出或者生效的问题解决方案 在pom.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>

到此这篇关于Mybatis步骤分解实现一个增删改查程序的文章就介绍到这了,更多相关Mybatis增删改查内容请搜索html5模板网以前的文章希望大家以后多多支持html5模板网!

上一篇:SpringBoot项目引入第三方sdk jar包的解决方案 下一篇:Spring深入讲解实现AOP的三种方式

相关文章

最新文章