JDBC
- JDBC就是使用Java语言操作关系型数据库的一套API
简单步骤
1.创建工程,导入驱动jar包
2.注册驱动(Class.forName())
3.获取数据库连接(DriverManager)
4.定义sql语句
5.获取执行sql对象
6.执行sql
7.处理返回结果
8.释放资源
JDBCAPI详解
1.DriverManager
1.注册驱动
2.获取数据库连接(getConnection(url,user,password))
MYSQL5之后的驱动包,可以省略注册驱动的步骤
2.Connection
1.获取执行SQL的对象
普通执行SQL对象
Statement createStatement()
预编译SQL的执行SQL对象:防止SQL注入
PreparedStatement prepareStatement(sql)
执行存储过程的对象
CallableStatement prepareCall(sql)
2.管理事务
开启事务:setAutoCommit(boolean autoCommit):true为自动提交
提交事务:commit()
回滚事务:rollback()
3.Statement
1.执行SQL语句
int executeUpdate(sql):执行DML,DDL语句
ResultSet executeQuery(sql):执行DQL语句
返回值:ResultSet结果集对象
ResultSet:封装了DQL查询语句的结构
获取查询结果
next():将光标从当前位置向前移动一行,判断当前行是否为有效行,true表示这行有数据,false当前行没有数据
getXxx(参数):获取数据
参数:int类型:列的编号,从1开始
String类型:列的名称
4.PreparedStatement
预编译SQL语句并执行:
1.获取PreparedStatement对象
SQL语句中的参数值,使用?占位符来代替
connection.prepareStatement(sql)
2.设置参数值
setXxx(参数1,参数2):给?赋值
参数1:?的位置编号,从1开始
参数2:?的值
3.执行SQL
executeQuery()/executeUpdate()
预防SQL注入问题
SQL注入:通过操作输入来修改预先编译好的SQL语句,字符串的拼接产生的问题
好处:预编译SQL,性能更高
防止SQL注入:将敏感字符进行转义
1.预编译功能开启
useServerPrepStmts=true
2.配置MySQL执行日志
原理:
1.在获取preparedStatement对象时,将sql语句发送给mysql服务器进行检查,编译
2.执行时就不用再进行这些步骤了,速度更快
3.如果sql末班一样,则只需要进行一次检查,编译
数据库连接池
简介
- 数据库连接池是一个容器,负责分配,管理数据库连接
- 好处:
- 资源重用
- 提升系统响应速度
- 避免数据库连接遗漏
数据库连接池实现
-
标准接口:DataSource
- 官方提供的数据库连接池标准接口,由第三方实现此接口
- 功能:获取连接
-
常见数据库连接池
DBCP、C3P0、Druid
Druid连接池是阿里巴巴开源的数据库连接池项目
功能强大,性能优秀
使用步骤:
1.导入jar包
2.定义配置文件
3.加载配置文件
4.获取数据库连接池对象
5.获取连接
//3.加载配置文件
Properties prop = new Properties();
prop.load(new FileInputStream("jdbc/src/druid.properties"));
//4.获取数据库连接池对象
DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
//5.获取连接
Connection conn = dataSource.getConnection();
Maven
- Maven是专门用于管理和构建Java项目的工具,主要功能
- 提供了标准化的项目结构
- 提供了标准化的构建流程(编译、测试、打包、发布)
- 提供了一套依赖管理机制
Maven仓库分类
本地仓库:自己计算机上的一个目录
中央仓库:由Maven团队维护的全球唯一的仓库
地址:https://repo1.maven.org/maven2/
远程仓库(私服):由公司团队搭建的私有仓库
安装配置步骤
1.解压apache-maven-3.6.1.rar既安装完成
2.配置环境变量为安装路径的bin目录到path系统变量下
3.配置本地仓库:修改conf/settings.xml中的<localRepository>为一个指定的本地子目录
4.配置远程仓库(私服):修改conf/settings.xml中的<mirrors>标签,为其添加子标签
IDEA配置Maven环境
1.File-->Settings
2.搜索maven
3.设置IDEA使用本地安装的Maven,并修改配置文件路径
坐标详解
什么是坐标
Maven中的坐标是资源的唯一标识
使用坐标来定义项目或引入项目中需要的依赖
Maven坐标主要组成
<groupId>:定义当前Maven项目隶属组织名称(域名反写)
<artifactld>:定义当前Maven项目名称(通常是模块名称)
<version>:定义当前的项目版本号
IDEA中Maven项目导入
1.选择右侧Maven面板,点击+号
2.选中对应项目的pom.xml文件,双击即可
3.如果没有Maven面板,选择View->Appearance->Tool Window Bars
锁定JDK版本
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
依赖管理
1.在pom.xml文件中编写<dependencies>标签
2.在<dependencies>标签中使用<dependency>引入坐标
3.定义坐标的groupa,artifactld,version
4,点击刷新按钮,使坐标生效
依赖范围
通过设置坐标的依赖范围<scope>,可以设置对应jar包的作用范围:编译环境、测试环境、运行环境
依赖范围 | 编译classpath | 测试classpath | 运行classpath | 例子 |
---|---|---|---|---|
compile | y | y | y | logback |
test | - | y | - | junit |
provided | y | y | - | servlet-api |
runtime | - | y | y | jdbc驱动 |
system | y | y | - | 存储在本地的jar包 |
Mybatis
-
概念:
- Mybatis是一款用于简化JDBC开发的持久层框架,免除了几乎所有的JDBC代码以及设置参数和获取结果集的工作
- 持久层负责将数据保存到数据库的那一层代码
- JavaEE三层架构:表现层、业务层、持久层
-
框架
- 框架是一个半成品软件,是一套可复用的、通用的软件基础代码模型
- 在框架基础上构建软件,编写更加高效、规范、通用、可扩展
mybatis操作步骤
1.在数据库中创建表,添加数据
2.创建模块,导入依赖坐标,单独使用只需要将mybatis的jar包导入classpath路径下就可以了
3.编写Mybatis核心配置文件-->替换连接信息,解决硬编码问题
官方网址:https://mybatis.org/mybatis-3/zh/index.html
4.编写SQL映射文件-->统一管理sql语句,解决硬编码问题
5.编码
1.定义POJO类
2.加载核心配置文件,获取SqlSessionFactory对象
3.获取SqlSession对象,执行SQL语句
4.释放资源
代码示例:
第三步:
<?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>
<typeAliases>
<package name="com.itheima.pojo"/>
</typeAliases>
<!--
environments:配置数据库连接环境信息。可以配置多个environment,通过default属性切换不同的environment
-->
<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://127.0.0.1:3306/db1?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="123"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--加载sql映射文件-->
<mapper resource="StudentMapper.xml"/>
</mappers>
</configuration>
4.SQL映射文件
<?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="haha">
<select id="selectAll" resultType="com.itheima.pojo.Student">
select * from student
</select>
<delete id="deleteById">
delete from student where id=2
</delete>
<update id="updateById" parameterType="com.itheima.pojo.Student">
update student set name="zhangsan",age=21 where id=2
</update>
<insert id="insertById">
insert into student(id,name,age) values(1,"zhangsan",13)
</insert>
</mapper>
5.编码
//1. 加载mybatis的核心配置文件,获取 SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2. 获取SqlSession对象,用它来执行sql
SqlSession sqlSession = sqlSessionFactory.openSession(true);
//3. 执行sql
// List<Student> users = sqlSession.selectList("haha.selectAll"); //参数是一个字符串,该字符串必须是映射配置文件的namespace.id
// System.out.println(users);
// int delete = sqlSession.delete("haha.deleteById");
// System.out.println(delete);
int insert = sqlSession.insert("haha.insertById");
System.out.println(insert);
// int update = sqlSession.update("haha.updateById");
// System.out.println(update);
//4. 释放资源
sqlSession.close();
Mapper代理开发
Mapper代理的步骤
1.定义与SQL映射文件同名的Mapper接口,并且将Mapper接口和SQL映射文件放置在同一目录下
2.设置SQL映射文件的namespace属性为Mapper接口全限定名
例:<mapper namespace="com.itheima.mapper.StudentMapper">
3.在Mapper接口中定义方法,方法名就是SQL映射文件中SQL语句的id,并保持参数类型和返回值类型一致
4.编码
例:
//1. 加载mybatis的核心配置文件,获取 SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2. 获取SqlSession对象,用它来执行sql
SqlSession sqlSession = sqlSessionFactory.openSession();//此方法可设置自动提交事务true
//3.通过SqlSession的getMapper方法获取Mapper接口的代理对象
StudentMapper stuMapper =sqlSession.getMapper(StudentMapper.class);
List<Student> students = stuMapper.selectAll();
System.out.println(students);
//4. 释放资源
sqlSession.close();
注意:如果Mapper接口名称和SQL映射文件名称相同,并在同一目录下,则可以使用包扫描的方式简化SQL映射文件的加载
mybatis-config.xml设置mapper代理的方式加载映射文件
<mappers>
<!--Mapper代理包扫描加载所有SQL映射文件-->
<package name="com.itheima.mapper"/>
</mappers>
配置文件完成增删改查
增删改查编写顺序
1.编写接口方法
2.编写SQL语句:SQL映射文件
3.执行方法,测试
表字段名与实体类属性名不一样,不能自动封装数据
解决方法
1.起别名:对不一样的列名起别名,让别名和实体类的属性名一样
缺点:每次查询都要定义一次别名
sql片段
缺点:不灵活
2.resultMap:
id:唯一标识
type:映射的类型,支持别名
<!--
id:完成主键字段的映射
result:完成一般字段的映射
column:表的列名
property:实体类的属性名
-->
1.定义resultMap标签
2.在select标签中,使用resultMap属性替换resultType属性
例: <resultMap id="resultBrand" type="brand">
<result column="brand_name" property="brandName"/>
<result column="company_name" property="companyName"/>
</resultMap>
<select id="selectAll" resultMap="resultBrand">
select *
from tb_brand;
</select>
查看详情
参数占位符
#{} 会将其替换为?,防止SQL注入
${} 字符串拼接,存在SQL注入问题
参数传递时:#{}
parameterType:指定参数类型,可以省略
特殊字符的处理
1.转义字符
2.CDATA区
条件查询
参数接收的方式
1.散装参数:如果方法中有多个参数,需要使用@Param("SQL语句里的占位符名称")
2.对象参数:对象的属性名称和参数占位符名称一致
3.Map集合的参数:Map集合的key名和参数占位符的名称一致
动态SQL(是Mybatis最强的功能之一)
1.if标签
test:逻辑表达式
2.where标签:替换where关键字
解决的问题:第一个条件不需要逻辑运算符
例:
<select id="selectByCondition" resultMap="resultBrand">
select *
from tb_brand
<where>
<if test="brandName!=null and brandName!=''">
and brand_name like #{brandName}
</if>
<if test="companyName!=null and companyName!=''">
and company_name like #{companyName}
</if>
<if test="status!=null">
and status = #{status}
</if>
</where>
</select>
3.choose(when,otherwise):类似Java中的switch语句
例
<select id="selectByConditionSingle" resultMap="resultBrand">
select *
from tb_brand
<where>
<choose>
<when test="brandName!=null and brandName!=''">
brand_name like #{brandName}
</when>
<when test="companyName!=null and companyName!=''">
company_name like #{companyName}
</when>
<when test="status!=null">
status = #{status}
</when>
</choose>
</where>
</select>
4.添加:设置主键返回useGeneratedKeys="true" keyProperty="id"
<insert id="insertBrand" useGeneratedKeys="true" keyProperty="id">
insert into
tb_brand(brand_name,company_name,ordered,
description,status)
values (#{brandName},#{companyName},
#{ordered},#{description},#{status});
</insert>
5.set标签
<update id="updateBrand">
update tb_brand
<set>
<if test="brandName!=null and brandName!=''">
brand_name=#{brandName},
</if>
<if test="companyName!=null and companyName!=''">
company_name=#{companyName},
</if>
<if test="ordered!=null">
ordered=#{ordered},
</if>
<if test="description!=null and description!=''">
description=#{description},
</if>
<if test="status!=null">
status=#{status}
</if>
</set>
where id=#{id}
</update>
6.foreach
mybatis会将数组参数,封装为一个Map集合
默认:array=数组
使用@Param注解改变map集合的默认key的名称
批量删除
<delete id="deleteByIds">
delete from student where id in
<foreach collection="ids或者array" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</delete>