当前位置: 首页 > news >正文

JavaWeb后端-JDBC、MyBatis

JDBC

Java DataBase Connectivity,java语言操作关系型数据库的一套API

入门程序

依赖项

<dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><version>8.0.33</version>
</dependency>

JDBC程序

public class JdbcTest {/*** JDBC入门程序*/@Testpublic void testUpdate() throws Exception {//1.注册驱动Class.forName("com.mysql.cj.jdbc.Driver");//2.获取数据库连接String url = "jdbc:mysql://localhost:3306/web01";String username = "root";String password = "1234";Connection connection = DriverManager.getConnection(url, username, password);//3.获取sql语句的执行对象Statement statement = connection.createStatement();//4.执行sql(仅限DML语句)int i = statement.executeUpdate("update user set age=25 where id=1");//DMLSystem.out.println("SQL语句执行完毕的影响的记录数:"+i);//5.释放资源statement.close();connection.close();}
}

查询数据

基于JDBC执行select语句,将查询结果封装到User对象中

ResultSet(结果集对象):ResultSet rs = statement.executeQuery()

  • next():将光标从当前位置向前移动一行,并判断当前行是否为有效行,返回值boolean
    true:有效行,当前行有数据
    false:无效行,当前行没有数据
  • getxxx(…):获取数据,可根据列的编号获取,也可根据列名获取(推荐)
    @Testpublic void testSelect(){String url = "jdbc:mysql://localhost:3306/web01";String username = "root";String password = "1234";Connection connection = null;PreparedStatement stmt = null;ResultSet rs = null;//封装查询结果try {//1.注册驱动Class.forName("com.mysql.cj.jdbc.Driver");//2.获取数据库连接connection = DriverManager.getConnection(url, username, password);//3.执行sqlString sql = "select * from user where username=? && password=?";//预编译SQLstmt = connection.prepareStatement(sql);stmt.setString(1, "fangyuan");stmt.setString(2, "123456");rs = stmt.executeQuery();//4.处理结果while (rs.next()) {User user = new User(rs.getInt("id"),rs.getString("username"),rs.getString("password"),rs.getString("name"),rs.getInt("age"));System.out.println(user);}} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();} finally {//5.释放资源try {if (rs != null) {rs.close();}if (stmt != null) {stmt.close();}if (connection != null) {connection.close();}} catch (SQLException e) {e.printStackTrace();}}}
}

预编译SQL

String sql = "select * from user where username=? && password=?";//预编译SQL

优势一:防止SQL注入,更安全
优势二:性能更高

MyBatis

MyBatis是一款持久层框架,用于简化JDBC的开发

查询所有用户数据

在这里插入图片描述

  • 准备工作:
    1、创建SpringBoot工程,引入Mybatis相关依赖
    2、准备数据库表user,实体类User
    3、配置Mybatis(在application.properties中)
  • 编写Mybatis程序:编写Mybatis持久层接口,定义SQL(注解)
# 配置数据库的连接信息
spring.datasource.url=jdbc:mysql://localhost:3306/web01
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=1234
@Mapper//应用程序在运行时会自动为该接口创建一个实现类对象(代理对象),该对象会作为Spring Bean对象加入到Spring容器中
public interface UserMapper {/*** 查询所有用户*/@Select("select * from user")public List<User> findAll();}
@SpringBootTest //SpringBoot单元测试的注解 - 当前测试类中的测试方法运行时,会启动SpringBoot项目 - IOC容器
class SpringbootMybatisQuickstartApplicationTests {@Autowiredprivate UserMapper userMapper;@Testpublic void testFindAll() {List<User> users = userMapper.findAll();users.forEach(System.out::println);}
}

数据库连接池

  • 一个容器,负责分配、管理数据库连接(资源重用)
  • 允许应用程序重复使用一个现有的数据库连接,而不是重新建立一个(提升系统响应速度)
  • 释放空闲时间超过最大空闲时间的连接,避免因为没有释放连接而引起的数据库连接遗漏(避免数据库连接遗漏)

切换数据库连接池:
在这里插入图片描述

增删改查

删除用户-delete

Mapper接口

@Mapper//应用程序在运行时会自动为该接口创建一个实现类对象(代理对象),该对象会作为Spring Bean对象加入到Spring容器中
public interface UserMapper {/*** 根据id删除用户*/@Delete("delete from user where id = #{id}")//public void deleteById(Integer id);public Integer deleteById(Integer id);
}
@SpringBootTest //SpringBoot单元测试的注解 - 当前测试类中的测试方法运行时,会启动SpringBoot项目 - IOC容器
class SpringbootMybatisQuickstartApplicationTests {@Autowiredprivate UserMapper userMapper;/*** 测试删除*/@Testpublic void testdeleteById() {Integer i = userMapper.deleteById(5);System.out.println("执行完毕后,影响的记录数:"+i);}
}

在这里插入图片描述

新增用户-insert

@Mapper//应用程序在运行时会自动为该接口创建一个实现类对象(代理对象),该对象会作为Spring Bean对象加入到Spring容器中
public interface UserMapper {/*** 添加用户*/@Insert("insert into user(username, password, name, age) values (#{username},#{password},#{name},#{age})")//大括号中写User对象的属性名public void insert(User user);
}
@SpringBootTest //SpringBoot单元测试的注解 - 当前测试类中的测试方法运行时,会启动SpringBoot项目 - IOC容器
class SpringbootMybatisQuickstartApplicationTests {@Autowiredprivate UserMapper userMapper;/*** 测试新增用户*/@Testpublic void testInsert() {User user = new User(null,"yuanlian","666888","元莲",24);userMapper.insert(user);}
}

修改用户-update

@Mapper//应用程序在运行时会自动为该接口创建一个实现类对象(代理对象),该对象会作为Spring Bean对象加入到Spring容器中
public interface UserMapper {/*** 更新用户*/@Update("update user set username=#{username},password=#{password},name=#{name},age=#{age} where id=#{id}")public void update(User user);
}
@SpringBootTest //SpringBoot单元测试的注解 - 当前测试类中的测试方法运行时,会启动SpringBoot项目 - IOC容器
class SpringbootMybatisQuickstartApplicationTests {@Autowiredprivate UserMapper userMapper;/*** 测试修改用户*/@Testpublic void testUpdateById() {User user = new User(6,"kuangman","666888","狂蛮",34);userMapper.update(user);}
}

查询用户-select

@Mapper//应用程序在运行时会自动为该接口创建一个实现类对象(代理对象),该对象会作为Spring Bean对象加入到Spring容器中
public interface UserMapper {/*** 查询用户*/@Select("select * from user where username=#{username} and password=#{password}")//public User findByUsernameAndPassword(@Param("username") String username, @Param("password") String password);public User findByUsernameAndPassword(String username, String password);

@Param注解的作用是为接口的方法形参起名字

@SpringBootTest //SpringBoot单元测试的注解 - 当前测试类中的测试方法运行时,会启动SpringBoot项目 - IOC容器
class SpringbootMybatisQuickstartApplicationTests {@Autowiredprivate UserMapper userMapper;/*** 测试查询用户*/@Testpublic void testFindByUsernameAndPassword() {User user = userMapper.findByUsernameAndPassword("kuangman","666888");System.out.println(user);}
}

基于官方骨架创建的springboot项目中,接口编译时会保留方法形参名,@Param注解可以省略(#{形参名})

XML映射配置

在这里插入图片描述
基本框架

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace=""></mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.it.mapper.UserMapper"><!--    resultType:查询返回的单条记录所封装的类型--><select id="findAll" resultType="com.it.pojo.User">select id, username, password, name, age from user</select></mapper>

原接口中的注解要注释掉

@Mapper//应用程序在运行时会自动为该接口创建一个实现类对象(代理对象),该对象会作为Spring Bean对象加入到Spring容器中
public interface UserMapper {/*** 查询所有用户*///@Select("select id, username, password, name, age from user")public List<User> findAll();
}

官方建议:使用注解来映射简单语句会使代码显得更加简洁,但对于稍微复杂一点的语句,Java 注解不仅力不从心,还会让你本就复杂的 SQL 语句更加混乱不堪。 因此,如果你需要做一些很复杂的操作,最好用 XML 来映射语句。

  • 配置XML映射文件的位置
    在这里插入图片描述
  • MybatisX插件

SpringBoot配置文件格式

SpringBoot提供了多种属性配置方式(properties、yaml、yml)
在这里插入图片描述
在这里插入图片描述

yml配置文件

格式:

  • 数值前面必须有空格,作为分隔符
  • 使用缩进表示层级关系,缩进时不能使用Tab键,只能用空格(idea自动将Tab转为空格)
  • 缩进空格数无要求,只要相同层级元素左侧对齐即可
  • “#” 表示注释

定义对象/Map集合
在这里插入图片描述
定义数组/List/Set集合
在这里插入图片描述
注意
在yml格式的配置文件中,若配置项的值是以0开头,值要用’'引起来。因为0开头的值在yml中表示八进制数值

spring:application:name: springboot-mybatis-quickstart#数据库的连接信息datasource:url: jdbc:mysql://localhost:3306/web01username: rootpassword: 1234#mybatis的配置信息
mybatis:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImplmapper-locations: classpath:mapper/*.xml
http://www.dtcms.com/a/549755.html

相关文章:

  • 网站访问流程改变WordPress界面
  • 聚合API平台如何重构AI开发效率?
  • 设计模式之单例模式:一个类就只有一个实例
  • 分布式数据库选型指南 (深入对比TiDB与OceanBase)
  • 模板方法模式:优雅地封装算法骨架
  • 有哪些做ppt用图片的网站有哪些免费咨询皮肤科医生在线
  • 理解 MySQL 架构:从连接到存储的全景视图
  • 电商网站 服务器易派客网站是谁做的
  • 大型语言模型(LLM)架构大比拼
  • 爱派(AiPy):一个让大语言模型直接操作Python完成任务
  • 【一加手机Bootloader解锁政策更新通知】
  • 什么是政企工作手机,有什么功能作用
  • 太原网站排名优化价格室内装修效果图网站有哪些
  • 深入探讨Python中三种核心数据结构:列表、字典和元组。
  • 建网站的几个公司通辽网站网站建设
  • 编辑 JAR 包内嵌套的 TXT 文件(Vim 操作)
  • 网站手机验证码如何做网站做链接代码
  • 无锡做网站6网站看不到预览图
  • Redis 限流最佳实践:令牌桶与滑动窗口全流程实现
  • *清理磁盘空间
  • 用什么软件做网站原型外贸退税流程及方法
  • 微软网站制作软件常见营销策略都有哪些
  • 全栈开源:一套源码快速构建电竞/体育直播平台(PC+H5+双端APP)
  • 淘宝网站维护用DW做的网站怎么弄成链接
  • 【C++】【常见面试题】最简版带大小和超时限制的LRU缓存实现
  • CSAPP实验2:Bomb
  • [人工智能-大模型-118]:模型层 - RNN状态记忆是如何实现的?是通过带权重的神经元,还是通过张量?
  • 手机做网站需要多少天国外代理ip地址和端口
  • Unity-WebGL开发——用IIS(Internet Information Services)部署webGL工程
  • 怎么仿制别人的网站一个网站的建设流程有哪些