一、JDBC
1.JDBC 简介
- JDBC 概念:
JDBC 就是使用Java语言操作关系型数据库的一套API
全称:(Java DataBase Connectivity)Java 数据库连接 - JDBC本质:
官方(sun公司)定义的一套操作所有关系型数据库的规则,即接口
各个数据库厂商去实现这套接口,提供数据库驱动jar包
我们可以使用这套接口(JDBC)编程,真正执行的代码是驱动jar包中的实现类 - JDBC 好处:
各数据库厂商使用相同的接口,Java代码不需要针对不同数据库分别开发
可随时替换底层数据库,访问数据库的Java代码基本不变
2.JDBC 快速入门
-
创建工程,下载驱动jar包
mysql-connector-java-8.0.24.jar
导入驱动jar包
-
注册驱动
Class.forName(“com.mysql.jdbc.Driver”); -
获取连接
Connection conn= DriverManager.getConnection(url, username, password); -
定义SQL语句
String sql = “update…” ; -
获取执行SQL对象
Statement stmt = conn.createStatement(); -
执行SQL
stmt.executeUpdate(sql); -
处理返回结果
-
释放资源
//1.注册驱动类
Class.forName("com.mysql.jdbc.Driver");
//2.创建连接对象
String url="jdbc:mysql://localhost:3306/users";
String username="root";
String password="685470";
Connection connection = DriverManager.getConnection(url,username,password);
//3.从连接对象中获取执行SQL语句的对象。
Statement statement = connection.createStatement();
//4.执行语句
String sql="insert into student value (11,'jie',2000100108)";
int i = statement.executeUpdate(sql);//返回受影响的行数。
//5.关闭对象
statement.close();
connection.close();
3.JDBC API详解
3-1 DriverManager
- 注册驱动
DriverManager.registerDriver(new Driver());
- 获取数据库连接
Connection connection = DriverManager.getConnection(url,username,password);
3-2 Connection
-
获取执行 SQL的对象
- 普通执行SQL对象
Statement createStatement()
Statement statement = connection.createStatement();
- 预编译SQL的执行SQL对象:防止SQL注入
PreparedStatement prepareStatement (sql) - 执行存储过程的对象
CallableStatement prepareCall (sql)
- 普通执行SQL对象
-
管理事务
-
JDBC 事务管理:Connection接口中定义了3个对应的方法
开启事务:setAutoCommit(boolean autoCommit):true为自动提交事务;false为手动提交事务,即为开启事务
提交事务:commit()
回滚事务:rollback() -
举例
-
try
{
//开启事务
connection.setAutoCommit(false);
String sql1="insert into student value (52,'j50',2000100108)";
String sql2="insert into student value (53,'j51',2000100108)";
int i1 = statement.executeUpdate(sql1);
int i2 = statement.executeUpdate(sql2);
//提交事务
connection.commit();
} catch (Exception e)
{
//回滚事务
connection.rollback();
throw new RuntimeException(e);
}
3-3 Statement
执行SQL语句
1. int executeUpdate(sql):执行DML、DDL语句
int返回值:
(1)DML语句影响的行数
(2)DDL语句执行后,执行成功也可能返回0
2. ResultSet executeQuery(sql):执行DQL语句返回值: ResultSet 结果集对象
3-4 ResultSet
封装了DQL查询语句的结果
相关方法有两个:
1.next()
2.getXXX()
具体实现步骤:
//执行语句
String sql="select * from student";
ResultSet resultSet = statement.executeQuery(sql);
//处理结果
while (resultSet.next())
int id = resultSet.getInt(1);//对应一行中的第1列。
String name =resultSet.getString(2);//对应一行中的第2列。
String number =resultSet.getString(3);//对应一行中的第3列。
System.out.println(id);
System.out.println(name);
System.out.println(number);
System.out.println("--------------");
}
System.out.println(resultSet);
3-5 PreparedStatement
1.SQL注入问题
- PreparedStatement用于预编译SQL语句并执行:预防SQL注入问题
- SQL注入
SQL注入是通过操作输入来修改事先定义好的SQL语句,用以达到执行代码对服务器进行攻击的方法。
简单点说就是会有些特别的代码的侵入
SQL注入举例
如下图代码所示,当PSW输入如下值时, 与正常的语句拼接出 or ‘1’=‘1’ 的恒成立语句, Select执行的语句条件恒成立。
String sql="select * from student where name='"+name+"' and no='"+psw+"' ";
ResultSet resultSet = statement.executeQuery(sql);
System.out.println(sql);
- 解决办法
//.执行语句
String sql="select * from student where name=? and no=? ";
//获取PreparedStatement对象
PreparedStatement pstat = connection.prepareStatement(sql);
//设置?的值
pstat.setString(1,name);
pstat.setString(2,psw);
ResultSet resultSet = pstat.executeQuery();
System.out.println(sql);
2.PreparedStatement预编译SQL
开启方式:useServerPrepStmts=true
String url="jdbc:mysql://localhost:3306/users?useSSL=false &useServerPrepStmts=true";
在获取PreparedStatement对象时,将sql语句提前发送给mysql服务器进行检查,编译(这些步骤很耗时)
执行时就不用再进行这些步骤了,速度更快
如果sql模板一样,则只需要进行一次检查、编译
4.数据库连接池
1.数据库连接池简介
-
数据库连接池是个容器,负责分配、管理数据库连接(Connection)
它允许应用程序重复使用一个现有的数据库连接,而不是再重新建立一个;
释放空闲时间超过最大空闲时间的数据库连接来避免因为没有释放数据库连接而引起的数据库连接遗漏 -
好处:
资源重用
提升系统响应速度
避免数据库连接遗漏
-
数据库连接池实现
标准接口:DataSource
官方(SUN) 提供的数据库连接池标准接口,由第三方组织实现此接口。
功能:获取连接 -
常见的数据库连接池:
DBCP
C3P0
Druid
2.Druid 数据库连接池
-
简介:
Druid连接池是阿里巴巴开源的数据库连接池项目功能强大,性能优秀,是Java语言最好的数据库连接池之一 -
Driud使用步骤
1.导入jar包 druid-1.1.12.jar
2.定义配置文件 —.properties文件
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///users?useSSL=false&useServerPrepStmts=true
username=root
password=685470
# 初始化连按数量
initialSize=5
# 最大连接数
maxActive=10
#最大等待时间
maxWait=3000
3.加载配置文件
prop.load(new FileInputStream("jdbc_demo/src/druid.properties"));
4.获取数据库连接池对象
DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
5.获取连接
Connection connection = dataSource.getConnection();
+大致演示
//1.导入jar包。
// ......
//2.定义配置文件。
// 。。。。。。
//3.加载配置文件。
Properties prop=new Properties();
prop.load(new FileInputStream("jdbc_demo/src/druid.properties"));
//4.获取连接池对象。
DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
//5.获取数据库连接Connection对象。
Connection connection = dataSource.getConnection();
System.out.println(connection);
- 获取当前项目的绝对路径
System.out.println(System.getProperty("user.dir"));//---获取当前项目的绝对路径。
5.JDBC练习
5-1 数据库准备
create table tb_brand(
-- id 主键
id int primary key auto_increment,
-- 品牌名称
brand_name varchar(20),
-- 企业名称
company_name varchar(20),
-- 排序字段
ordered int,
-- 描述信息
description varchar(100),
-- 状态:0:禁用 1:启用
status int);
insert into tb_brand (brand_name,company_name, ordered,description,status)
values ('三只松鼠','三只松鼠股份有限公司',5,'好吃不上火',0),
('华为','华为技术有限公司',108,'华为致力于把数字世界带入每个人、每个家庭、每个组织,构建万物互联的智能世界',1),
('小米','小米科技有限公司',50,'are you·ok',1);
5-2 Java相关类的操作
- 封装品牌
public class Brand
{
//id 主键
private Integer id ;
// 品牌名称
private String brandName;
// 企业名称;
private String companyName;
// 排序f字段;
private int ordered;
// 描述信息;
private String description;
// 状态:0:禁用 1:启用;
private Integer status;
//集合
static ArrayList<Brand> brands=new ArrayList<>();
public Integer getId()
{
return id;
}
public void setId(Integer id)
{
this.id = id;
}
public String getBrandName()
{
return brandName;
}
public void setBrandName(String brandName)
{
this.brandName = brandName;
}
public String getCompanyName()
{
return companyName;
}
public void setCompanyName(String companyName)
{
this.companyName = companyName;
}
public int getOrdered()
{
return ordered;
}
public void setOrdered(int ordered)
{
this.ordered = ordered;
}
public String getDescription()
{
return description;
}
public void setDescription(String description)
{
this.description = description;
}
public Integer getStatus()
{
return status;
}
public void setStatus(Integer status)
{
this.status = status;
}
public Brand(Integer id, String brandName, String companyName, int ordered, String description, Integer status)
{
this.id = id;
this.brandName = brandName;
this.companyName = companyName;
this.ordered = ordered;
this.description = description;
this.status = status;
}
@Override
public String toString()
{
return "Brand{" + "id=" + id + ", brandName='" + brandName + '\'' + ", companyName='" + companyName + '\'' + ", ordered=" + ordered + ", description='" + description + '\'' + ", status=" + status + '}';
}
/*
编辑小技巧积累-------->Alt加鼠标左键,特定范围多行选择。
* */
}
- 测试数据
@SuppressWarnings({"all"})
/*
* 品牌数据的增删改查操作
* */
public class BrandTest
{
public static void main(String[] args) throws Exception
{
BrandTest brandTest = new BrandTest();
brandTest.testAll();
}
public void testAll() throws Exception
{
//1.获取连接池对象。
Properties prop=new Properties();
prop.load(new FileInputStream("./jdbc_demo/src/druid.properties"));
DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
Connection conn = dataSource.getConnection();
//2.定义执行sql语句的对象
PreparedStatement pstmt;
//3.选择增删改查。
Scanner scanner = new Scanner(System.in);
System.out.println("请选择你需要实现的功能:\n1.增加数据\n2.删除数据\n3.修改数据\n4.查找数据");
String choose=scanner.next();
System.out.println(choose);
switch (Integer.parseInt(choose))
{
case 1:
//3-1-1.定义sql
String sqlInsert="insert into tb_brand (brand_name,company_name, ordered,description,status)\n" +
"values (?,?,?,?,?)";
//3-1-2.获取执行sql语句的对象
pstmt = conn.prepareStatement(sqlInsert);
//3-1-3.设置?的值
pstmt.setString(1,"李宁");
pstmt.setString(2,"李宁有限公司");
pstmt.setString(3,"8");
pstmt.setString(4,"一切皆有可能");
pstmt.setString(5,"1");
//3-1-4.执行sql
int i1 = pstmt.executeUpdate();
System.out.println(i1);
if (i1>0)
{
System.out.println("创建成功" );
}
else
{
System.out.println("创建失败 ");
}
//3-1-5释放资源
pstmt.close();
break;
case 2:
//3-2-1.定义sql
String sqlDrop="delete from tb_brand where id=?";
//3-2-2.获取执行sql语句的对象
pstmt = conn.prepareStatement(sqlDrop);
//3-2-3.设置?的值
pstmt.setString(1,"4");
//3-2-4.执行sql
int i2 = pstmt.executeUpdate();
System.out.println(i2);
if (i2>0)
{
System.out.println("删除成功" );
}
else
{
System.out.println("删除失败 ");
}
//3-2-5释放资源
pstmt.close();
break;
case 3:
//3-3-1.定义sql
String sqlUpdate="update tb_brand set description=? where id=4";
//3-3-2.获取执行sql语句的对象
pstmt = conn.prepareStatement(sqlUpdate);
//3-3-3.设置?的值
pstmt.setString(1,"真的一切皆有可能吗? ");
//3-3-4.执行sql
int i3 = pstmt.executeUpdate();
System.out.println(i3);
if (i3>0)
{
System.out.println("修改成功" );
}
else
{
System.out.println("修改失败");
}
//3-3-5释放资源
pstmt.close();
break;
case 4:
//3-4-1.定义sql
String sqlSelect="select * from tb_brand";
//3-4-2.获取执行sql语句的对象
pstmt = conn.prepareStatement(sqlSelect);
//3-4-3.执行sql
ResultSet rs = pstmt.executeQuery();
//3-4-4.将封装的数据储存到Brand类集合中。
while (rs.next())
{
//获取数据
Integer id = rs.getInt("id");
String brandName = rs.getString("brand_name");
String companyName = rs.getString("company_name");
int ordered = rs.getInt("ordered");
String description = rs.getString("description");
Integer status = rs.getInt("status");
//封装数据
Brand brand = new Brand(id, brandName, companyName, ordered, description, status);
//集合收集数据
Brand.brands.add(brand);
}
//3-4-5.打印测试
System.out.println(Brand.brands);
//3-4-6.资源释放
rs.close();
pstmt.close();
}
//4.资源释放
conn.close();
}
}
二 Maven
1. 概述
1-1 Maven介绍
Apache Maven 是一个项目管理和构建工具,它基于项目对象模型M(POM)的概念,通过一小段描述信息来管理项目的构建、报告和文档
- Maven模型
- Maven仓库
Maven中央仓库Link
当项目中使用坐标引入对应依赖jar包后,首先会查找本地仓库中是否有对应的jar包:
如果有,则在项目直接引用;
如果没有,则去中央仓库中下载对应的jar包到本地仓库。
1-2 Maven的作用
-
Maven是专门用于管理和构建Java项目的工具,它的主要功能有:
提供了一套标准化的项目结构
提供了一套标准化的构建流程(编译,测试,打包,发布.
提供了一套依赖管理机制 -
Maven提供了一套标准化的项目结构,所有IDE使用Maven构建的项目结构完全一样,所有IDE创建的Maven项目可以通用
-
标准化的构建流程
-
依赖管理
依赖管理其实就是管理你项目所依赖的第三方资源 (jar包、插件…)
2. Maven 安装配置
-
2.配置环境变量 MAVEN_HOME为安装路径的bin目录
-
3.配置本地仓库:修改 conf/settings.xml中的< localRepository >为一个指定目录
-
4.配置阿里云私服:修改 conf/settings.xml中的 < mirrors> 标签,为其添加如下子标签:
<mirror>
<id>aliyunmaven</id>
<mirrorOf>*</mirrorOf>
<name>阿里云公共仓库</name>
<url>https://maven.aliyun.com/repository/public</url>
</mirror>
3. Maven 基本使用(mvn)
3-1 Maven 常用命令
- compile :编译
- clean:清理
- test:测试
- package:打包
- install:安装
3-2 Maven 生命周期
- Maven 构建项目生命周期描述的是一次构建过程经历经历了多少个事件
- Maven 对项目构建的生命周期划分为3套:
clean:清理工作
default:核心工作,例如编译,测试,打包,安装等
site:产生报告,发布站点等
4. IDEA 配置 Maven
-
IDEA 配置 Maven 环境
选择 IDEA中 File -->Settings
搜索 maven
设置 IDEA 使用本地安装的 Maven,并修改配置文件路径
-
Maven 坐标详解
- 什么是坐标?
Maven 中的坐标是资源的唯一标识
使用坐标来定义项目或引入项目中需要的依赖 - Maven 坐标主要组成
groupld:定义当前Maven项目隶属组织名称(通常是域名反写,例如:com.test)
artifactld:定义当前Maven项目名称(通常是模块名称,例如 order-service、goods-service)
version:定义当前项目版本号
- 什么是坐标?
-
IDEA 创建 Maven 项目
-
IDEA 导入 Maven 项目
1.选择右侧Maven面板,点击+号
2.选中对应项目的pom.xml文件,双击即可
3.如果没有Maven面板,选择
View →>Appearance > Tool Window Bars
maven helper插件
5. 依赖管理、范围
- 管理
在Maven pox.xml文件中进行依赖管理
1.在 pom.xml 中编写标签
2.在标签中 使用引入坐标
3.定义坐标的 groupld,artifactld,version
4.点击刷新按钮,使坐标生效
<!--导入mysql 驱动jar包-->
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
</dependencies>
- 范围
通过设置坐标的依赖范围(scope),可以设置 对应jar包的作用范围:编译环境、测试环境、运行环境
三、MyBatis
3-1 概念
-
什么是MyBatis?
MyBatis是一款优秀的持久层框架,用于简化JDBC开发
MyBatis本是 Apache 的一个开源项目iBatis,2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis。2013年11月迁移到Github官网:https://mybatis.org/mybatis-3/zh/index.html -
持久层
负责将数据到保存至利数据库的那一层代码
JavaEE三层架构:表现层、业务层、持久层 -
框架
框架就是一个半成品软件,是一套可重用的、通用的、软件基础代码模型
在框架的基础之上构建软件编写更加高效、规范、通用、可扩展
MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作
3-2 MyBatis 快速入门
- 创建user表,添加数据
- 创建模块,导入坐标
- 编写 MyBatis 核心配置文件 -->替换连接信息 解决硬编码问题
<?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.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///users?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="685470"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 加载sql映射文件 -->
<mapper resource="UserMapper.xml"/>
</mappers>
</configuration>
- 编写 SQL 映射文件 -->统一管理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">
<!--
namespace:名称空间
-->
<mapper namespace="test">
<select id="selectAll" resultType="com.pojo.User">
select * from tb_user;--
</select>
</mapper>
解决SQL映射文件的警告提示
产生原因:ldea和数据库没有建立连接,不识别表信息
解决方式:在ldea中配置MySQL数据库连接
- 编码
public static void main(String[] args) throws IOException
{
//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();
//3.执行sql语句
List<User> Users = sqlSession.selectList("test.selectAll");
System.out.println(Users);
//4.
sqlSession.close();
}
3-3 Mapper 代理开发
-
目的
解决原生方式中的硬编码
简化后期执行SQL -
步骤
- 定义与SQL映射文件同名的Mapper接口,并且将Mapper接口和SQL映射文件放置在同一目录下
在源文件中不需要把两个文件放在同一个目录下,而是在resource文件夹中创建一个与map接口所在目录相同结构的目录,编译之后,他们就会自动在一起。
2.设置SQL映射文件的namespace属性为Mapper接口全限定名
3.在 Mapper 接口中定义方法,方法名就是SQL映射文件中sql语句的id,并保持参数类型和返回值类型一致
4.编码
4-1 通过 SqlSession 的 getMapper方法获取 Mapper接口的代理对象
4-2 调用对应方法完成sql的执行
- 细节:
细节:以后需要用到的配置文件会很多很多,需要在mybatis核心配置文件中一条条配置sql语句映射路径就很麻烦,这时我们可以通过标签
<package name=" " />
来打包所有的sql语句映射路径。
3-4 MyBatis 核心配置文件
environments
:配置数据库连按环境信息。可以配置多个environment,通过default板性切换不同的environmentmappers
: sql语句的映射路径typeAliases
:用于简便指定执行sql语句后返回的结果类型resultType
。(首先你得知道resultType是干什么的)
<typeAliases>
<package name="com.pojo"/>-- 基于com.pojo包下的所有实体类,之后resultType写对应的类名即可。
</typeAliases>
- 需要注意的一点是:在MyBatis核心配置文件中,以上配置标签的编写,是按照官方设定的文档结构顺序进行编写:
否则代码会报错
3-5 Java层、数据库层 连接时的相关问题。
- 两种方式来应对Java类中的属性名与数据库中的字段名写法不一样的问题
// 1.使用<sql>标签,使用<include>标签引用
<sql id="brandSql">
id, brand_name as brandName, company_name as companyName, ordered, description, status
</sql>
<select id="selectAll" resultType="brand">
select <include refid="brandSql"/> from tb_brand;
</select>
//2.使用<resultMap>标签对单个字段进行修改,再使用<resultMap>标签引用
<resultMap id="brandResultMap" type="brand">
<result column="brand_name" property="brandName"/>
<result column="company_name" property="companyName"/>
</resultMap>
<select id="selectAll" resultMap="brandResultMap">
select * from tb_brand;
</select>
MybatisX插件 是一款基于 IDEA的快速开发插件,为效率而生。
主要功能:
XML 和 接口方法 相互跳转
根据接口方法生成 statement
-
参数占位符:
1.#{ }:会将其替换为?,为了防止SQL注入
2.${ }:拼sqL,会存在SQL注入问题使用时机:
参数传递的时候:#{}
表名或者列名不固定的情况下:${}会存在SQL注入问题
<select id="selectById" resultMap="brandResultMap">
select * from tb_brand where id=#{id};
</select>
- 特殊字符处理:(在配置文件XML中,有些符号是不能够出现的比如说
<
,这个时候就需要进行特色符号处理)
1.转义字符:<
—》<
2.CDATAIX:<![CDATA[ ] ]>
在[ ]
中填写对应的特色符号。
<select id="selectById" resultMap="brandResultMap">
select * from tb_brand where id
<![CDATA[
<
]]>
#{id};
- SQL语句设置多个参数的2种方式
- 散装参数:需要使用@Param(“saL中的参数占位符名称")
List<Brand> selectByCondition(@Param("status")int status,@Param("companyName")String companyName,@Param("brandName")String brandName);
- 实体类封装参数
只需要保证SQL中的参数名 和 实体类属性名对应上,即可设置成功
List<Brand> selectByCondition(Brand brand);
sql映射文件:(各种方式都用此映射文件)
<select id="selectByCondition" resultMap="brandResultMap">
select * from tb_brand
where status = #{status}
and company_name like #{companyName}
and brand_name like #{brandName}
</select>
- 动态SQL多查询 (属性存在、不存在都会进行查询))
<if>
<select id="selectByCondition" resultMap="brandResultMap">
select * from tb_brand
<where>
<if test="status!=null">
and status = #{status}
</if>
<if test="companyName !=null and companyName !='' ">
and company_name like #{companyName}
</if>
<if test="brandName !=null and brandName !='' ">
and brand_name like #{brandName}
</if>
</where>
</select>
- 动态SQL单查询
choose (when, otherwise)
<!--单条件动态查询-->
<select id="selectByConditionSingle" resultMap="brandResultMap">
select * from tb_brand
where
<choose><!--类似于switch-->
<when test="status!=null">status = #{status}</when>
<when test="companyName !=null and companyName !=''">company_name like #{companyName}</when>
<when test="brandName !=null and brandName !=''">brand_name like #{brandName}</when>
<otherwise>1=1</otherwise><!--类似于default-->
</choose>
</select>
- MyBatis事务:
openSession():默认开启事务,进行增删改操作后需要使用sqlSession.commit;
sqlSession.commit();
手动提交事务openSession(true):可以设置为自动提交事务(关闭事务)
SqlSession sqlSession = sqlSessionFactory.openSession(true);
useGeneratedKeys="true" keyProperty="id"
主键返回
Mybatis 配置文件 useGeneratedKeys 参数只针对 insert 语句生效,默认为 false。当设置为 true 时,表示如果插入的表以自增列为主键,则允许 JDBC 支持自动生成主键,并可将自动生成的主键返回, 插入返回的主键id是映射回原实体类中的
<insert id="addBrand" useGeneratedKeys="true" keyProperty="id">
insert into tb_brand (brand_name, company_name, ordered, description, status)
value
(#{brandName},#{companyName},#{ordered},#{description},#{status});
</insert>
- update动态语句
<if>
<update id="updateBrandNameByIdAfter">
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>
- sql批量删除语句
<foreach>
标签数组遍历
void deleteByIds(@Param("ids") int[] ids);
<delete id="deleteByIds">
delete from tb_brand where id in (<foreach collection="ids" item="id" separator=","> #{id}</foreach>);
</delete>
- 我一直很好奇SQL映射文件中的参数是如何与对应接口方法参数对应的————Mybatis的
ParamNameResolver
类底层代码解读中。。。
MyBatis 接口方法中可以接收各种各样的参数,MyBatis底层对于这些参数进行不同的封装处理方式
- 注解完成增删改查
@Select("select * from tb_brand where id = #{id};")
Brand selectById(int id);