网站在线建设方案,闵行网站推广,上海网站建设营销,品牌网站模板Javaweb学习 一、Maven1.1 Maven概述1.2 Maven简介1.3、Maven基本使用1.4、IDEA配置Maven1.6、依赖管理依赖范围 二、MyBatis2.1 MyBatis简介2.2 Mybatis快速入门2.3、解决SQL映射文件的警告提示2.4、Mapper代理开发 三、MyBaits核心配置文件四、 配置文件的增删改查4.1 M… Javaweb学习 一、Maven1.1 Maven概述1.2 Maven简介1.3、Maven基本使用1.4、IDEA配置Maven1.6、依赖管理依赖范围 二、MyBatis2.1 MyBatis简介2.2 Mybatis快速入门2.3、解决SQL映射文件的警告提示2.4、Mapper代理开发 三、MyBaits核心配置文件四、 配置文件的增删改查4.1 Mybatis案列4.1.1 环境的准备4.2 查询所有数据和结果映射 4.3、查看详情单个查询4.4、条件查询4.4.1、多条件查询4.4.2、动态条件查询4.4.3、单条件动态条件查询 4.5、添加4.6、修改功能4.6.1、修改全部字段4.6.2、修改动态字段 4.7、删除功能4.7.1、删除单个字段4.7.2、批量删除 4.8、参数传递4.9、注解开发 一、Maven
1.1 Maven概述
Maven是专门用于管理和构建Java项目的工具它的主要功能有
提供了一套标准化的项目结构 Maven提供了一套标准化的项目结构所有IDE使用Maven构建的项目结构完全一样所有IDE创建的Maven项目可以通用 提供了一套标准化的构建流程(编译测试打包发布.....) 提供了一套依赖管理机制
1.2 Maven简介
Apache Maven是一个项目管理和构建工具它基于项目对象模型(POM)的概念通过一小段描述信息来管理项目的构建、报告和文档 项目对象模型Project Object Model依赖管理模型Dependency插件Plugin 仓库分类: 本地仓库:自己计算机上的一个目录 中央仓库:由Maven团队维护的全球唯一的仓库 地址: 中央仓库地址 远程仓库(私服):一般由公司团队搭建的私有仓库当项目中使用坐标引入对应依赖jar包后首先会查找本地仓库中是否有对应的jar包: 如果有则在项目直接引用; 如果没有则去中央仓库中下载对应的jar包到本地仓库。 还可以搭建远程仓库将来jar包的查找顺序则变为:本地仓库→远程仓库→中央仓库
1.3、Maven基本使用
常用命令
compile :编译 clean:清理 test:测试 package:打包 install:安装
生命周期 Maven构建项目生命周期描述的是一次构建过程经历经历了多少个事件Maven对项目构建的生命周期划分为3套 clean:清理工作 default:核心工作例如编译测试打包安装等 site:产生报告发布站点等 同一生命周期内执行后边的命令前边的所有命令会自动执
1.4、IDEA配置Maven
步骤 选择IDEA中 设置搜索maven设置IDEA使用本地安装的Maven并修改配置文件路径 Maven坐标详解
什么是坐标? Maven 中的坐标是资源的唯一标识 使用坐标来定义项目或引入项目中需要的依赖Maven 坐标主要组成 groupld:定义当前Maven项目隶属组织名称(通常是域名反写例如: com.itheima) artifactld:定义当前Maven项目名称通常是模块名称例如order-service、goods-service) version:定义当前项目版本号
IDEA创建Maven项目 创建模块选择Maven点击Next填写模块名称坐标信息点击finish创建完成编写HelloWorld并运行 IDEA导入Maven项目 选择右侧Maven面板点击号选中对应项目的pom.xml文件双击即可如果没有Maven面板选择 View → Appearance → Tool Window Bars 配置Maven-Hepler插件 选择IDEA中 File -- Settings选择Plugins搜索Maven选择第一个Maven Helper点击Install安装弹出面板中点击Accept重启IDEA 1.6、依赖管理依赖范围
依赖管理
在pom.xml中编写dependencies标签在dependencies标签中使用dependency引入坐标定义坐标的 groupld,artifactldversion点击刷新按钮使坐标生效
依赖范围 通过设置坐标的依赖范围(scope)可以设置对应jar包的作用范围:编译环境、测试环境、运行环境 scope 默认值compile
二、MyBatis
2.1 MyBatis简介
什么是MyBatis MyBatis是一款优秀的持久层 ,框架用于简化JDBC开发MyBatis本是 Apache的一个开源项目iBatis, 2010年这个项目由apache softwarefoundation迁移到了google code并且改名为MyBatis 。2013年11月迁移到Github官网: MyBatis官网 持久层
负责将数据到保存到数据库的那一层代码JavaEE三层架构: 表现层、业务层、持久层
框架
框架就是一个半成品软件是一套可重用的、通用的、软件基础代码模型在框架的基础之上构建软件编写更加高效、规范、通用、可扩展
JDBC缺点 由于JDBC的缺点所以出现了MyBatis
2.2 Mybatis快速入门 2.3、解决SQL映射文件的警告提示
产生原因Idea和数据库没有建立连接不识别表信息 解决方式在Idea中配置MySQL数据库连接
第一步 首先在设置当中去下载Database Navigator 第二步
第三步
第四步
2.4、Mapper代理开发
目的 解决原生方式中的硬编码简化后期执行SQL 使用Mapper代理方式要求 定义与SQL映射文件同名的Mapper接口并且将Mapper接口和SQL映射文件放置在同一目录下 设置SQL映射文件的namespace属性为Mapper接口全限定名 在Mapper接口中定义方法方法名就是SQL映射文件中sql语句的id并保持参数类型和返回值类型一致 编码 通过SqlSession 的getMapper方法获取Mapper接口的代理对象调用对应方法完成sql的执行 细节如果Mapper接口名称和SQL映射文件名称相同并在同一目录下则可以使用包扫描的方式简化SQL映射文件的加载
package com.Smulll;import com.Smulll.mapper.UserMapper;
import com.Smulll.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.InputStream;
import java.util.List;/*
* 代理开发
* */
public class MybatisDemo2 {public static void main(String[] args) throws Exception {//1加载mybatis的核心配置文件获取sqlSessFactoryString resource mybatis-config.xml;InputStream inputStream Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory new SqlSessionFactoryBuilder().build(inputStream);//2.获取SqlSession对象用它来执行SQLSqlSession sqlSession sqlSessionFactory.openSession();//3.执行sql语句//ListObject Users sqlSession.selectList(test.selectAll);//获取UserMapper接口的代理对象UserMapper usermapper sqlSession.getMapper(UserMapper.class);ListUser users usermapper.selectAll();//打印System.out.println(users);//关流sqlSession.close();}
}
核心配置文件
?xml version1.0 encodingUTF-8 ?
!DOCTYPE configurationPUBLIC -//mybatis.org//DTD Config 3.0//ENhttps://mybatis.org/dtd/mybatis-3-config.dtd
configuration!--environments:配置数据库连接环境信息可以配置多个environment,通过default属性切换不同的environment即通过这个改变其数据库的不同--environments defaultdevelopmentenvironment iddevelopmenttransactionManager typeJDBC/dataSource typePOOLED!--数据库连接信息--property namedriver valuecom.mysql.jdbc.Driver/property nameurl valuejdbc:mysql://localhost:3306/mybatis?useSSLfalseamp;serverTimezoneUTC/property nameusername valueroot/property namepassword value123456//dataSource/environment/environmentsmappers!--加载SQL的映射文件--mapper resourcecom/mybatisDom/mapper/UserMapper.xml//mappers
/configuration
mapper代理
?xml version1.0 encodingUTF-8 ?
!DOCTYPE mapperPUBLIC -//mybatis.org//DTD Mapper 3.0//ENhttps://mybatis.org/dtd/mybatis-3-mapper.dtd
!--namespace: 名称空间
--
mapper namespacecom.itheima.mapper.UserMapper!--statement--select idselectAll resultTypecom.itheima.pojo.Userselect * from tb_user;/select
/mapper
接口文件
package com.itheima.mapper;import com.itheima.pojo.User;import java.util.List;public interface UserMapper {ListUser selectAll();
}三、MyBaits核心配置文件
MyBatis核心配置文件的顶层结构如下: !--用这个就可以省略前面的包名目录了
--
typeAliases package namecom.itheima.pojo/
/typeAliases细节配置各个标签时需要遵守前后顺序
四、 配置文件的增删改查 4.1 Mybatis案列
4.1.1 环境的准备 4.2 查询所有数据和结果映射
编写接口方法Mapper接口 参数无 结果List编写SQL语句SQL映射文件 执行方法测试
测试
package com.itheima.test;import com.itheima.mapper.BrandMapper;
import com.itheima.pojo.Brand;
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 org.junit.Test;import java.io.IOException;
import java.io.InputStream;
import java.util.List;public class MyBatisTest {Testpublic void testselectAll() throws IOException {//1.获取sqlSessionFactoryString resource mybatis-config.xml;InputStream inputStream Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory new SqlSessionFactoryBuilder().build(inputStream);//2.获取SQLsessionSqlSession sqlSession sqlSessionFactory.openSession();//3. 获取Mapper接口的代理对象BrandMapper brandMapper sqlSession.getMapper(BrandMapper.class);//4.执行方法ListBrand brands brandMapper.selectAll();System.out.println(brands);sqlSession.close();}
}
接口文件:
package com.itheima.mapper;import com.itheima.pojo.Brand;import java.util.List;public interface BrandMapper {public ListBrand selectAll();
}?xml version1.0 encodingUTF-8 ?
!DOCTYPE mapperPUBLIC -//mybatis.org//DTD Mapper 3.0//ENhttps://mybatis.org/dtd/mybatis-3-mapper.dtd
!--namespace: 名称空间
--
mapper namespacecom.itheima.mapper.BrandMapper!--statement--!--数据库表的字段名称 和 实体类的属性名称 不一样则不能自动封装数据起别名对不一样的列名起别名使其和实体类的属性名一样缺点每次查询都要定义一次别名sql片段缺点 不灵活resultMap1定义resultMap标签2在select标签中使用resultMap属性替换resultType属性--!--id:唯一标识type映射类型支持别名--resultMap idbrandResultMap typecom.itheima.pojo.Brand!--id:完成主键字段的映射column表的别名property实体类的属性名result完成一般字段的映射column表的别名property实体类的属性名--result columnbrand_name propertybrandName/result columncompany_name propertycompanyName//resultMapselect idselectAll resultMapbrandResultMapselect*from tb_brand;/select!--sql idbrand_columid,brand_name as brandName, company_name as companyName ,ordered,description,status/sqlselect idselectAll resultTypecom.itheima.pojo.Brandselectinclude refidbrand_colum/includefrom tb_brand;/select--
/mapper
核心配置文件
?xml version1.0 encodingUTF-8 ?
!DOCTYPE configurationPUBLIC -//mybatis.org//DTD Config 3.0//ENhttps://mybatis.org/dtd/mybatis-3-config.dtd
configuration!--environments:配置数据库连接环境信息可以配置多个environment,通过default属性切换不同的environment--typeAliases package namecom.itheima.pojo//typeAliasesenvironments defaultdevelopmentenvironment iddevelopmenttransactionManager typeJDBC/dataSource typePOOLED!--数据库连接信息--property namedriver valuecom.mysql.jdbc.Driver/property nameurl valuejdbc:mysql://localhost:3306/mybatis?useSSLfalseamp;serverTimezoneUTC/property nameusername valueroot/property namepassword value123456//dataSource/environment/environmentsmappers!--加载SQL的映射文件--mapper resourcecom/itheima/mapper/BrandMapper.xml//mappers
/configuration
实体类属性名和数据库表列名不一致不能自动封装数据
起别名:在sql语句中对不一样的列名起别名别名和实体类属性名一样 可以定义片段提升复用性 resultMap:定义完成不一致的属性名和列名的映射
4.3、查看详情单个查询
编写接口方法:Mapper接口 参数:id 结果:Brand编写SQL语句: SQL映射文件 执行方法测试
package com.itheima.test;import com.itheima.mapper.BrandMapper;
import com.itheima.pojo.Brand;
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 org.junit.Test;import java.io.IOException;
import java.io.InputStream;
import java.util.List;public class MyBatisTest_selectById {Testpublic void testselectAll() throws IOException {//1.获取sqlSessionFactoryString resource mybatis-config.xml;InputStream inputStream Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory new SqlSessionFactoryBuilder().build(inputStream);//2.获取SQLsessionSqlSession sqlSession sqlSessionFactory.openSession();//3. 获取Mapper接口的代理对象BrandMapper brandMapper sqlSession.getMapper(BrandMapper.class);//4.执行方法Brand brand1 brandMapper.selectByID(1);//打印结果System.out.println(brand1);sqlSession.close();}
}
接口文件
public interface BrandMapper {Brand selectByID(int id);
}Mapper映射文件
select idselectByID resultMapbrandResultMapselect *from tb_brandwhereid #{id};/select参数占位符
#{} 会将其替换为? 防止了sql注入$ {} 会将sql拼进去存在sql注入问题
使用时机 1.参数传递时#{} 2.表名或者列名不固定的情况下:${}会存在SQL注入问题
细节
参数类型parameterType:可以省略特殊字符处理 1.转义字符 2.CDATA区
输入CD会出现提示 语法 ![CDATA[ 内容]]可以将字符直接写入由于xml语句中许多符号无法直接打入 例如
4.4、条件查询
4.4.1、多条件查询
编写接口方法: Mapper接口 参数:所有查询条件 结果: ListBrand编写SQL语句:SQL映射文件执行方法测试
测试
public void testselectByCondition() throws IOException {//接收参数int status 1;String companyName 华为;String brandName 华为;//处理参数companyName % companyName %;brandName % brandName %;//使用brand对象进行查询/*Brand brand new Brand();brand.setStatus(status);brand.setCompanyName(companyName);brand.setBrandName(brandName);*///使用Map集合处理Map map new HashMap();map.put(status,status);map.put(companyName,companyName);map.put(brandName,brandName);//1.获取sqlSessionFactoryString resource mybatis-config.xml;InputStream inputStream Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory new SqlSessionFactoryBuilder().build(inputStream);//2.获取SQLsessionSqlSession sqlSession sqlSessionFactory.openSession();//3. 获取Mapper接口的代理对象BrandMapper brandMapper sqlSession.getMapper(BrandMapper.class);//4.执行方法// 4.1 使用散装参数进行查询//ListBrand brands brandMapper.selectByCondition(status, companyName, brandName);//4.2 使用brand对象进行查询//ListBrand brands brandMapper.selectByCondition(brand);//4.3 使用Map集合处理ListBrand brands brandMapper.selectByCondition(map);//打印结果System.out.println(brands);sqlSession.close();}
接口
/*
* 条件查询
* 参数
* 1. 散装参数如果方法中有多个参数需要使用Param(SQL参数占位符名称)* 2. brand对象参数: 对象的属性名称要和参数占位符名称一致* 3. Map集合参数
*
* */ListBrand selectByCondition(Param(status)int status,Param(companyName)String companyName,Param(brandName)String brandName);ListBrand selectByCondition(Brand brand);ListBrand selectByCondition(Map map);
}Mapper映射文件:
select idselectByCondition resultMapbrandResultMapselect *from tb_brandwhereif teststatus !null status #{status}/ifif testcompanyName !null and companyName ! and company_name like #{companyName}/ifif testbrandName !null and brandName ! and brand_name like #{brandName}/if/where/select散装参数 如果方法中有多个参数需要使用Param(“SQL参数占位符名称”) 实体类对象参数: 对象的属性名称要和参数占位符名称一致 Map集合参数 只需要保证SQL中的参数名 和 map集合的键的名称对应上即可设置成功 4.4.2、动态条件查询
SQL语句会随着用户的输入或外部条件的变化而变化我们称为动态SQL
MyBatis 对动态SQL有很强大的支撑:
if test逻辑表达式choose (when, otherwise)foreach
问题 当第一个条件判断不满足要求后面的条件判断满足要求会导致后面语句的and出现在第一个条件判断中使得报错 解决方案 写恒等式 where替换 where关键字
public void testselectByCondition() throws IOException {//接收参数int status 1;String companyName 华为;String brandName 华为;//处理参数companyName % companyName %;brandName % brandName %;//使用brand对象进行查询/*Brand brand new Brand();brand.setStatus(status);brand.setCompanyName(companyName);brand.setBrandName(brandName);*///使用Map集合处理Map map new HashMap();map.put(status,status);map.put(companyName,companyName);//map.put(brandName,brandName);//1.获取sqlSessionFactoryString resource mybatis-config.xml;InputStream inputStream Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory new SqlSessionFactoryBuilder().build(inputStream);//2.获取SQLsessionSqlSession sqlSession sqlSessionFactory.openSession();//3. 获取Mapper接口的代理对象BrandMapper brandMapper sqlSession.getMapper(BrandMapper.class);//4.执行方法// 4.1 使用散装参数进行查询//ListBrand brands brandMapper.selectByCondition(status, companyName, brandName);//4.2 使用brand对象进行查询//ListBrand brands brandMapper.selectByCondition(brand);//4.3 使用Map集合处理ListBrand brands brandMapper.selectByCondition(map);//打印结果System.out.println(brands);sqlSession.close();}接口文件没有变化
Mapper映射文件 select idselectByCondition resultMapbrandResultMapselect *from tb_brand!--当第一个条件判断不满足要求后面的条件判断满足要求会导致后面语句的and出现在第一个条件判断中使得报错解决方案1. 写恒等式2. where替换 where关键字--!--where//第一种解决方案11--!--第二种解决方案--whereif teststatus !null status #{status}/ifif testcompanyName !null and companyName ! and company_name like #{companyName}/ifif testbrandName !null and brandName ! and brand_name like #{brandName}/if/where/select
4.4.3、单条件动态条件查询
从多个条件中选择一个 choose (when, otherwise):选择类似于Java 中的switch语句
测试文件
Testpublic void testselectByConditionSingle() throws IOException {//接收参数int status 1;String companyName 华为;String brandName 华为;//处理参数companyName % companyName %;brandName % brandName %;//使用brand对象进行查询Brand brand new Brand();brand.setStatus(status);brand.setCompanyName(companyName);brand.setBrandName(brandName);//1.获取sqlSessionFactoryString resource mybatis-config.xml;InputStream inputStream Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory new SqlSessionFactoryBuilder().build(inputStream);//2.获取SQLsessionSqlSession sqlSession sqlSessionFactory.openSession();//3. 获取Mapper接口的代理对象BrandMapper brandMapper sqlSession.getMapper(BrandMapper.class);//4.执行方法//使用brand对象进行查询ListBrand brands brandMapper.selectByConditionSingle(brand);//打印结果System.out.println(brands);sqlSession.close();}
接口文件 ListBrand selectByConditionSingle(Brand brand);
}Mapper映射文件 select idselectByConditionSingle resultTypecom.Smulll.pojo.Brandselect *from tb_brandwherechoosewhen teststatus !nullstatus #{status}/whenwhen testcompanyName !null and companyName ! and company_name like #{companyName}/whenwhen testbrandName !null and brandName ! and brand_name like #{brandName}/whenotherwise11/otherwise/choose/select!-- ----------------------- -------------------------------------------------- ------select idselectByConditionSingle resultTypecom.Smulll.pojo.Brandselect *from tb_brandwherechoose!--类似于switch--when teststatus !null!--类似于case--status #{status}/whenwhen testcompanyName !null and companyName ! and company_name like #{companyName}/whenwhen testbrandName !null and brandName ! and brand_name like #{brandName}/whenotherwise!--类似于default--11/otherwise/choose/where/select4.5、添加
编写接口方法: Mapper接口 参数:除了id之外的所有数据 结果:void编写SQL语句:SQL映射文件
insert idaddinsert into tb_brand (brand_name, company_name, ordered, description, status)values (#{brandName},#{companyName},#{ordered},#{description},#{status});
/insert进行测试
MyBatis事务:
openSession():默认开启事务进行增删改操作后需要使sqlSession.commit();手动提交事务openSession(true):可以设置为自动提交事务(关闭事务)
/** 添加字段* */Testpublic void testAdd() throws IOException {//接收参数int status 1;String companyName 阿里粑粑有限公司;String brandName 阿里嘎多汽车;int order 100;String description 华华华华短视的;//使用brand对象进行查询Brand brand new Brand();brand.setStatus(status);brand.setCompanyName(companyName);brand.setBrandName(brandName);brand.setOrdered(order);brand.setDescription(description);//1.获取sqlSessionFactoryString resource mybatis-config.xml;InputStream inputStream Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory new SqlSessionFactoryBuilder().build(inputStream);//2.获取SQLsession 在里面传参数可以控制是否自动提交SqlSession sqlSession sqlSessionFactory.openSession(true);//3. 获取Mapper接口的代理对象BrandMapper brandMapper sqlSession.getMapper(BrandMapper.class);//4.执行方法brandMapper.add(brand);//提交事务sqlSession.commit();sqlSession.close();}添加-主键返回 在数据添加成功后需要获取插入数据库数据的主键的值 比如:添加订单和订单项 添加订单 添加订单项订单项中需要设置所属订单的id
insert idagdOrder useGeneratedKeystrue keyPropertyidinsert into tb_order (payment, payment_type, status)values (#{payment},#{paymentType},#{status});
linsertinsert idaddOrderlteminsert into tb_order_item (goods_name, goods_price,count,order_id)values (#{goodsName},#{goodsPrice},#{count},#{orderld});
/insert4.6、修改功能
4.6.1、修改全部字段
编写接口u方法Mapper接口 参数所有数据 结果void编写SQL语句SQL映射文件执行方法测试
/** 更新字段* */Testpublic void testUpdateAll() throws IOException {//接收参数int status 1;String companyName 阿里粑粑有限公司;String brandName 阿里嘎多汽车;int order 100;String description 华华华华短视的;int id 5;//使用brand对象进行查询Brand brand new Brand();brand.setStatus(status);brand.setCompanyName(companyName);brand.setBrandName(brandName);brand.setOrdered(order);brand.setDescription(description);brand.setId(id);//1.获取sqlSessionFactoryString resource mybatis-config.xml;InputStream inputStream Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory new SqlSessionFactoryBuilder().build(inputStream);//2.获取SQLsession 在里面传参数可以控制是否自动提交SqlSession sqlSession sqlSessionFactory.openSession(true);//3. 获取Mapper接口的代理对象BrandMapper brandMapper sqlSession.getMapper(BrandMapper.class);//4.执行方法brandMapper.update(brand);//提交事务sqlSession.commit();sqlSession.close();}
Mapper映射文件 update idupdateAllupdate tb_brandset brand_name #{brandName},company_name#{companyName},ordered#{ordered},description#{description},status#{status}where id#{id};/update接口文件 void updateAll(Brand brand);4.6.2、修改动态字段
编写接口方法: Mapper接口 参数:部分数据封装到对象中 结果: void编写SQL语句:SQL映射文件执行方法测试
public void testUpdate() throws IOException {//接收参数int status 1;String companyName 阿里粑粑有限公司;String brandName 阿里嘎多汽车;int order 100;String description 华华华华短视的;int id 5;//使用brand对象进行查询Brand brand new Brand();//brand.setStatus(status);//brand.setCompanyName(companyName);//brand.setBrandName(brandName);brand.setOrdered(order);//brand.setDescription(description);brand.setId(id);//1.获取sqlSessionFactoryString resource mybatis-config.xml;InputStream inputStream Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory new SqlSessionFactoryBuilder().build(inputStream);//2.获取SQLsession 在里面传参数可以控制是否自动提交SqlSession sqlSession sqlSessionFactory.openSession(true);//3. 获取Mapper接口的代理对象BrandMapper brandMapper sqlSession.getMapper(BrandMapper.class);//4.执行方法brandMapper.update(brand);//提交事务sqlSession.commit();sqlSession.close();}接口文件 void update(Brand brand);Mapper映射文件 update idupdateupdate tb_brandsetif testbrandName !null and brandName ! brand_name #{brandName},/ifif testcompanyName !null and companyName ! company_name#{companyName},/ifif testordered !null ordered#{ordered},/ifif testdescription !null and description ! description#{description},/ifif teststatus !null status#{status},/if/setwhere id#{id};/update4.7、删除功能
4.7.1、删除单个字段
编写接口方法: Mapper接口 参数: id 结果:void编写SQL语句: SQL映射文件执行方法测试 /** 删除字段* */Testpublic void testDelete() throws IOException {int id 6;//设置对象Brand brand new Brand();brand.setId(id);//1.获取sqlSessionFactoryString resource mybatis-config.xml;InputStream inputStream Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory new SqlSessionFactoryBuilder().build(inputStream);//2.获取SQLsession 在里面传参数可以控制是否自动提交SqlSession sqlSession sqlSessionFactory.openSession(true);//3. 获取Mapper接口的代理对象BrandMapper brandMapper sqlSession.getMapper(BrandMapper.class);//4.执行方法brandMapper.deleteById(brand);//提交事务sqlSession.commit();sqlSession.close();}接口文件 void deleteById(Brand brand);Mapper映射文件 delete iddeleteByIddelete from tb_brandwhere id #{id}/delete4.7.2、批量删除
编写接口方法: Mapper接口 参数:id数组 结果: void编写SQL语句: SQL映射文件执行方法测试 /** 批量删除字段* */Testpublic void testDeleteIds() throws IOException {int[] ids {7,8};//1.获取sqlSessionFactoryString resource mybatis-config.xml;InputStream inputStream Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory new SqlSessionFactoryBuilder().build(inputStream);//2.获取SQLsession 在里面传参数可以控制是否自动提交SqlSession sqlSession sqlSessionFactory.openSession(true);//3. 获取Mapper接口的代理对象BrandMapper brandMapper sqlSession.getMapper(BrandMapper.class);//4.执行方法brandMapper.deleteByIds(ids);//提交事务sqlSession.commit();sqlSession.close();}接口 mybatis会将数组参数封装为一个Map集合
默认array 数组使用Param注解改变map集合的默认key的名称
void deleteByIds(Param(Ids)int[] ids);Mapper映射文件 delete iddeleteByIdsdelete from tb_brandwhere id in(foreach collectionids itemid separator, open ( close ) #{id}/foreach)/delete4.8、参数传递
MyBatis 接口方法中可以接收各种各样的参数MyBatis底层对于这些参数进行不同的封装处理方式
单个参数:
POJO类型直接使用属性名 和 参数占位符名称一致Map集合直接使用键名 和 参数占位符名称一致Collection封装为Map集合可以使用Param注解替换Map集合中默认的arg键名
map.put(arg0,Collection集合)
map.put(collection,Collection集合)List封装为Map集合可以使用Param注解替换Map集合中默认的arg键名
map.put(arg0,List集合)
map.put(collection,List集合)
map.put(List,List集合)Array封装为Map集合可以使用Param注解替换Map集合中默认的arg键名
map.put(arg0,数组)
map.put(array,数组)其他类型直接使用
多个参数封装为Map集合可以使用Param注解替换Map集合中默认的arg键名
map.put(arg0,参数1)
map.put(param1,参数1)
map.put(arg1,参数2)
map.put(param2,参数2)
-------------Param(username)
map.put(username,参数1)
map.put(param1,参数1)
map.put(arg1,参数2)
map.put(param2,参数2)MyBatis提供了ParamNameResolver类来进行参数封装 建议:将来都使用Param注解来修改Map集合中默认的键名并使用修改后的名称来获取值这样可读性更高
4.9、注解开发
使用注解开发会比配置文件开发更加方便
Select(select * from tb_user where id #{id})
public User selectByld(int id);查询Select添加Insert修改Update删除Delete
提示 注解完成简单功能配置文件完成复杂功能 使用注解来映射简单语句会使代码显得更加简洁但对于稍微复杂一点的语句,Java注解不仅力不从心还会址你本就复杂的SQL语句更加期乱不堪。因此。如果你需要的一些很亮杂的涯作最好用XML来映射语句。
选择何种方式来配置映射以及认为是否应该要统一映射语句定义的形式完全取决于你和你的团队。换句话说永远不要拘泥于一种方式你可以很轻松的在基于注解和XML的语句映射方式间自由移植和切换。