初学Mybatis之 CRUD 增删改查

namespace 中的包名要和 Dao/Mapper 接口的包名一致

select:选择,查询语句

同理,还有 insert、update、delete 标签

id:对应的 namespace 中的方法名

resultType:sql 语句执行的返回值

parameterType:参数类型

先在 mysql 建表(id、name、pwd)

配置 Maven 环境(mysql、mybatis、junit)

MybatisUtils.java:

package com.demo.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;

public class MybatisUtils {

    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            //获取sqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

        /*
        有了SqlSessionFactory,就可以获得SqlSession的实例
        SqlSession提供了在数据库执行SQL命令所需的所有方法
        可以通过SqlSession实例来执行已映射的SQL语句
         */
        public static SqlSession getSqlSession(){
            return sqlSessionFactory.openSession();
        }
}

mybatis-config.xml:(resources 目录下)

<?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核心配置文件 -->
<configuration>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <!-- 每一个Mapper.xml都需要在Mybatis核心配置文件中注册 -->
    <mappers>
        <mapper resource="com/demo/dao/UserMapper.xml"/>
    </mappers>

</configuration>

 User.java:

package com.demo.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 + '\'' +
                '}';
    }
}

UserMapper 接口:

package com.demo.dao;

import com.demo.pojo.User;

import java.util.List;

public interface UserMapper {

    //查询全部用户
    List<User> getUserList();

    //根据ID查询用户
    User getUserById(int id);

    //insert插入用户
    int addUser(User user);

    //update修改用户
    int updateUser(User user);

    //delete删除用户
    int deleteUser(int id);
}

UserMapper.xml:

<?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">

<mapper namespace="com.demo.dao.UserMapper">

    <!-- select 查询语句 -->
    <select id="getUserList" resultType="com.demo.pojo.User">
        select * from mybatis.user
    </select>

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

    <!-- insert插入数据,对象中的属性可以直接取出来 -->
    <insert id="addUser" parameterType="com.demo.pojo.User">
        insert into mybatis.user(id,name,pwd) values(#{id},#{name},#{pwd});
    </insert>

    <!-- update更新数据 -->
    <update id="updateUser" parameterType="com.demo.pojo.User">
        update mybatis.user set name = #{name}, pwd = #{pwd} where id = #{id};
    </update>

    <!-- delete删除数据 -->
    <delete id="deleteUser" parameterType="int">
        delete from mybatis.user where id = #{id};
    </delete>

</mapper>

UserDaoTest.java:(test 目录下)

package com.demo.dao;

import com.demo.pojo.User;
import com.demo.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class UserDaoTest {

    //查询全部
    @Test
    public void test(){

        //获得SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.getUserList();

        for(User user : userList){
            System.out.println(user);
        }

        //关闭sqlSession
        sqlSession.close();
    }

    //根据id查询
    @Test
    public void getUserById(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        User user = mapper.getUserById(1);

        System.out.println(user);

        sqlSession.close();
    }

    //增删改需要提交事务
    //添加数据
    @Test
    public void addUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        mapper.addUser(new User(4, "张三4", "123"));

        //提交事务
        sqlSession.commit();

        sqlSession.close();
    }

    //修改数据
    @Test
    public void updateUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        mapper.updateUser(new User(4,"李四","111"));

        sqlSession.commit();

        sqlSession.close();
    }

    //删除数据
    @Test
    public void deleteUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        mapper.deleteUser(4);

        sqlSession.commit();

        sqlSession.close();
    }
}

总结:

1.编写接口

2.编写对应的 Mapper 中的 sql 语句

3.测试

select:

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

 insert:

    <insert id="addUser" parameterType="com.demo.pojo.User">
        insert into mybatis.user(id,name,pwd) values(#{id},#{name},#{pwd});
    </insert>

update:

    <update id="updateUser" parameterType="com.demo.pojo.User">
        update mybatis.user set name = #{name}, pwd = #{pwd} where id = #{id};
    </update>

delete:

    <delete id="deleteUser" parameterType="int">
        delete from mybatis.user where id = #{id};
    </delete>

注意:增删改需要提交事务 

相关推荐

  1. 初学Mybatis CRUD 增删

    2024-07-22 02:36:03       30 阅读
  2. Mybatis增删

    2024-07-22 02:36:03       73 阅读
  3. Mybatis增删

    2024-07-22 02:36:03       58 阅读
  4. gorm框架常用增删(CRUD)

    2024-07-22 02:36:03       62 阅读
  5. MyBaties-增删

    2024-07-22 02:36:03       67 阅读
  6. mybatis增删

    2024-07-22 02:36:03       31 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-22 02:36:03       168 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-22 02:36:03       185 阅读
  3. 在Django里面运行非项目文件

    2024-07-22 02:36:03       155 阅读
  4. Python语言-面向对象

    2024-07-22 02:36:03       169 阅读

热门阅读

  1. TensorFlow 的基本概念和使用场景

    2024-07-22 02:36:03       34 阅读
  2. Windows图形界面(GUI)-DLG-C/C++ - 列表视图(ListView)

    2024-07-22 02:36:03       32 阅读
  3. 大规模语言模型从理论到实践 高效模型微调

    2024-07-22 02:36:03       35 阅读
  4. [11 Qt CMake开发]

    2024-07-22 02:36:03       34 阅读
  5. 显示隐式-》初始化 & 类型转换

    2024-07-22 02:36:03       32 阅读
  6. ReentrantLock源码

    2024-07-22 02:36:03       33 阅读
  7. 向量数据库Milvus

    2024-07-22 02:36:03       38 阅读
  8. 在 ASP.NET Core Web API 中实现审计跟踪

    2024-07-22 02:36:03       30 阅读
  9. leetcode-56. 合并区间

    2024-07-22 02:36:03       33 阅读
  10. 后端开发: 如何去使用公共组件

    2024-07-22 02:36:03       28 阅读
  11. 初步认识css(1)

    2024-07-22 02:36:03       33 阅读