Maven+Mybatis实现数据库增删改查

2023-05-16

Maven+Mybatis实现数据库增删改查

  • 1. 新建一个普通的Maven项目,在pom.xml导入maven依赖。
  • 2. 创建一个模块 在mybatis-config.xml编写mybatis的核心配置文件
  • 3. 编写mybatis工具类
  • 4. 编写代码:实体类
  • 5. 编写代码:dao接口
  • 6. 编写代码:接口实现类
  • 7. 测试(junit测试)
  • 8.注意事项:
    • 8.1 运行报错:Type interface dao.UserDao is not known to the MapperRegister
    • 8.2 运行报错:The error may exit in dao/UserMapper.xml
  • 9.运行结果:

1. 新建一个普通的Maven项目,在pom.xml导入maven依赖。

   <!--导入依赖-->
    <dependencies>
        <!-- 1. mysql驱动 2.mybatis 3.junit -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.22</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

2. 创建一个模块 在mybatis-config.xml编写mybatis的核心配置文件

<!--mybatis核心配置文件-->
<configuration>
  <!-- <properties resource="jdbc.properties"></properties>-->
    <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/manage_system?characterEncoding=UTF-8&amp;serverTimezone=GMT%2b8"/>
                <property name="username" value="root"/>
                <property name="password" value="520myself1996"/>
            </dataSource>
        </environment>
    </environments>

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

3. 编写mybatis工具类

创建工具类 从 XML 中构建 SqlSessionFactory(固定写法)(SqlSessionFactory -> sqlSession 把资源加载进来,并创建可执行sql的对象) 。关键点: 从"mybatis-config.xml"中构建SqlSessionFactory。

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

4. 编写代码:实体类

public class User {

    private String user_id;
    private String user_name;
    private String password;
    private String create_time;

    public String getUser_id() {
        return user_id;
    }

    public void setUser_id(String user_id) {
        this.user_id = user_id;
    }

    public void setUser_name(String user_name) {
        this.user_name = user_name;
    }

    public String getUser_name() {
        return user_name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getCreate_time() {
        return create_time;
    }

    public void setCreate_time(String create_time) {
        this.create_time = create_time;
    }

    @Override
    public String toString() {
        return "User{" +
                "user_id='" + user_id + '\'' +
                ", user_name='" + user_name + '\'' +
                ", password='" + password + '\'' +
                ", create_time='" + create_time + '\'' +
                '}';
    }

    public User() {   }
    public User(String user_id, String user_name, String password, String create_time) {
        this.user_id = user_id;
        this.user_name = user_name;
        this.password = password;
        this.create_time = create_time;
    }
}

5. 编写代码:dao接口

package dao;
import entity.User;
import java.util.List;

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

6. 编写代码:接口实现类

以前在接口实现类写JDBC一些操作数据集库的代码,现在可以建一个UserMapper.xml在xml写sql语句。

<!--namespace = 绑定一个对应的Dao/Mapper接口-->
<!--接口实现类由原来的接口实现类UserDaoImpl转变一个Mapper配置文件-->
<mapper namespace="dao.UserDao">
    <select id="getUserList" resultType="entity.User">
        select * from manage_system.user
    </select>
</mapper>

7. 测试(junit测试)

在test目录下绿色java下新建与main一样的dao的目录(推荐)

package dao;

import entity.User;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import utils.MybatisUtils;
import java.util.List;

public class UserDaoTest {

    @Test
    public void test(){
        //第一步:获取SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        // 执行sql语句
        UserDao userDao =  sqlSession.getMapper(UserDao.class);
        List<User> userList = userDao.getUserList();
        for (User user : userList) {
            System.out.println(user);
        }

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

    }
}

8.注意事项:

8.1 运行报错:Type interface dao.UserDao is not known to the MapperRegister

在第二步Mybatis核心配置文件中。

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

8.2 运行报错:The error may exit in dao/UserMapper.xml

(资源过滤问题) target生成目录中没有这个xml文件.
maven由于约定大于配置,我们之后可能遇到我们自己写的配置文件,无法被导出或者生效问题,默认配置资源放在resource下,现在我们却放在java
目录下。解决方案:在pom.xml中增加:

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

9.运行结果:

在这里插入图片描述

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Maven+Mybatis实现数据库增删改查 的相关文章

  • 如何保证缓存与数据库的一致性

    关系型数据库系统给我们带来许多惊艳的特性 xff0c 例如 xff1a ACID 但为了维护这些特性 xff0c 数据库的性能在高负载下也会下降 为了提高性能 xff0c 通常会在项目的应用层 xff08 处理业务逻辑 xff09 和存储层
  • linux自定义图标主题目录及启动路径

    启动图标 就是按windows键出现一大堆应用的快捷方式 xff08 xxxx desktop xff09 目录 xff1a usr share applications 图标文件目录 xff1a usr share icons
  • Centos7 yum升级内核

    1 查看当前内核版本 uname r 3 10 0 1160 25 1 el7 x86 64 uname a Linux localhost localdomain 3 10 0 1160 25 1 el7 x86 64 1 SMP Wed
  • Ubuntu上安装Git

    1 安装git span class token function apt get span span class token function install span span class token function git span
  • AE或PR2020版本驱动程序或显卡不兼容问题解决

    AE或PR2020版本驱动程序或显卡不兼容问题解决 建议系统提前备份 xff0c 防止后期出错 驱动程序不兼容 xff1a AE为例 1 点击修复 gt 跳转到浏览器界面 gt 建议驱动程序版本 xff08 27 20 100 8476 或
  • Qt调用js和js交互, QWebengine调用js

    QWebengine 调用js有两种方式 通过QWebChannel调用 写一个类然后继承QObject用于和js进行通信交互 ifndef TINTERACT OBJECT H define TINTERACT OBJECT H incl
  • LinuxMint KDE任务栏消失恢复

    桌面右击 gt 添加面板 gt 添加默认面板 就恢复了
  • 神奇的输入法——小狼毫——个性化设置

    电脑硬盘坏了 xff0c 重新换了硬盘 xff0c 自然就要把软件重新安装一遍 个人喜欢用 五笔输入法 xff0c 之前一直用的 极点五笔 xff0c 但是它一直没有更新 偶然间搜索到了 小狼毫 xff0c 用户评价都不错 xff0c 果断
  • MySQL explain字段总结

    目录 作用表组成id xff08 表的读取顺序 xff09 select type xff08 数据读取操作的操作类型 xff09 字段 type字段 possible key xff08 那些索引可以使用 xff09 key xff08
  • 查找 替换 细节

    查找内容 可以快速搜索每一处指定单词或词组 1 单击 编辑 菜单中的 查找 命令 2 在 查找内容 框内键入要查找的文字 3 选择其他所需选项 若要一次选中指定单词或词组的所有实例 xff0c 请选中 突出显示所有在该范围找到的项目 复选框
  • Anaconda和pip异常

    一 Anaconda异常 1 No module named unicodedata 正常使用时出现这个问题 xff0c 与其想着怎么解决 xff0c 不如直接重装python环境或者试试卸载并重新安装pip 卸载并重新安装pip请参考博客
  • Linux下批量替换tab到空格的转换

    将所有文件中的tab批量替换为空格 find type f exec sed i orig 39 s t g 39 43 其中 34 t 34 后面跟的是空格的数量 xff0c 我这里是4个空格 原链接 xff1a https stacko
  • fegin调用的时候数据格式转换为linkedhashmap

    在spring cloud项目开发中 xff0c 使用fegin进行远程调用 1 接口服务方返回类型为Map String Object 类型 2 接口调用方返回值类型也是Map String Object 3 通过fegin调用之后返回的
  • 在虚拟机上运行vxWorks

    Vxworks是一个嵌入式系统 xff0c 主要运行在arm ppc mips等嵌入式处理器上 xff0c 它同样可以运行在X86处理器上 风河公司开发的tornado开发环境就 包括了pentium版本 xff0c 并且发布了相应的bsp
  • 点乘和叉乘

    向量点乘 xff08 内积 xff09 和叉乘 xff08 外积 向量积 xff09 向量 向量是由n个实数组成的一个n行1列 xff08 nX1 xff09 或一个1行n列 xff08 1Xn xff09 的有序数组 xff1b 点乘 向
  • ​​Linux下ps -ef和ps aux的区别及格式详解​

    Linux下显示系统进程的命令ps xff0c 最常用的有 ps ef 和 ps aux 这两个到底有什么区别呢 xff1f 两者没太大差别 xff0c 讨论这个问题 xff0c 要追溯到Unix系统中的两种风格 xff0c System
  • Windows命令行操作

    打开 win 43 r然后输入cmd回车 命令 cd进入命令 dir显示命令
  • JDK源码之-java.lang.Object

    JDK源码之 java lang Object public final native Class lt gt getClass public native int hashCode public boolean equals Object
  • Docker安装Elasticsearch的遇到的那些坑

    1 根据百度到的一篇文章 https segmentfault com a 1190000004376504 下载其最新镜像 hangxin1940 docker elasticsearch cn v2 1 0 使用 docker run
  • APScheduler Execution of job “***“ skipped: maximum number of running instances reached (1)

    错误原因 有错误提示所说 xff0c 因为超过了最多实例个数 xff0c APScheduler的默认最大实例个数为1 xff0c 导致之后任务调用阻塞 xff0c 无法进行执行 解决办法 提高代码效率 xff0c 缩短代码运行时间 延长定

随机推荐

  • Spring boot + Spring Security + Thymeleaf 认证失败返回错误信息

    Spring boot 43 Spring Security 43 Thymeleaf 认证失败返回错误信息 Spring boot以其众多友谊的特性 xff0c 如零配置 微服务等 xff0c 吸引了很多的粉丝 而其与Spring Sec
  • Java经典面试题(其三)——JVM原理和调优

    Java经典面试题 xff08 其三 xff09 JVM原理和调优 一 什么是JVM JVM是Java Virtual Machine xff08 Java虚拟机 xff09 的缩写 xff0c JVM是一种用于计算设备的规范 xff0c
  • Spring Boot Starter的面试题

    Spring Boot Starter的面试题 1 常见的starter会包几个方面的内容 xff1f 分别是什么 xff1f span class hljs comment 常见的starter会包括下面四个方面的内容 span span
  • 个人经历:谈一谈的程序员求职途径

    个人经历 xff1a 谈一谈的程序员求职途径 互联网招聘网站的确是五花八门 xff0c 种类繁多 xff0c 在投递简历 xff0c 接听面试电话的过程中 xff0c 要擦亮眼睛 xff0c 慎重选择和沟通 我是去年跳槽的 xff0c 下面
  • JVM调优再学习

    JVM调优再学习 堆大小设置 JVM中最大堆大小有三方面限制 xff1a 相关操作系统的数据模型 xff08 32 bit还是64 bit xff09 限制 xff1b 系统的可用虚拟内存限制 xff1b 系统的可用物理内存限制 32位系统
  • Dubbo源码学习基础

    dubbo源码学习基础 Dubbo源码学习基础Java RMI 基本概念在 Dubbo 中使用注解自定义容错策略正确加载MyFilter类Dubbo可扩展机制实战Dubbo的SPI机制自定义一个LoadBalance扩展Dubbo 外部化配
  • ubuntu中Terminal消失

    Terminal不见了 安装Python 3 6 在Ubuntu 16 04 LTS 版本 警告 xff1a 在根据下面文章操作之后 xff0c 电脑终端关上之后再也打不开 xff0c 因为同时修改了很多东西 xff0c 所以排查了好久才找
  • MacVim学习总结

    Emacs和Vim都是程序员专用编辑器 xff0c Emacs被称为神的编辑器 xff0c Vim则是编辑器之神 至于两者到底哪个更好用 xff0c 网络上两大派系至今还争论不休 不过 xff0c 相比之下 xff0c Emacs更加复杂
  • Passbook对应系统配置 Eclipse Tomcat配置JavaWeb项目部署 Sysdeo Eclipse Tomcat Launcher plugin

    在 Eclipse J2EE Juno 43 Tomcat 6 用Tomcat Plugin配置Tomcat 应用时 xff0c 不想Copy一堆 jar文件到应用的lib目录中 xff0c 应该可以用Activate DevLoader在
  • Ubuntu或CentOS下Python源码安装,以及需要的依赖包,pip修复安装

    准备环境 依赖包 span class token function sudo span span class token function apt get span y update span class token operator a
  • Seasar2 框架学习笔记

    基本Seasar2 Web应用工程结构 Seasar2这个框架在日本十分的流行 Seasar2其实就是类似于Spring的一个提供DI功能的开源框架 xff0c 但比Sping轻量级 并且同 其它轻量级容器 不同的是 xff0c 完全不需要
  • Struts Tiles框架,标签库详解<tiles:insert page="facebook.jsp" />

    Tiles框架为创建Web页面提供了一种模板机制 xff0c 它能将网页的布局和内容分离 它允许先创建模板 xff0c 然后在运行时动态地将内容插入到模板中 Tiles 框架建立在JSP的include指令的基础上 xff0c 但它提供了比
  • 解决:弹出“Building workspace has encountered a problem. Error 方法

    开发过程中常遇到这种情况 xff0c 在打开eclipse的时候 xff0c 弹出对话框 xff0c 提示 Building workspace has encountered a problem Errors during build 解
  • flexpaper实现文档的在线预览

    在把文档的格式转换成swf格式以后 xff0c 现在该实现在线的预览 在线预览的方法有两种方式 第一种 xff1a 通过flashpaper实现文档的在线预览 第二种是通过flexpaper实现文档的在线预览 在博客中用到的是第二种方法 在
  • MySql可视化工具MySQL Workbench使用教程

    1 MySQL Workbench MySQL Workbench 为数据库管理员 程序开发者和系统规划师提供可视化的Sql开发 数据库建模 以及数据库管理功能 2 MySQL Workbench 的下载和安装 xff08 1 xff09
  • MAC OS命令行使用详解

    原文地址 xff1a http www renfei org blog mac os x terminal 101 html 最近学习苹果认证的 Mac OS X Support Essentials 教程 xff0c 看到 Command
  • 理论: 图论(14):最大强连通图算法 tarjan

    最大强连通图定义 在有向图G中 xff0c 如果两个顶点间至少存在一条路径 xff0c 称两个顶点强连通 strongly connected 如果有向图G的每两个顶点都强连通 xff0c 称G是一个强连通图 非强连通图有向图的极大强连通子
  • 手机开发之三:CoreApp的深入分析

    四 xff0e CoreApp的深入分析 目前参考代码里面的CoreApp所完成的工作比较多且杂 xff0c 主要说来有如下几件事 a 系统组件初始化 xff1b b 开机Logo的显示 xff1b c Sim卡检测和Pin码校验 xff1
  • 阿里云上运行rabbitmq docker镜像无法远程访问rabbitmq management

    原连接https blog csdn net u012884074 article details 87346960
  • Maven+Mybatis实现数据库增删改查

    Maven 43 Mybatis实现数据库增删改查 1 新建一个普通的Maven项目 xff0c 在pom xml导入maven依赖 2 创建一个模块 在mybatis config xml编写mybatis的核心配置文件3 编写mybat