目录
MyBatis(优秀的持久层框架,用于简化JDBC开发)
表现层:页面展示
业务层:逻辑处理
持久层:数据持久化
MyBatis快速入门
创建User表
create database mybatis;
use mybatis;
drop table if exists tb_user;
create table tb_user(
id int primary key auto_increment,
username varchar(20),
password varchar(20),
gender char(1),
addr varchar(30)
);
创建模块 导入坐标
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>mybatis-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!--mybatis的 依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<!--mysql的 依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<!--junit 单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<!-- 添加slf4j日志api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.20</version>
</dependency>
<!-- 添加logback-classic依赖 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<!-- 添加logback-core依赖 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.2.3</version>
</dependency>
</dependencies>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!--
CONSOLE :表示当前的日志信息是可以输出到控制台的。
-->
<appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%level] %blue(%d{HH:mm:ss.SSS}) %cyan([%thread]) %boldGreen(%logger{15}) - %msg %n</pattern>
</encoder>
</appender>
<logger name="com.itheima" level="DEBUG" additivity="false">
<appender-ref ref="Console"/>
</logger>
<!--
level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF
, 默认debug
<root>可以包含零个或多个<appender-ref>元素,标识这个输出位置将会被本日志级别控制。
-->
<root level="DEBUG">
<appender-ref ref="Console"/>
</root>
</configuration>
编写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>
<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:///mybatis?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="1234"/>
</dataSource>
</environment>
<!-- <environment id="test">-->
<!-- <transactionManager type="JDBC"/>-->
<!-- <dataSource type="POOLED">-->
<!-- <!–数据库连接信息–>-->
<!-- <property name="driver" value="com.mysql.jdbc.Driver"/>-->
<!-- <property name="url" value="jdbc:mysql:///mybatis?useSSL=false"/>-->
<!-- <property name="username" value="root"/>-->
<!-- <property name="password" value="1234"/>-->
<!-- </dataSource>-->
<!-- </environment>-->
</environments>
<mappers>
<!--加载sql映射文件-->
<mapper resource="UserMapper.xml"/>
<!--Mapper代理方式-->
<!-- <package name="com.itheima.mapper"/>-->
</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.itheima.pojo.User">
select * from tb_User;
</select>
<!-- <select id="selectById" resultType="user">-->
<!-- select *-->
<!-- from tb_user where id = #{id};-->
<!-- </select>-->
</mapper>
定义POJO类
加载核心配置文件,获取sqlsessionfactory对象
获取sqlsession对象,执行SQL语句
释放资源
public static void main(String[] args) throws Exception {
//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();
}
IDEA中也可以写mysql语句且功能也很强大
Mapper代理开发
定义与sql映射文件同名的Mapper接口,并将Mapper接口与SQL映射文件放置在同一目录下
在resource中创建文件夹要用 / eg:com/itheima/mapper
设置SQL映射文件的namespace属性为Mapper接口全限定名
<mapper namespace="com.itheima.mapper.UserMapper">
<select id="selectAll" resultType="com.itheima.pojo.User">
select * from tb_User;
</select>
</mapper>
在Mapper接口中定义方法,方法名就是SQL映射文件中sql语句的id,并保持参数类型和返回类型一致
package com.itheima.mapper;
import com.itheima.pojo.User;
import java.util.List;
public interface UserMapper {
List<User> selectAll();
User selectById(int id);
}
编码
package com.itheima;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
//Mybatis 代理开发
public class MybatisDemo2 {
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");
//3.1 获取UserMapper接口的代理对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> users = userMapper.selectAll();
System.out.println(users);
//4. 释放资源
sqlSession.close();
}
}
细节:如果Mapper接口名称和SQL映射文件名称相同,并在同一目录下,则可以使用包扫描的方式简化SQL映射文件的加载
<!--Mapper代理方式-->
<package name="com.itheima.mapper"/>
MyBatis核心配置文件
environments:配置数据库连接环境信息。可以配置多个environment,通过default属性切换不同的environment
<!--
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:///mybatis?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="1234"/>
</dataSource>
</environment>
<!--MyBatis 可以配置多种环境,这种机制有助于将 SQL 映射应用于多种数据库之中,-->
<environment id="test">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!--数据库连接信息-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///mybatis?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="1234"/>
</dataSource>
</environment>
</environments>
起别名,扫描指定路径的包
# 起别名
<typeAliases>
<package name="com.itheima.pojo"/>
</typeAliases>
# 这里就可以写user了 因为定义了user类 又起了别名
<select id="selectAll" resultType="user">
select *
from tb_user;
</select>
配置文件完成增删改查(方式一)
-- 删除tb_brand表
drop table if exists tb_brand;
-- 创建tb_brand表
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),
('华为', '华为技术有限公司', 100, '华为致力于把数字世界带入每个人、每个家庭、每个组织,构建万物互联的智能世界', 1),
('小米', '小米科技有限公司', 50, 'are you ok', 1);
SELECT * FROM tb_brand;
<!-- 数据库表的字段名称 和 实体类的属性名称 不一样,则不能自动封装数据
法一:起别名 对不一样的列名起别名,让别名和实体类的属性名一样
缺点:每次查询都要定义一次别名
使用sql片段
法二:resultMap id: 唯一标识 type: 映射的类型 支持别名
<resultMap id="brandResultMap" type="brand">
<result column="brand_name" property="brandName"/>
<result column="company_name" property="companyName"/>
</resultMap>
-->
<!-- <select id="selectAll" resultType="com.itheima.pojo.Brand">-->
<!-- select id,brand_name as brandName,company_name as companyName,ordered,description,status from tb_brand;-->
<!-- </select>-->
<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>
三个点:语句怎么写,要不要参数,要不要返回参数
<!-- 参数占位符
1 #{}:会将其替换为 ? 为了防止SQL注入
2 ${}:拼sql 会存在SQL注入问题
3 使用时机
参数传递的时候:#{}
表名或者列名不固定的情况下: ${} 会存在SQL注入问题
参数类型:parameterType:可以省略
特殊字符处理:
1 转义字符:小于号 <
2 CDATA区:<![CDATA[
<
]]>
-->
<select id="selectById" resultMap="brandResultMap">
select * from tb_brand where id = #{id};
</select>
条件查询(重中之重)![](https://img-blog.csdnimg.cn/31231901b4e444eca13e205f613298ca.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAaW50ZXJuZXR2,size_20,color_FFFFFF,t_70,g_se,x_16)
/**
* 条件查询
* 参数接收
* 散装参数:如果方法中有多个参数,需要使用@Param("SQL参数占位符名称")
* 对象参数:对象的属性名称要和参数占位符名称一致
* map集合参数
*/
//散装参数
// List<Brand>selectByCondition(@Param("status")int status,@Param("companyName")
// String companyName,@Param("brandName")String brandName);
// 对象参数(在准备参数时,将数据封装成对象)
// List<Brand> selectByCondition(Brand brand);
// map集合参数
List<Brand> selectByCondition(Map map);
<!-- 条件查询 -->
<select id="selectByCondition" resultMap="brandResultMap">
select *
from tb_brand
where status = #{status}
and company_name like #{companyName}
and brand_name like #{brandName}
</select>
@Test
public void testSekectByCondition() throws Exception {
//接收参数
int status = 1;
String companyName = "华为";
String brandName = "华为";
//处理参数
companyName = "%" + companyName + "%";
brandName = "%" + brandName + "%";
// //封装对象
// Brand brand = new Brand();
// brand.setStatus(status);
// brand.setCompanyName(companyName);
// brand.setBrandName(brandName);
Map map = new HashMap();
map.put("status",status);
map.put("companyName",companyName);
map.put("brandName",brandName);
//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.1 获取UserMapper接口的代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
// 执行方法
// List<Brand> brands = brandMapper.selectByCondition(status, companyName, brandName);
// List<Brand> brands = brandMapper.selectByCondition(brand);
List<Brand> brands = brandMapper.selectByCondition(map);
System.out.println(brands);
//4. 释放资源
sqlSession.close();
}
动态条件查询即可能输入的限定条件个数不确定·
<!-- 动态条件查询 输入参数的个数不确定
if:条件判断
test:逻辑表达式
问题: and 的存在可能会出现问题
解决:1 恒等式 where 1=1
2 用<where> 代替 where
-->
<select id="selectByCondition" resultMap="brandResultMap">
select *
from tb_brand
where
<if test="status != null">
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>
</select>
<select id="selectByConditionSingle" resultMap="brandResultMap">
select *
from tb_brand
where
<choose><!--相当于Switch -->
<when test="status != null"><!--相当于case-->
status = #{status}
</when>
<when test="companyName != null and companyName != '' "><!--相当于case-->
company_name like #{companyName}
</when>
<when test="brandName != null and brandName != '' "><!--相当于case-->
brand_name like #{brandName}
</when>
<!--此处避免用户一个都不选 / 或者用<where><where>-->
<otherwise>
1=1
</otherwise>
</choose>
</select>
添加 添加-主键返回
<insert id="add">
insert into tb_brand(brand_name, company_name, ordered, description, status)
value (#{brandName},#{companyName},#{ordered},#{description},#{status})
</insert>
@Test
public void testAdd() throws Exception {
//接收参数
int status = 1;
String companyName = "中国手机";
String brandName = "波导";
String description = "手机中的战斗机";
int ordered = 100;
//封装对象
Brand brand = new Brand();
brand.setStatus(status);
brand.setCompanyName(companyName);
brand.setBrandName(brandName);
brand.setDescription(description);
brand.setOrdered(ordered);
//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();
//2. 获取SqlSession对象,用它来执行sql 此时可以自动提交事务
SqlSession sqlSession = sqlSessionFactory.openSession(true);
//3.1 获取UserMapper接口的代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
// 执行方法
brandMapper.add(brand);
//提交事务
// sqlSession.commit();
//4. 释放资源
sqlSession.close();
}
能够获取插入数据库数据的主键ID值
<insert id="add" useGeneratedKeys="true" keyProperty="id">
insert into tb_brand(brand_name, company_name, ordered, description, status)
value (#{brandName},#{companyName},#{ordered},#{description},#{status})
</insert>
@Test
public void testAdd2() throws Exception {
//接收参数
int status = 1;
String companyName = "中国手机";
String brandName = "波导";
String description = "手机中的战斗机";
int ordered = 100;
//封装对象
Brand brand = new Brand();
brand.setStatus(status);
brand.setCompanyName(companyName);
brand.setBrandName(brandName);
brand.setDescription(description);
brand.setOrdered(ordered);
//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();
//2. 获取SqlSession对象,用它来执行sql 此时可以自动提交事务
SqlSession sqlSession = sqlSessionFactory.openSession(true);
//3.1 获取UserMapper接口的代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
// 执行方法
brandMapper.add(brand);
Integer id = brand.getId();
System.out.println(id);
//提交事务
// sqlSession.commit();
//4. 释放资源
sqlSession.close();
}
<update id="update">
update tb_brand
set
brand_name = #{brandName},
company_name = #{companyName},
ordered = #{ordered},
description = #{description},
status = #{status}
where id = #{id};
</update>
@Test
public void testUpdate() throws Exception {
//接收参数
int status = 1;
String companyName = "中国手机";
String brandName = "波导";
String description = "波导手机,手机中的战斗机";
int ordered = 200;
int id = 5;
//封装对象
Brand brand = new Brand();
brand.setStatus(status);
brand.setCompanyName(companyName);
brand.setBrandName(brandName);
brand.setDescription(description);
brand.setOrdered(ordered);
brand.setId(id);
//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();
//2. 获取SqlSession对象,用它来执行sql 此时可以自动提交事务
SqlSession sqlSession = sqlSessionFactory.openSession(true);
//3.1 获取UserMapper接口的代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
// 执行方法
int count = brandMapper.update(brand);
System.out.println(count);
//提交事务
// sqlSession.commit();
//4. 释放资源
sqlSession.close();
}
<!-- update 的 动态语句 -->
<update id="update">
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 and status != '' ">
status = #{status}
</if>
</set>
where id = #{id};
</update>
@Test
public void testUpdate() throws Exception {
//接收参数
int status = 1;
String companyName = "中国手机";
String brandName = "波导";
String description = "波导手机,手机中的战斗机";
int ordered = 200;
int id = 5;
//封装对象
Brand brand = new Brand();
brand.setStatus(status);
brand.setCompanyName(companyName);
brand.setBrandName(brandName);
brand.setDescription(description);
brand.setOrdered(ordered);
brand.setId(id);
//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();
//2. 获取SqlSession对象,用它来执行sql 此时可以自动提交事务
SqlSession sqlSession = sqlSessionFactory.openSession(true);
//3.1 获取UserMapper接口的代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
// 执行方法
int count = brandMapper.update(brand);
System.out.println(count);
//提交事务
// sqlSession.commit();
//4. 释放资源
sqlSession.close();
}
<delete id="deleteByID">
delete from tb_brand where id = #{id};
</delete>
@Test
public void testDeleteByID() throws Exception {
//接收参数
int id = 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();
//2. 获取SqlSession对象,用它来执行sql 此时可以自动提交事务
SqlSession sqlSession = sqlSessionFactory.openSession();
//3.1 获取UserMapper接口的代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
// 执行方法
brandMapper.deleteByID(id);
//提交事务
sqlSession.commit();
//4. 释放资源
sqlSession.close();
}
<!-- mybatis会将数组参数,封装为一个Map集合
1 默认:array = 数组
2 使用@Param注解改变map集合的默认key的名称
-->
<delete id="deleteByIDs">
delete from tb_brand where id
in
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
;
</delete>
@Test
public void testDeleteByIDs() throws Exception {
//接收参数
int[] ids = {2,3,7};
//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();
//2. 获取SqlSession对象,用它来执行sql 此时可以自动提交事务
SqlSession sqlSession = sqlSessionFactory.openSession();
//3.1 获取UserMapper接口的代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
// 执行方法
brandMapper.deleteByIDs(ids);
//提交事务
sqlSession.commit();
//4. 释放资源
sqlSession.close();
}
注解完成增删改查(方式二)(完成简单功能)
MyBatis参数传递
多个参数 一定要使用@Param注解,替换Map集合中默认的arg键名
User select(@Param("username") String username,String password);
_______________________________________________________________
map.put("username",参数值1)
map.put("param1",参数值2)
map.put("param2",参数值3)
map.put("agr1",参数值4)
1 POJO类型:直接使用,属性名 和 参数占位符名称一致
2 Map集合 :直接使用,键名 和 参数占位符名称一致
3 Collection:封装为Map集合 一定要使用@Param注解,替换Map集合中默认的arg键名
map.put("arg0", collection集合);
map.put("collection",collection集合);
4 List:封装成Map集合 一定要使用@Param注解,替换Map集合中默认的arg键名
map.put("arg0",list集合);
map.put("collection",list集合);
map.put("list",list集合);
5 Array:封装成Map集合 一定要使用@Param注解,替换Map集合中默认的arg键名
map.put("arg0",数组);
map.put("array",数组);
6 其他类型:直接使用