首页 > 数据库 >mybatis中映射和注解在数据库进行增删改查的方法

mybatis中映射和注解在数据库进行增删改查的方法

时间:2024-07-30 19:29:05浏览次数:12  
标签:改查 update public 增删 sqlSession build student mybatis id

此两种方法都是基于maven项目的基础上运行

主要步骤如下:

1、在mevan中的pom文件添加依赖文件:

 2、在src目录下编写编写配置文件(mybatis-cfg.xml)

 3、编写实体类(Student.java)

 4、编写映射文件(StudentMapper.xml)

 5、编写测试文件

 6、调用JUnit 5进行调试

核心文件含义:

(1)mybatis-config.xml是Mybatis的核心配置文件,通过其中的配置可以生成SqlSessionFactory,也就是SqlSession工厂

(2)基于SqlSessionFactory可以生成SqlSession对象

(3)SqlSession是一个既可以发送SQL去执行,并返回结果,类似于JDBC中的Connection对象,也是Mybatis中至关重要的一个对象。

(4)Executor是SqlSession底层的对象,用于执行SQL语句

(5)MapperStatement对象也是SqlSession底层的对象,用于接收输入映射(SQL语句中的参数),以及做输出映射(即将SQL查询的结果映射成相应的结果)

pom文件所需添加的依赖:

<dependencies>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.22</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>
            1.2.12
        </version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.5</version>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter</artifactId>
        <version>RELEASE</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.example</groupId>
        <artifactId>javaTest</artifactId>
        <version>1.0-SNAPSHOT</version>
    </dependency>
</dependencies>

一、配置日志文件代码(可要可不要):

log4j.rootLogger=debug, stdout,R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
Log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=example.log
Log4j.appender.R.MaxFileSize=100KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=5
log4j.appender.R.layout=org.apache.log4j.PatternLayout
Log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n

二、核心配置文件代码:

<?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="develop">
        <environment id="develop">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/xsgl?serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mapper/StudentMapper.xml"/>//第一种:映射文件的地址
        <mapper class="com.jiazhong.Dao.StudentDao"/>//dao的接口位置
    </mappers>
</configuration>

三、1.第一种方法:

映射文件代码:

<?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="StudentMapper">
    <select id="findAll" resultType="com.jiazhong.pojo.Student">//javabean的地址,查询必须有
        select * from student//sql语句
    </select>
    <update id="insert">//添加
        insert into student values(null,"bb","男",22,"dd","2024-7-7")
    </update>
    <delete id="delete">//删除
        delete from student where id="19"
    </delete>
    <update id="update">//更新
        update student set name="aa",sex="bb",age=33,major="dd",time="2024-7-11" where id=25;
    </update>//根据id查找
    <select id="findById" resultType="com.jiazhong.pojo.Student">
        select * from student where id=#{id}
    </select>
    <update id="insertData">//动态插入
        insert into student values(null,#{name},#{sex},#{age},#{major},#{time})
    </update>
    <update id="updateData">//动态更新
        update student set name=#{name},sex=#{sex},age=#{age},major=#{major},time=#{time} where id=#{id};
    </update>
    <delete id="deleteData">//动态删除
        delete from student where id=#{id}
    </delete>
    <select id="findAll1" resultType="com.jiazhong.pojo.Student">//查询一列
        select ${cols} from student
    </select>
    <select id="findAll2" resultType="com.jiazhong.pojo.Student">//模糊查询
        select * from student where name like"%${name}%"
    </select>
    <select id="findAllAge" resultType="com.jiazhong.pojo.Student">//条件查询
        select * from student where 1=1
    <if test="minAge !=null">
    and age>#{minAge}
    </if>
        <if test="maxAge !=null">
    and age<![CDATA[<]]>#{maxAge}
     </if>
    </select>
    <select id="deleteByIds">
        delete from student where id in
    <foreach collection="array" open="(" item="id" separator="," close=")">
        #{id}
    </foreach>
    </select>
</mapper>

测试代码:

import com.jiazhong.pojo.Student;
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.apache.log4j.PropertyConfigurator;
import org.junit.jupiter.api.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

public class TestMybits {
    /**
     * 找所用数据
     * @throws IOException
     */
    @Test
    public  void findAll() throws IOException {
        TestMybits.info();
        InputStream resourceAsStream = Resources.getResourceAsStream("config/mybatis_config.xml");

        //获取一个工厂对象
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //通过工厂获取一个对象
        SqlSession sqlSession = build.openSession();
        List<Student> students = sqlSession.selectList("StudentMapper.findAll");
        for (Student stu:students){
            System.out.println("信息:" + stu);
        }
    }

    /**
     * 配置文件封装
     * @throws IOException
     */
    public static void info() throws IOException {
        Properties properties = new Properties();
        FileInputStream fileInputStream = new FileInputStream("src/main/resources/config/log4j.properties");
        properties.load(fileInputStream);
        PropertyConfigurator.configure(properties);
    }

    /**
     * 添加一条数据
     * @throws IOException
     */
    @Test
    public void insert() throws IOException {
        TestMybits.info();
        InputStream resourceAsStream = Resources.getResourceAsStream("config/mybatis_config.xml");

        //获取一个工厂对象
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //通过工厂获取一个对象
        SqlSession sqlSession = build.openSession();
        int update= sqlSession.update("StudentMapper.insert");
        sqlSession.commit();
        System.out.println("update = " + update);

    }

    /**
     * 删除一条数据
     * @throws IOException
     */
    @Test
    public void delete() throws IOException {
        TestMybits.info();
        InputStream resourceAsStream = Resources.getResourceAsStream("config/mybatis_config.xml");

        //获取一个工厂对象
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //通过工厂获取一个对象
        SqlSession sqlSession = build.openSession();
        int update= sqlSession.update("StudentMapper.delete");
        sqlSession.commit();
        System.out.println("update = " + update);

    }

    /**
     * 更新一条数据
     * @throws IOException
     */
    @Test
    public void update() throws IOException {
        TestMybits.info();
        InputStream resourceAsStream = Resources.getResourceAsStream("config/mybatis_config.xml");

        //获取一个工厂对象
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //通过工厂获取一个对象
        SqlSession sqlSession = build.openSession();
        int update= sqlSession.update("StudentMapper.update");
        sqlSession.commit();
        System.out.println("update = " + update);

    }

    /**
     * 根据id查数据
     * @throws IOException
     */
    @Test
    public void findById() throws IOException {
        TestMybits.info();
        InputStream resourceAsStream = Resources.getResourceAsStream("config/mybatis_config.xml");

        //获取一个工厂对象
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //通过工厂获取一个对象
        SqlSession sqlSession = build.openSession();
        List<Student> student = sqlSession.selectList("StudentMapper.findById",25);
        System.out.println("student = " + student);
    }

    /**
     * 添加数据传值
     * @throws IOException
     */
    @Test
    public void insertData() throws IOException {
        TestMybits.info();
        InputStream resourceAsStream = Resources.getResourceAsStream("config/mybatis_config.xml");

        //获取一个工厂对象
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //通过工厂获取一个对象
        SqlSession sqlSession = build.openSession();
        HashMap map=new HashMap();
        map.put("name","aa");
        map.put("sex","bb");
        map.put("age",33);
        map.put("major","ee");
        map.put("time","2024-8-8");
        int update= sqlSession.update("StudentMapper.insertData",map);
        sqlSession.commit();
        System.out.println("update = " + update);
    }

    /**
     * 更新数据传值
     * @throws IOException
     */
    @Test
    public void updateData() throws IOException {
        Student student = new Student();
        student.setName("bb");
        student.setSex("vv");
        student.setAge(33);
        student.setMajor("ff");
        student.setTime("2024-8-9");
        student.setId(29);
        TestMybits.info();
        InputStream resourceAsStream = Resources.getResourceAsStream("config/mybatis_config.xml");

        //获取一个工厂对象
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //通过工厂获取一个对象
        SqlSession sqlSession = build.openSession();
        int update= sqlSession.update("StudentMapper.updateData",student);
        sqlSession.commit();
        System.out.println("update = " + update);

    }

    /**
     * 删除数据传值
     * @throws IOException
     */
    @Test
    public void deleteData() throws IOException {
        TestMybits.info();
        InputStream resourceAsStream = Resources.getResourceAsStream("config/mybatis_config.xml");

        //获取一个工厂对象
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //通过工厂获取一个对象
        SqlSession sqlSession = build.openSession();
        int update= sqlSession.update("StudentMapper.deleteData",28);
        sqlSession.commit();
        System.out.println("update = " + update);

    }
    @Test
    public  void findAll1() throws IOException {
        TestMybits.info();
        InputStream resourceAsStream = Resources.getResourceAsStream("config/mybatis_config.xml");
        HashMap map = new HashMap();
        map.put("cols","name,sex");
        //获取一个工厂对象
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //通过工厂获取一个对象
        SqlSession sqlSession = build.openSession();
        List<Student> students = sqlSession.selectList("StudentMapper.findAll1",map);
        for (Student stu:students){
            System.out.println("信息:" + stu);
        }
    }
    @Test
    public  void findAll2() throws IOException {
        TestMybits.info();
        InputStream resourceAsStream = Resources.getResourceAsStream("config/mybatis_config.xml");
        HashMap map = new HashMap();
        map.put("name","bb");
        //获取一个工厂对象
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //通过工厂获取一个对象
        SqlSession sqlSession = build.openSession();
        List<Student> students = sqlSession.selectList("StudentMapper.findAll2",map);
        for (Student stu:students){
            System.out.println("信息:" + stu);
        }
    }
    @Test
    public  void findAllAge() throws IOException {
        TestMybits.info();
        InputStream resourceAsStream = Resources.getResourceAsStream("config/mybatis_config.xml");
        HashMap<String, Object> map = new HashMap<>();
        map.put("minAge",10);
        map.put("maxAge",30);
        //获取一个工厂对象
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //通过工厂获取一个对象
        SqlSession sqlSession = build.openSession();
        List<Student> students = sqlSession.selectList("StudentMapper.findAllAge",map);
        for (Student stu:students){
            System.out.println("信息:" + stu);
        }
    }
    @Test
    public void deleteByIds() throws IOException {
        TestMybits.info();
        InputStream resourceAsStream = Resources.getResourceAsStream("config/mybatis_config.xml");

        //获取一个工厂对象
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //通过工厂获取一个对象
        SqlSession sqlSession = build.openSession();
        Integer [] ids={17,18,24};
        int delete= sqlSession.delete("StudentMapper.deleteByIds",ids);
        sqlSession.commit();
        System.out.println("delete = " + delete);

    }


    public static void main(String[] args) throws IOException {

        TestMybits testMybits = new TestMybits();
//        testMybits.findAll();
        testMybits.insert();



    }
}

2.第二种:注解的方法连接数据库进行增删查改

接口代码:

import com.jiazhong.pojo.Student;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface StudentDao {
    @Select("select * from student")//sql语句
    List<Student> findAll();
    @Insert("insert into student values(null,#{name},#{sex},#{age},#{major},#{time})")
    void saveStudent(Student student);
    @Delete("delete from student where id=#{id}")
    void deleteStudent(int id);
    @Update("update student set name=#{name},sex=#{sex},age=#{age},major=#{major},time=#{time}where id=#{id}")
    void updateStudent(Student student);
    @Select("select * from student where id=#{id}")
    Student selectById(int id);
    @Select("select * from student where name like '%${value}%'")
    List<Student> selectByName(String name);
    @Select("select  count(*) from student")
    int selectTotal();
//    @Select("select * from user where sname=#{sname} and password=#{password}")
//    User login(@Param("sname") String sname,@Param("password") String password);
}

测试代码:

public class Student {
    private Integer id;
    private String name;
    private String sex;
    private Integer age;
    private String major;
    private String time;

    public Student() {
    }

    public Student(Integer id, String name, String sex, Integer age, String major, String time) {
        this.id = id;
        this.name = name;
        this.sex = sex;
        this.age = age;
        this.major = major;
        this.time = time;
    }

    /**
     * 获取
     * @return id
     */
    public Integer getId() {
        return id;
    }

    /**
     * 设置
     * @param id
     */
    public void setId(Integer id) {
        this.id = id;
    }

    /**
     * 获取
     * @return name
     */
    public String getName() {
        return name;
    }

    /**
     * 设置
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * 获取
     * @return sex
     */
    public String getSex() {
        return sex;
    }

    /**
     * 设置
     * @param sex
     */
    public void setSex(String sex) {
        this.sex = sex;
    }

    /**
     * 获取
     * @return age
     */
    public Integer getAge() {
        return age;
    }

    /**
     * 设置
     * @param age
     */
    public void setAge(Integer age) {
        this.age = age;
    }

    /**
     * 获取
     * @return major
     */
    public String getMajor() {
        return major;
    }

    /**
     * 设置
     * @param major
     */
    public void setMajor(String major) {
        this.major = major;
    }

    /**
     * 获取
     * @return time
     */
    public String getTime() {
        return time;
    }

    /**
     * 设置
     * @param time
     */
    public void setTime(String time) {
        this.time = time;
    }

    public String toString() {
        return "Stusent{id = " + id + ", name = " + name + ", sex = " + sex + ", age = " + age + ", major = " + major + ", time = " + time + "}";
    }

标签:改查,update,public,增删,sqlSession,build,student,mybatis,id
From: https://blog.csdn.net/2301_76908023/article/details/140769213

相关文章

  • Mybatis批量更新数据库错误
    问题:记录一次使用Mybatis批量更新数据库的错误,错误信息,Errorupdatingdatabase.Cause:org.postgresql.util.PSQLException:错误:字段"update_time"的类型为timestampwithouttimezone,但表达式的类型为text建议:你需要重写或转换表达式位置:391如下图,说我有一......
  • 设置mybatis 是否打印日志
    @Bean(name="dbzyqsV102SqlSessionFactory")//@Qualifier表示查找Spring容器中名字为blogDataSource的对象publicSqlSessionFactorydbzyqsV102SqlSessionFactory(@Qualifier("dbzyqsV102DataSource")DataSourcedatasource)throwsEx......
  • 一款新的超强的ORM框架 mybatis-mp !!!
    官网:https://mybatis-mp.cn1.单表查询SysUsersysUser=QueryChain.of(sysUserMapper).eq(SysUser::getId,1).eq(SysUser::getUserName,'admin').get();2.VO映射@Data@ResultEntity(SysUser.class)publicclassSysUserVo{p......
  • MyBatis-Plus学习笔记
    使用SpringBoot创建工程并添加依赖pom.xml版本:SpringBoot2.3JDK1.8<?xmlversion="1.0"encoding="UTF-8"?><!--定义项目元数据,基于MavenPOM4.0.0模型--><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.......
  • sharding-jdbc 兼容 MybatisPlus的动态数据源
    背景:之前的项目做读写分离的时候用的MybatisPlus的动态数据做的,很多地方使用的@DS直接指定的读库或者写库实现的业务;随着表数据量越来越大,现在打算把比较大的表进行水平拆分,准备使用ShardingJDBC实现,但是发现两者配合起来并不是那么顺利,网上大部分文章都是直接把整个Sharding的......
  • Javaweb简单的学生管理系统(增删改)
    学生servletimportjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjava.io.IOException;......
  • springboot整合mybatis
    第一部分:创建springboot文件 第一步:打开软件,点击file,点击new然后选择module,在右侧选择springboot第二步:选择配置和JDK以及java版本①选择maven类型②选择JDK1.8版本③选择java8版本④选择jar包类型http://t.csdnimg.cn/XeplRhttp://t.csdnimg.cn/XeplR第三步:选择......
  • MyBatisPlus分页查询
     一、导入依赖<!--MyBatis-plus的依赖--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.4</version></dependency><!--mysql的依赖--&......
  • v-for 进行列表的 增删改查
    通过对象下标替换属性值但是通过实践此方法是错误的,Vue监听的是students这个对象,而不是这个对象里面的数组信息,也就是说,改变里面的值,并不能在页面上实现更新的功能<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content=......
  • 实战:MyBatis适配多种数据库:MySQL、Oracle、PostGresql等
    概叙很多时候,一套代码要适配多种数据库,主流的三种库:MySQL、Oracle、PostGresql,刚好mybatis支持这种扩展,如下图所示,在一个“namespace”,判断唯一的标志是id+databaseId,刚好写了三个同样的方法,一个不带databaseId,两个带databaseId,此时当前库如果连接的是oracle则执行databaseId=......