文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

如何使用MyBatis框架实现增删改查(CRUD)操作

2023-05-18 20:36

关注

mybatis 介绍

Mybatis官方文档 :
http://www.mybatis.org/mybatis-3/zh/index.html

GitHub :https://github.com/mybatis/mybatis-3

代码演示

CREATE DATABASE `mybatis`;

USE `mybatis`;

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
`id` int(20) NOT NULL,
`name` varchar(30) DEFAULT NULL,
`pwd` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert  into `user`(`id`,`name`,`pwd`) values (1,'张三','123456'),(2,'李四','abcdef'),(3,'王五','987654');
<dependencies>
        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>
        <!--mybatis包-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <!--junit 测试包-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

该配置文件主要是配置连接mysql的基本信息及注册mapper(具体配置参考官方文档)

<?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.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=utf-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/xiezhr/Dao/UserMapper.xml"></mapper>
    </mappers>
</configuration>

查看官方文档,我们这里要封装一个工具类生成SqlSession对象,SqlSession用于后面的执行sql

package com.xiezhr.util;

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 MysqlUtil {

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

    }

    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }


}

各个属性得命名必须与数据库字段一一对应,具体如下所示,数据库对应字段为id,name,pwd

package com.xiezhr.pojo;

public class User {
    private int id;
    private String name;
    private String pwd;

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public User() {
    }

    public User(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}

该接口对应原来的dao,具体代码如下

package com.xiezhr.dao;

import com.xiezhr.pojo.User;

import java.util.List;

public interface UserMapper {
    List<User> getUserList();
}

由于我们使用了mybatis,所以这的xml文件相当于我们原来dao得实现类daoimpl。namespace属性对应着接口,不能写错,标签表示是个查询语句。id 属性对应着接口的方法,result Type代表返回得类型,即对应这pojo实体。具体代码如下

<?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.xiezhr.dao.UserMapper">
    <select id="getUserList" resultType="com.xiezhr.pojo.User">
     select * from mybatis.user;
    </select>
</mapper>
package com.xiezhr.dao;

import com.xiezhr.pojo.User;
import com.xiezhr.util.MysqlUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class TestUserDao {
    @Test
    public void selectUser(){
        SqlSession sqlSession = MysqlUtil.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.getUserList();

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

    }
}

经过测试后输出测试结果

D:\Java\jdk1.8.0_91\bin\java.exe -ea -Didea.test.cyclic.buffer.size=1048576 "-javaagent:D:\JetBrains\IntelliJ IDEA 2019.3.3\lib\idea_rt.jar=54576:D:\JetBrains\IntelliJ IDEA 2019.3.3\bin" -Dfile.encoding=UTF-8 -classpath "D:\JetBrains\IntelliJ IDEA 2019.3.3\lib\idea_rt.jar;D:\JetBrains\IntelliJ IDEA 2019.3.3\plugins\junit\lib\junit5-rt.jar;D:\JetBrains\IntelliJ IDEA 2019.3.3\plugins\junit\lib\junit-rt.jar;D:\Java\jdk1.8.0_91\jre\lib\charsets.jar;D:\Java\jdk1.8.0_91\jre\lib\deploy.jar;D:\Java\jdk1.8.0_91\jre\lib\ext\access-bridge-64.jar;D:\Java\jdk1.8.0_91\jre\lib\ext\cldrdata.jar;D:\Java\jdk1.8.0_91\jre\lib\ext\dnsns.jar;D:\Java\jdk1.8.0_91\jre\lib\ext\jaccess.jar;D:\Java\jdk1.8.0_91\jre\lib\ext\jfxrt.jar;D:\Java\jdk1.8.0_91\jre\lib\ext\localedata.jar;D:\Java\jdk1.8.0_91\jre\lib\ext\nashorn.jar;D:\Java\jdk1.8.0_91\jre\lib\ext\sunec.jar;D:\Java\jdk1.8.0_91\jre\lib\ext\sunjce_provider.jar;D:\Java\jdk1.8.0_91\jre\lib\ext\sunmscapi.jar;D:\Java\jdk1.8.0_91\jre\lib\ext\sunpkcs11.jar;D:\Java\jdk1.8.0_91\jre\lib\ext\zipfs.jar;D:\Java\jdk1.8.0_91\jre\lib\javaws.jar;D:\Java\jdk1.8.0_91\jre\lib\jce.jar;D:\Java\jdk1.8.0_91\jre\lib\jfr.jar;D:\Java\jdk1.8.0_91\jre\lib\jfxswt.jar;D:\Java\jdk1.8.0_91\jre\lib\jsse.jar;D:\Java\jdk1.8.0_91\jre\lib\management-agent.jar;D:\Java\jdk1.8.0_91\jre\lib\plugin.jar;D:\Java\jdk1.8.0_91\jre\lib\resources.jar;D:\Java\jdk1.8.0_91\jre\lib\rt.jar;F:\workspace_idea\Mybatis-test\mybatis-01\target\test-classes;F:\workspace_idea\Mybatis-test\mybatis-01\target\classes;D:\maven\repository\mysql\mysql-connector-java\5.1.46\mysql-connector-java-5.1.46.jar;D:\maven\repository\org\mybatis\mybatis\3.5.2\mybatis-3.5.2.jar;D:\maven\repository\junit\junit\4.12\junit-4.12.jar;D:\maven\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar" com.intellij.rt.junit.JUnitStarter -ideVersion5 -junit4 com.xiezhr.dao.TestUserDao,selectUser
Tue Apr 14 22:54:48 CST 2020 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
User{id=1, name='张三', pwd='322334'}
User{id=2, name='李四', pwd='123456'}
User{id=3, name='王五', pwd='123456'}

扩展

public interface UserMapper {
    //根据ID查询用户
    User selectUserById(int id);
}
<mapper namespace="com.xiezhr.dao.UserMapper">
    <select id="selectUserById" parameterType="int" resultType="com.xiezhr.pojo.User">
        select * from mybatis.user where id = #{id}
    </select>
</mapper>
@Test
    public void selectUserByid(){
        SqlSession sqlSession = MysqlUtil.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.selectUserById(1);
        System.out.println(user);
    }

测试通过

Wed Apr 15 23:08:00 CST 2020 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
User{id=1, name='张三', pwd='322334'}
public interface UserMapper {
    //根据用户名密码查询用户信息
    User selectUserByNP(@Param("name") String name,@Param("pwd") String pwd);
}
<mapper namespace="com.xiezhr.dao.UserMapper">
    <select id="selectUserByNP" resultType="com.xiezhr.pojo.User">
        select * from mybatis.user where name=#{name} and pwd=#{pwd}
    </select>
</mapper>
    @Test
    public void selectUserByNP(){
        SqlSession sqlSession = MysqlUtil.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.selectUserByNP("张三","322334");
        System.out.println(user);
    }

测试成功

Wed Apr 15 23:24:02 CST 2020 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
User{id=1, name='张三', pwd='322334'}

以上通过用户名和密码查询用户,传参还可以通过万能的map实现,具体代码如下

public interface UserMapper {
    //根据用户名和密码查询用户信息
    User queryUserByNP(Map<String,Object> map);
}
<mapper namespace="com.xiezhr.dao.UserMapper">
    <select id="queryUserByNP" parameterType="map" resultType="com.xiezhr.pojo.User">
        select * from mybatis.user where name=#{name} and pwd=#{pwd}
    </select>
</mapper>
 @Test
    public void queryUserByNp(){
        SqlSession sqlSession = MysqlUtil.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("name","张三");
        map.put("pwd","322334");
        User user = mapper.queryUserByNP(map);
        System.out.println(user);
    }
string wildcardname = “%smi%”;
list<name> names = mapper.selectlike(wildcardname);
<select id=”selectlike”>
select * from foo where bar like #{value}
</select>
string wildcardname = “smi”;
list<name> names = mapper.selectlike(wildcardname);
<select id=”selectlike”>
    select * from foo where bar like "%"#{value}"%"
</select>

接下来我们分别来实现insert、update、delete

insert

public interface UserMapper {
    //添加一条用户信息
    int addUser(User user);
}

2.在UserMapper.xml 中写insert 语句

<insert id="addUser" parameterType="com.xiezhr.pojo.User">
        insert into mybatis.user values(#{id},#{name},#{pwd})
</insert>
@Test
    public void addUser(){
        SqlSession sqlSession = MysqlUtil.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = new User(4, "大头儿子", "123456");
        mapper.addUser(user);
        sqlSession.commit();  //增删改一定要提交事务
        sqlSession.close();
    }

update

public interface UserMapper {
    //修改一条记录
    int updateUserById(int id);
}

2.在UserMapper.xml 中写insert 语句

<update id="updateUserById" parameterType="int">
        update mybatis.user set name='小头爸爸' where id=#{id}
</update>
    @Test
    public void updateUserById(){
        SqlSession sqlSession = MysqlUtil.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.updateUserById(4);
        sqlSession.commit();  //增删改一定要提交事务
        sqlSession.close();
    }

delete

public interface UserMapper {
    //根据ID删除一条记录
    int deleteUserById(int id);
}
}

2.在UserMapper.xml 中写insert 语句

<delete id="deleteUserById" parameterType="int">
        delete from mybatis.user where id=#{id}
</delete>
    @Test
    public void deletUserById(){
        SqlSession sqlSession = MysqlUtil.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.deleteUserById(4);
        sqlSession.commit();  //增删改一定要提交事务
        sqlSession.close();
    }

注意

可能出现问题说明:Maven静态资源过滤问题

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

在静态资源的过滤中,基本的元素有三种:

MyBatis是一款优秀的持久层框架,它可以帮助我们简化数据库操作的代码。本文介绍了MyBatis框架的基本概念和使用方法,以及如何使用MyBatis实现增删改查操作。在使用MyBatis进行开发时,需要注意一些细节问题,比如如何处理事务、如何使用Mapper接口等。此外,MyBatis还提供了一些高级特性,比如动态SQL、缓存等,可以帮助我们更加灵活地进行数据库操作。MyBatis是一款非常优秀的持久层框架,值得我们深入学习和使用。

到此这篇关于如何使用MyBatis框架实现增删改查(CRUD)操作的文章就介绍到这了,更多相关mybatis实现增删改查CRUD内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯