原打算把Mysql操作数据库的一些知识写进去,但是感觉没必要,要是现在会的都是简单的增删改查,所以,这一篇,我直接从java操作数据库开始写,所以这一篇大致就是记一下JDBC、MyBatis、以及SpringBoot的配置文件
JDBC
JDBC是java最底层最基础的操作数据库的技术,这一部分因为之后用的少,我直接从代码开始看了。
java
@Test
public void testUpdata() throws ClassNotFoundException, SQLException {
//注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//获取数据库链接
String url = "jdbc:mysql://localhost:3306/web01";
String username = "root";
String password = "123456";
Connection connection = DriverManager.getConnection(url, username, password);
//获取SQL语句执行对象
Statement statement = connection.createStatement();
//执行SQL
int flag = statement.executeUpdate("update user set age = 25 where id = 1");//DML语句
System.out.println("sql语句执行完毕 影响记录数" + flag);
//释放资源
statement.close();
connection.close();
}
这是基本操作的几个步骤, 注册驱动 数据库连接 获取SQL语句执行对象 然后执行SQL 关流
在SQL语句,为了防止SQL注入,我们一般使用参数动态传递,也就是预编译SQL,不光可以防止SQL注入,而且性能更高,缓存会存储已编译的SQL语句。举个栗子
java
@Test
public void testSelect() {
String url = "jdbc:mysql://localhost:3306/web01";
String username = "root";
String password = "123456";
String sql = "SELECT id, username, password, name, age FROM user WHERE username = ? AND password = ?";
// 用于存储查询结果的 User 列表
List<User> userList = new ArrayList<>();
// JDBC 连接和查询
try (Connection connection = DriverManager.getConnection(url, username, password);
PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
// 设置 SQL 参数
preparedStatement.setString(1, "daqiao");
preparedStatement.setString(2, "123456");
// 执行查询
try (ResultSet resultSet = preparedStatement.executeQuery()) {
// 遍历结果集
while (resultSet.next()) {
// 将每一行数据封装到 User 对象中
User user = new User();
user.setId(resultSet.getInt("id"));
user.setUsername(resultSet.getString("username"));
user.setPassword(resultSet.getString("password"));
user.setName(resultSet.getString("name"));
user.setAge(resultSet.getInt("age"));
// 将 User 对象添加到列表
userList.add(user);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
// 输出查询结果
for (User user : userList) {
System.out.println(user);
}
}
-
JDBC程序执行DML语句:int rowsUpdated = pstmt.executeUpdate(); //返回值是影响的记录数
-
JDBC程序执行DQL语句:ResultSet resultSet = pstmt.executeQuery(); //返回值是查询结果集
MyBatis
MyBatis是一款优秀的持久层框架,用于简化JDBC的开发,也就是之前提到的DAO层。通过Mybatis就可以大大简化原生的JDBC程序的代码编写。在pom文件中导入Mybatis依赖即可使用。
在java中对于数据库的数据,一般都使用对象进行封装。
配置
然后在java文件夹的resouse中有一个数据库的配置文件application.properties,用于
配置数据库的连接信息
java
#数据库访问的url地址
spring.datasource.url=jdbc:mysql://localhost:3306/web
#数据库驱动类类名
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#访问数据库-用户名
spring.datasource.username=root
#访问数据库-密码
spring.datasource.password=root@1234
#mybatis的配置
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
但是遇到特别复杂的工程配置,一般使用application.yml进行配置 方便 直观 清晰
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl这条配置是查看SQL语句执行的日志信息
java
spring:
application:
name: springboot-mybatis-quickstart
#配置数据库连接信息
datasource:
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:mysql://localhost:3306/web01
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
mybatis:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mapper-locations: classpath:com.ght666.mapper/*.xml
编写
一般编写Mybatis程序 是在mapper包中编写Mybatis的持久层接口,定义SQL语句(注解)
java
package com.ght666.mapper;
import com.ght666.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper//应用程序在运行时会自动的为该接口创建一个实现类对象,并且会自动将该实现类对象存入IOC容器 -bean对象
public interface UserMapper {
@Select("select * from user")
public List<User> findAll();
}
- @Mapper注解:表示是mybatis中的Mapper接口
程序运行时,框架会自动生成接口的实现类对象(代理对象),并给交Spring的IOC容器管理
- @Select注解:代表的就是select查询,用于书写select查询语句
在创建出来的SpringBoot工程中,在src下的test目录下,已经自动帮我们创建好了测试类 ,并且在测试类上已经添加了注解 @SpringBootTest
,代表该测试类已经与SpringBoot整合。
该测试类在运行时,会自动通过引导类加载Spring的环境(IOC容器)。我们要测试那个bean对象,就可以直接通过@Autowired
注解直接将其注入进行,然后就可以测试了。
java
@SpringBootTest //springboot单元测试注解 当前测试类的测试方法运行时 会自动启动Springboot 产生IOC容器
class SpringbootMybatisQuickstartApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
public void testFindAll() {
List<User> userList = userMapper.findAll();
userList.forEach(System.out::println);//方法引用
}
}
数据库连接池
数据库连接池是个容器,负责分配、管理数据库连接(Connection),程序在启动时,会在数据库连接池(容器)中,创建一定数量的Connection对象

允许应用程序重复使用一个现有的数据库连接,而不是再重新建立一个
客户端在执行SQL时,先从连接池中获取一个Connection对象,然后在执行SQL语句,SQL语句执行完之后,释放Connection时就会把Connection对象归还给连接池(Connection对象可以复用)
释放空闲时间超过最大空闲时间的连接,来避免因为没有释放连接而引起的数据库连接遗漏,客户端获取到Connection对象了,但是Connection对象并没有去访问数据库(处于空闲),数据库连接池发现Connection对象的空闲时间 > 连接池中预设的最大空闲时间,此时数据库连接池就会自动释放掉这个连接对象
Spring默认连接池是Hikari(追光者),还有一个常用的是阿里巴巴开源的数据库连接池项目Druid
如果使用Druid连接池,先添加依赖,再在application配置文件中
引入数据库连接配置
java
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
Mybatis占位符
在Mybatis中,占位符是#{...}
生成的是预编译的SQL语句。例如:
java
/**
* 根据id删除
*/
@Delete("delete from user where id = #{id}")
public void deleteById(Integer id);
- Mybatis的提供的符号,有两个,一个是
#{...}
,另一个是${...}
,区别如下
|--------|-------------------------------|---------------|
| 符号 | 说明 | 场景 |
| #{...} | 占位符。执行时,会将#{...}替换为?,生成预编译SQL | 参数值传递 |
| ${...} | 拼接符。直接将参数拼接在SQL语句中,存在SQL注入问题 | 表名、字段名动态设置时使用 |
补充一个点:有一个注解,@param,这个注解的作用是为接口的方法形参起名字的。(由于用户名唯一的,所以查询返回的结果最多只有一个,可以直接封装到一个对象中)举个栗子
java
/**
* 根据用户名和密码查询用户信息
*/
@Select("select * from user where username = #{username} and password = #{password}")
public User findByUsernameAndPassword(@Param("username") String username, @Param("password") String password);
XML映射配置
Mybatis的开发有两种方式:注解 XML。使用Mybatis的注解方式,主要是来完成一些简单的增删改查功能。如果需要实现复杂的SQL功能,建议使用XML来配置映射语句,也就是将SQL语句写在XML配置文件中。
XML映射文件的名称与Mapper接口名称一致,并且将XML映射文件和Mapper接口放置在相同包下(同包同名) 如果不同包同名,可以在配置文件中添加配置
mybatis:
mapper-locations: classpath:com.ght666.mapper/*.xml

XML映射文件的namespace属性为Mapper接口全限定名,XML映射文件中sql语句的id与Mapper接口中的方法名一致,并保持返回类型一致
java
<?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.ght666.mapper.UserMapper">
<!--查询操作-->
<select id="findAll" resultType="com.ght666.pojo.User">
select * from user
</select>
</mapper>
SpringBoot配置文件
主要就是yml配置文件的语法:
-
大小写敏感
-
数值前边必须有空格,作为分隔符
-
使用缩进表示层级关系,缩进时,不允许使用Tab键,只能用空格(idea中会自动将Tab转换为空格)
-
缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
-
#
表示注释,从这个字符一直到行尾,都会被解析器忽略
yml文件中常见的数据格式。在这里我们主要介绍最为常见的两类:
-
定义对象或Map集合
-
定义数组、list或set集合
java
user:
name: zhangsan
age: 18
password: 123456
hobby:
- java
- game
- sport