myBatis之增删改查

本文详细介绍了myBatis的入门步骤,包括创建数据库、Maven项目配置、编写Mapper接口、执行SQL(select,insert,update,delete)以及使用工具类简化操作。通过示例展示了如何根据ID查询、插入、更新和删除数据。
摘要由CSDN通过智能技术生成

目录

1. myBatis入门

2. 查找数据 select

2.1 查询所有数据

 2.1.2 抽取工具类

 2.1.3 修改测试类 

2.2 根据id查询数据

3. 新增数据 Insert 

4. 更新数据 Update 

5. 删除数据 Delete


1. myBatis入门

1.1 创建数据库和表

 1.2  创建一个maven项目,并导入相关依赖

1.3 添加依赖,在pom.xml文件中添加

<!--  添加坐标  -->
    <dependencies>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.9</version>
        </dependency>
        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.26</version>
        </dependency>
    </dependencies>

1.4 创建Stundet类

1.5 创建Mapper接口,把sql写在接口中的方法上

1.6 创建配置文件,用于声明数据库信息和接口位置

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

    <settings>
        <!--在控制台输出发送的sql日志-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <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/Student"/>
                <property name="username" value="root"/>
                <property name="password" value="sunyu123"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <!--声明含有sql的接口所在包-->
        <package name="mapper"/>
    </mappers>
</configuration>

2. 查找数据 select

2.1 查询所有数据

接口

测试 

import domain.User;
import mapper.UserMapper;
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 org.junit.Test;
import java.io.IOException;
import java.io.InputStream;


public class TestUserMapper {
    @Test
    public void testInsert() throws IOException {
        // 1.获得核心配置文件
        InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
        // 2.加载核心配置文件,获得连接工厂
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        // 3.获得连接Session
        SqlSession session = sqlSessionFactory.openSession();
        // 4.通过session获得映射类(mapper)
        UserMapper userMapper = session.getMapper(UserMapper.class);
        // 5.进行操作
        List<Student> studentList = studentMapper.selectAll();
        studentList.forEach(System.out::println);
        // 6.释放资源
        session.close();
    }
}

运行结果 

 2.1.2 抽取工具类

package utils;
import mapper.UserMapper;
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 sessionFactory;
    static {
        try {
            // 1 获得核心配置文件
            InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
            // 2.加载核心配置文件,获得连接工厂
            sessionFactory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 获得会话
    public static SqlSession getSqlSession() {
        SqlSession session = sessionFactory.openSession();
        return session;
    }

    // 释放资源
    public static void close(SqlSession session) {
        if (session != null) {
            // 事务打开了 需要提交
            session.commit();
            // 6.释放资源
            session.close();
        }
    }
}
2.1.3 修改测试类 

2.2 根据id查询数据

接口

import domain.Student;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;

public interface StudentMapper {
    // 根据id查询数据
    @Select("select * from student where id=#{id}")
    public Student selectById(@Param("id") Integer id);
}

 测试

import domain.Student;
import mapper.StudentMapper;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import utils.MybatisUtils;
import java.io.IOException;
import java.util.List;


public class TestStudentMapper {
    @Test
    public void testSelectById() throws IOException {
        SqlSession session = MybatisUtils.getSqlSession();
        // mapper映射
        StudentMapper studentMapper = session.getMapper(StudentMapper.class);
        // 操作
        Student student = studentMapper.selectById(1);
        System.out.println(student);
        // 释放资源
        MybatisUtils.close(session);
    }
}

3. 新增数据 Insert 

接口

public interface StudentMapper {
    // 新增数据
    @Insert("insert into student values (null,#{sname},#{age},#{gender},#                    
    {introduce})")
    public Integer insert(Student student);
}

测试 

import domain.Student;
import mapper.StudentMapper;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import utils.MybatisUtils;
import java.io.IOException;
import java.util.List;


public class TestStudentMapper {
    @Test
    public void testInsert() throws IOException {
        SqlSession session = MybatisUtils.getSqlSession();
        StudentMapper studentMapper = session.getMapper(StudentMapper.class);
        // 操作
        Student student = new Student(null,"张三",18,"女","666666666");
        studentMapper.insert(student);
        System.out.println(student);
        // 释放资源
        MybatisUtils.close(session);
    }
}

4. 更新数据 Update 

接口

import domain.Student;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

public interface StudentMapper {
    @Update("update student set sname=#{sname},age=#{age},gender=#{gender},introduce=#{introduce} where id=#{id}")
    public Integer update(Student student);
}

测试

import domain.Student;
import mapper.StudentMapper;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import utils.MybatisUtils;
import java.io.IOException;
import java.util.List;


public class TestStudentMapper {
    @Test
    public void testUpdate() throws IOException {
        SqlSession session = MybatisUtils.getSqlSession();
        StudentMapper studentMapper = session.getMapper(StudentMapper.class);
        // 操作
        Student student = new Student(3,"张三2",18,"女","hhhhhhhhh");
        studentMapper.update(student);
        System.out.println(student);
        // 释放资源
        MybatisUtils.close(session);
    }
}

5. 删除数据 Delete

接口

package mapper;
import domain.Student;
import org.apache.ibatis.annotations.*;
import java.util.List;

public interface StudentMapper {
    @Delete("delete from student where id=#{id}")
    public Integer delete(@Param("id") Integer id);
}

测试

import domain.Student;
import mapper.StudentMapper;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import utils.MybatisUtils;
import java.io.IOException;

public class TestStudentMapper {
    @Test
    public void testDelete() throws IOException {
        SqlSession session = MybatisUtils.getSqlSession();
        StudentMapper studentMapper = session.getMapper(StudentMapper.class);
        // 操作
        Integer res = studentMapper.delete(4);
        System.out.println(res);
        // 释放资源
        MybatisUtils.close(session);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值