MyBatis(用于简化JDBC开发)
MyBatis是一款持久层框架,用于简化JDBC开发
持久层:将数据报错到数据库,持久化更改的意思
javaEE三层架构:表现层(页面)、业务层(处理逻辑)、持久层(数据永久化更改)
mybatis – MyBatis 3 | 入门https://mybatis.org/mybatis-3/zh/getting-started.html jdbc缺点:
1.硬编码(很多重复,且耦合性强的代码,注册驱动,获取连接、SQL语句)
2.操作繁琐(手动设置参数,手动封装结果集)
注意:在使用jdbc或mybatis时,需要在mysql中先创建表和添加数据,并且需要创建实体类
MyBatis操作步骤:(黑色字体都是格式,复制粘贴即可,红色字体根据需求修改)
1.创建user表,添加数据
2.创建模块,导入坐标,并在main文件中将logback.xml导入resources文件夹中
<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.32</version></dependency><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>
logback.xml
<?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>
3.编写MyBatis核心配置文件(替换连接信息,解决硬编码问题)
在main文件中的resources文件夹中创建名为mybatis-config.xml的file文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""https://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.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><mapper resource="UserMapper.xml"/>//注意此处为sql映射文件</mappers> </configuration>
4.编写SQL映射文件(统一管理sql语句,解决硬编码问题)
在main文件中的resources文件夹中创建名为UserMapper.xml的file文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""https://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="test">//名称空间<select id="selectAll" resultType="pojo.User">//resultType意思是最终输出类型select * from tb_user;</select>//select标签,也有其他的update、delete等标签,根据需求编辑 </mapper>
5.编码:
1.定义POJO类(创建User实体类)
2.加载核心配置文件,获取SqlSessionFactory对象
3.获取SqlSession对象,执行SQL语句
4.释放资源
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 pojo.User;import java.io.IOException; import java.io.InputStream; import java.util.List;public class mybatisdemo {public static void main(String[] args) throws IOException {String resource = "mybatis-config.xml";//导入mybatis核心配置文件InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();List<User> users = sqlSession.selectList("test.selectAll");//sql语句定位:空间名.id //selectList也可以改成selectOne只查询一个System.out.println(users);sqlSession.close();} }
解决SQL映射文件的警告提示:
产生原因:idea和数据库没有建立连接,不识别表信息
解决方式:在idea中配置Mysql数据库连接
解决步骤:
点击idea最右侧Maven上面的Database,然后点击+号选择Mysql,
Driver(驱动):选择MySQL
Host:localhost或者172.0.0.1 Port:3306
User:root
Password:1234
Database(你在mysql创建的数据库名称):mybatis
然后点击Test Connection如果提示成功就ok
当导入Database之后点击最高级的目录mybatis@localhost,然后再点击上面一排目录的QL,点击console(Defalut),就可以直接在该窗口写mysql语句
Mapper代理开发:
好处:
1.解决硬编码问题,
List<User> users = sqlSession.selectList("test.selectAll");
2.简化后期执行sql
注意:
在创建包时,java文件夹下可以创建package,而resources下只能创建Directory,在此处需要注意,不能用com.it.xxx,这样系统会自动定义为 名字叫com.it.xxx的文件夹,而不会像package自动分层,如果要创建分成则需要使用/分隔,com/it/xxx
maven在complie时即编译时,如果已经编译过一次,需要重新再编译,需要修改一下代码,不然不会重复编译,可以在代码中加入一些空格
Mapper代理开发步骤:(在上面MyBatis开发的基础上)
1.在java下创建一个名为mapper的package文件夹,并在文件夹内创建一个UserMapper接口(建议在java下创建一个com.公司官网名。的分层文件夹,方便归纳)
2.在java下的resources中创建一个与步骤1创建的路径同名的Directory(注意上面提到的Directory创建分层包的注意事项),并将UserMapper.xml的sql映射文件拖入创建好的Directory文件夹中
3.修改sql映射文件中的namespace空间名称名为UserMapper接口的全限定名com.mapper.UserMapper(com.mapper.UserMapper.java注意千万不要加.java,而且不要用/只能用.分隔,否则会报错)
4.在UserMapper接口中 写List<User> selectAll();(抽象方法,方法名是sql映射文件中sql语句的id,返回值是list集合,如果只返回一个可以写User)
5.注意,刚刚更改了sql映射文件的位置,那么在mybatis核心文件即mybatis-config.xml中修改一下sql映射文件的地址
6.编码(编写完运行run一下代码即可)
package com.it;import com.mapper.UserMapper; import com.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;public class mybatisdemo2 {public static void main(String[] args) throws IOException {String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();UserMapper userMapper = sqlSession.getMapper(UserMapper.class);List<User> users = userMapper.selectALl();System.out.println(users);sqlSession.close();} }
注意:为什么UserMapper.xml这个映射文件,能够在编译后在文件夹里和编码文件在同一个目录下呢?
因为在mybatis-config.xml核心配置文件下,最下面有个mappers,此处为映射位置
细节优化:
包扫描:即以后不管有多少映射文件,直接在mabatis核心配置文件的映射位置里直接写
</environments> <mappers><!--<mapper resource="com/mapper/UserMapper.xml"/>此处为注释--><package name = "com/mapper"/> //com/mapper为映射文件的地址 </mappers>
MyBatis-config.xml核心配置文件的详解:
环境配置:就是选择数据库进行操作,到时候可以配置多个数据库,可以用dafault切换测试开发等操作(除了数据库地址,其他的不修改)
<environments default="此处为数据库id">
<environment id = "development">...
<environment id = "test">...
类型别名:作用就是以后在sql映射文件里的ResultType输出结果类型可以直接写类型名称(不区分大小写 ),例如user
<typeAliases>
<package name = "com.pojo"/>
</typeAliases>
配置各个标签时,需要遵守前后顺序:
在官网有更详细的解释
安装:在idea内部下载 pulgins中下载 mybatisX插件(为效率而生)(安装好后有些地方例如若使用了myBatis核心配置文件类型别名字段,则可能会提示错误,但任然可以运行,可以使用警告压制)
插件作用:
1.XML和接口方法快速相互转跳
2.根据接口方法生成statement(即sql映射文件中的sql语句,保证接口的抽象方法名称和sql语句的id一致,自动生成)(即在接口中写抽象方法,然后可以快捷生成sql映射语句)
红色的鸟代表映射文件,蓝色的代表接口
增删改查操作:(使用测试用例,即在test.java下创建一个类用来编码)
核心步骤:1.sql语句咋写,2.是否有参数,3.返回的结果是集合还是单个数据
步骤:
1.在mapper接口编写抽象方法,快捷生成sql映射文件里的statement语句即sql语句
2.判断有无参数、返回结果是什么类型
3.执行方法
查询:
1.查询所有数据
2.查看详情
3.条件查询
1.多条件查询
2.多条件动态查询
3.单条件动态查询
查询所有数据:
1.首先要配置两个东西,一个是mysql中的数据库和数据,另一个是创建一个pojo实用类Brand
2.在新建一个BrandMapper接口,写好查询的抽象方法
3.另外需要新建一个与之对应的sql映射文件BrandMapper.xml
在sql映射文件中若出现没有sql语句提示:
需要操作两步:
1.点击右侧Database,然后点击刷新,才会将新创建的数据,刷新出来
2.小黄灯是输入部分sql语句后alt+Enter 然后按照下面的操作
点击小黄灯http://t.csdn.cn/9wYEP
出现问题:查询结果有两个字段都是null,实际mysql中该字段都有对应的数据
原因:mysql的字段为Brand_name,而idea中pojo封装数据的为brandName
处理方法:
1.直接在sql映射文件里的sql语句中用as起别名(不实用)
2.sql片段(不实用)
<sql id="brand_column">id,brand_name as brandName </sql><!--suppress MybatisXMapperXmlInspection --> <select id="selectAll" resultType="brand">select <include refid="brand_column"/>from tb_brand; </select>
3.sql映射 (不管有多少个语句,只需设置一次)
column为字段名,property为实体类的属性名,type为映射类型(支持别名),id为唯一标识(任意起),但注意,在select标签中要将resultType改成resultMap并指向resultMap的id名
<resultMap id="brandResultMap" type="brand"><result column="brand_name" property="brandName"/>//注意:此处有result或id,id就是指主键的映射,result指其他字段的映射<result column="company_name" property="companyName"/> </resultMap><!--suppress MybatisXMapperXmlInspection --> <select id="selectAll" resultMap="brandResultMap">select*from tb_brand; </select>
注意点:sql语句是传输给mysql里运行的,必须输入mysql能识别的字段,而sql映射,是处理从mysql传回到idea的数据,并将sql映射好的字段,进行转义
查看详情:
brandMapper接口
public interface BrandMapper {List<Brand> selectAll();Brand selectById(int id); }
sql映射文件
<select id="selectById" resultMap="brandResultMap">select * from tb_user where id = #{id} </select>
测试用例
public class mybatisTest {@Testpublic void testSelectAll() throws IOException {int id = 1;//当用户点击界面的查看详情,界面会把该数据的id返回到服务器,此处id为模拟String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);Brand brand = mapper.selectById(id);System.out.println(brand);sqlSession.close();} }
参数占位符:
1.#{}:将会用?来展位
2.${}:拼sql语句,会存在sql注入问题
使用时机:
参数传递,都用#{}
如果要对表名、列名进行动态设置,只能用${}进行sql动态拼接
在sql语句中有特殊字符:(因为当前编写的为xml文件)
用转义字符 <...
<![CDATA[内容]]>(当特殊字符很多时使用,按CD、sel会有语法提示)
条件查询:
1.多条件查询
2.多条件动态查询
3.单条件动态查询
多条件查询:(参数的接收方式有这几种:散装参数、对象参数、map集合参数)
所有条件用户必须填写,否则会报错
散装参数
BrandMapper接口
List<Brand> selectCondition(@Param("status")int status,@Param("brandName")String brandName,@Param("companyName")String companyName);//@Param("brandName")里的status要和sql中的占位符一致
sql映射文件
<select id="selectCondition" resultMap="brandResultMap">select *from tb_brand where status = #{status} and ( brand_name like #{brandName} or company_name like #{companyName} ); </select>
test测试用例
@Test public void testSelectCondition() throws IOException {int status = 1;String brandName = "华为";String companyName = "松鼠";brandName = "%" + brandName + "%";companyName = "%" + companyName + "%";String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);List<Brand> brands = mapper.selectCondition(status, brandName,companyName);System.out.println(brands);sqlSession.close(); }
对象参数
BrandMapper接口
List<Brand> selectCondition(Brand b);
sql映射文件不变
test测试用例
@Test public void testSelectCondition() throws IOException {int status = 1;String brandName = "华为";String companyName = "松鼠";brandName = "%" + brandName + "%";companyName = "%" + companyName + "%"; Brand b = new Brand();b.setStatus(status);b.setBrandName(brandName);b.setCompanyName(companyName);String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);List<Brand> brands = mapper.selectCondition(b);System.out.println(brands);sqlSession.close(); }
map集合参数
BrandMapper接口
List<Brand> selectCondition(Map map);
sql映射文件不变
test测试用例
@Test public void testSelectCondition() throws IOException {int status = 1;String brandName = "华为";String companyName = "松鼠";brandName = "%" + brandName + "%";companyName = "%" + companyName + "%";Map map = new HashMap();map.put("status",status);//键值对的键要和sql语句的占位符保持一致map.put("brandName",brandName);map.put("companyName",companyName);String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);List<Brand> brands = mapper.selectCondition(map);System.out.println(brands);sqlSession.close(); }
bug:用户不会填写全部的条件,可能只会只填写一个进行搜索,而只填写一个上面的方式是查询不出来的
即:最终输入的只有一个数据
Map map = new HashMap();
map.put("companyName",companyName);
解决方式:用多条件的动态查询
多条件动态查询:
所有条件,用户可以自行填写,例如3个条件,用户可能只填写1个或2个条件,也可以不填写直接点击查询
标签类型:
if
choose(when,otherwise)
trim(where,set)
foreach
if:相当于判断(一般作用是,但用户只输入了一个条件,直接查询的问题),格式按照下面的写
trim(where,set):where可以单独<where>,作用是如果开头是and或or会自动忽略,trim是可以自定义忽略内容
<select id="selectCondition" resultMap="brandResultMap">select *from tb_brand<trim prefix="where" prefixOverrides="and|or|(|)"> <!--<where>--><if test="status != null">status = #{status}</if><if test="brandName !=null and brandName != '' ">and ( brand_name like #{brandName}</if><if test="companyName !=null and companyName != '' ">or company_name like #{companyName} )</if>; <!--</where>--></trim></select>
但括号忽略不了??
单条件动态查询:(选择任意一个条件进行查询)
用户从多个条件中选择其中一个条件,第二框是输入搜索内容,也可以啥都不选直接点击查询
注意:
条件的填写方式有选择和填写等,例如status条件,我可以用选择的方式选择1、2、3,或者直接是输入框的方式填写1、2、3
选择条件的意思是,例如有A,B,C三个条件,我选择A条件,并输入内容,进行搜索,就是上面那张图
choose(when,otherwise):choose相当于switch,when相当于case,otherwise相当于default
List<Brand> selectConditionSingle(Map map);
<select id="selectConditionSingle" resultMap="brandResultMap">select *from tb_brand //where<where><choose><when test="status != null">status = #{status}</when><when test="brandName !=null and brandName != '' ">and brand_name like #{brandName}</when><when test="companyName !=null and companyName != '' ">and company_name like #{companyName}</when><otherwise>1=1</otherwise></choose></where></select>
当使用的是where,需要使用到<otherwise>
日志结果:select * from tb_brand WHERE 1=1
当使用<where>,可以不用<otherwise>,会自动判断若where后面没有条件,where会自动消失
日志结果:select * from tb_brand
上面的恒等式的出现,是为了防止,用户没有选择任何条件,直接点击搜索导致的报错
@Test public void testSelectConditionSingle() throws IOException {int status = 1;String brandName = "华为";String companyName = "松鼠";brandName = "%" + brandName + "%";companyName = "%" + companyName + "%";Map map = new HashMap();//map.put("status",status);//map.put("brandName",brandName);//map.put("companyName",companyName);String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);List<Brand> brands = mapper.selectConditionSingle(map);System.out.println(brands);sqlSession.close(); }
添加:
void add(Brand b);
<insert id="add" useGeneratedKeys="true" keyProperty="id">insert into tb_brand (brand_name, company_name, ordered, description, status)values (#{brandName},#{companyName},#{ordered},#{description},#{status});</insert>
@Test public void testAdd() throws IOException { int status = 1;String brandName = "大白熊";String companyName = "大白熊公司";int ordered = 123;String description = "大白熊是巨星";Brand b = new Brand();b.setStatus(status);b.setBrandName(brandName);b.setCompanyName(companyName);b.setOrdered(ordered);b.setDescription(description);String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession(true);BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); mapper.add(b); //sqlSession.commit(); Integer id = b.getId();System.out.println(id);sqlSession.close(); }
注意:若没有开启事务,就算运行成功,在mysql里查询结果是没有添加的,因为事务被回滚了
解决方法:在openSession(true)中开启事务,或者sqlSession调用,sqlSession.commit()方法
日志里有提示:
[DEBUG] 08:56:30.910 [main] o.a.i.t.j.JdbcTransaction - Opening JDBC Connection
[DEBUG] 08:56:31.285 [main] o.a.i.d.p.PooledDataSource - Created connection 501187768.
[DEBUG] 08:56:31.285 [main] o.a.i.t.j.JdbcTransaction - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@1ddf84b8]
[DEBUG] 08:56:31.291 [main] c.m.B.add - ==> Preparing: insert into tb_brand (brand_name, company_name, ordered, description, status) values (?,?,?,?,?);
[DEBUG] 08:56:31.332 [main] c.m.B.add - ==> Parameters: 大白熊(String), 大白熊公司(String), 123(Integer), 大白熊是巨星(String), 1(Integer)
[DEBUG] 08:56:31.335 [main] c.m.B.add - <== Updates: 1
[DEBUG] 08:56:31.336 [main] o.a.i.t.j.JdbcTransaction - Rolling back JDBC Connection [com.mysql.jdbc.JDBC4Connection@1ddf84b8]
[DEBUG] 08:56:31.350 [main] o.a.i.t.j.JdbcTransaction - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@1ddf84b8]
[DEBUG] 08:56:31.351 [main] o.a.i.t.j.JdbcTransaction - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@1ddf84b8]
[DEBUG] 08:56:31.351 [main] o.a.i.d.p.PooledDataSource - Returned connection 501187768 to pool.
注意点:当在添加的同时返回id主键时候,需要在sql语句里添加
<insert id="add" useGeneratedKeys="true" keyProperty="id">
否则,返回的是null(id值本身就存在,只是没有绑定到sql语句里)
应用场景:
订单项的外键,要指向订单的id主键
修改:
1.修改全部字段
2.修改动态字段
修改全部字段:
可以用int也可以用void,看需求
int updata(Brand b);
<update id="updata">update tb_brandsetstatus = #{status},company_name = #{companyName},ordered = #{ordered},description = #{description},brand_name = #{brandName}where id = #{id}; </update>
@Test public void testUpdata() throws IOException { int status = 1;String brandName = "大白熊";String companyName = "大白熊公司";int ordered = 1236666;String description = "大白熊是巨星,很大6666666";int id = 6;Brand b = new Brand();b.setStatus(status);b.setBrandName(brandName);b.setCompanyName(companyName);b.setOrdered(ordered);b.setDescription(description);b.setId(id);String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);int updata = mapper.updata(b);System.out.println(updata);sqlSession.commit();sqlSession.close(); }
修改动态字段:
应用场景:
用户信息里包含账号密码信息,如果不使用动态字段,默认还是使用之前的全部字段修改,会导致只有账号密码修改,其他的字段都会被复制为null,从而修改错误
解决方式:sql语句加if判断
<update id="updata">update tb_brand<set><if test="status !=null">status = #{status},</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="brandName !=null and brandName != '' ">brand_name = #{brandName}</if></set>where id = #{id}; </update>
<set>标签用于解决:
1.如果一个条件都没有填写直接提交的问题(但是出现报错问题??)
2.若不填写最后一个brand_name = #{brandName}条件,只填写前面的任意条件,那么会出现 update tb_brand set status = ? , where id = ?;语句中有逗号,导致sql语法错误
@Test public void testUpdata() throws IOException {int status = 0;String brandName = "大白熊";String companyName = "大白熊公司";int ordered = 1236666;String description = "大白熊是巨星,很大6666666";int id = 9;Brand b = new Brand();b.setStatus(status); //b.setBrandName(brandName);//b.setCompanyName(companyName);//b.setOrdered(ordered);//b.setDescription(description);b.setId(id);String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);int updata = mapper.updata(b);System.out.println(updata);sqlSession.commit();sqlSession.close(); }
删除:
1.删除一个
2.批量删除
删除一个:
void deleteid(int id);
<delete id="deleteid">deletefrom tb_brandwhere id = #{id}; </delete>
@Test public void testDelete() throws IOException {int id = 9;String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);mapper.deleteid(id);sqlSession.commit();sqlSession.close(); }
批量删除:(动态)
foreach:
注意:当删除的id不存在时,受影响行数为0,不会报错
void deleteids(int[] ids);
<delete id="deleteids">deletefrom tb_brandwhere id in<foreach collection="array" item="id" separator="," open="(" close=")">#{id}</foreach> ; </delete>
foreach为动态生成,即用户可能勾选多个选项。
collection为数组名
注意:mybatis会将数组参数,封装为一个Map集合
1.默认Map集合为("array",数组名)
2.使用@Param注解改变map集合的默认key的名称
若collection就要使用ids,那么在接口的抽象方法就必须使用@Param注解改变map集合的默认key的名称:void deleteids(@Param("ids")int[] ids);
item为id字段名
separator为分隔符,当勾选了2个以上时,需要用,分隔符隔开
open为开头需要插入(
close为结束需要插入 )
@Test public void testDeleteids() throws IOException {int[] id = {4,6,8,10};//这些数据都是前端传过来的String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); mapper.deleteids(id); sqlSession.commit();sqlSession.close(); }
参数传递:
MyBatis参数封装:
单个参数:(需要注意,单个参数如果参数类型为Collection、List、Array数组,则接口的抽象方法的参数必须(最好)使用@Param注解替换键名)
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:其他参数:直接使用,属性名和参数占位符名称要一致,例:int等
多个参数:
封装为Map集合,可以使用@Paran注解,替换Map集合中默认的arg键名
参数1:
map.put("arg0",参数值1);
map.put("param1",参数值1);
参数2:
map.put("arg1",参数值2);
map.put("param2",参数值2);
结论:只要是底层封装为Map集合,统一用@Param注解
??
注解开发:(只能完成简单的sql语句)
MyBatis(用于简化JDBC开发)相关推荐
- Spring JDBC开发
Spring JDBC开发 @(Spring)[spring jdbc] Spring JDBC开发 Spring的JDBC模板的概述 什么是JDBC的模板 Spring的JDBC模板入门 创建web ...
- Spring框架对JDBC的简单封装。提供了一个JDBCTemplate对象简化JDBC的开发
Spring JDBC * Spring框架对JDBC的简单封装.提供了一个JDBCTemplate对象简化JDBC的开发 * 步骤: 1. 导入jar包 ...
- Spring JDBC,JDBCTemplate对象简化JDBC的开发
Spring JDBC,JDBCTemplate对象简化JDBC的开发 本篇文章中使用到了Druid数据库连接池,和自己创建的一个配合数据库连接池的工具类,本篇文章对于这些没有进行详细说明,对于这个, ...
- 6、HIVE JDBC开发、UDF、体系结构、Thrift服务器、Driver、元数据库Metastore、数据库连接模式、单/多用户模式、远程服务模式、Hive技术原理解析、优化等(整理的笔记)
目录: 5 HIVE开发 5.1 Hive JDBC开发 5.2 Hive UDF 6 Hive的体系结构 6.2 Thrift服务器 6.3 Driver 6.4 元数据库Metastore 6.5 ...
- Spring简化Java开发_spring如何简化java开发
1.spring简介 Spring的主要目的是用来替代更加重量级的企业级的java技术 2.spring如何简化java开发 1)基于POJO的轻量级和最小侵入性编程: 2)通过依赖注入和面向接口实现 ...
- Spring+Dubbo+MyBatis+Linner分布式Web开发环境搭建
Spring+Dubbo+MyBatis+Linner分布式Web开发环境搭建 本文承接我之前的博客<Spring+Maven+Dubbo+MyBat ...
- Spring+Dubbo+MyBatis+Linner分布式Web开发环境(一)
本文承接<Spring+Maven+Dubbo+MyBatis+Linner+Handlebars-Web开发环境搭建>,以下对相关的Maven配置和详细的Spring配置文件进 ...
- 用JSP+JDBC开发Web程序
以前一直想找个纯粹的JSP+JDBC开发Web程序的架构,一直没有找到合适的,后来自己写了一个简单实现,并实施了几个项目. 此开发架构的特点是: 1.架构技术简单,只包含JSP和JDBC,不需要学习即 ...
- Bootstrap4+MySQL前后端综合实训-Day05-AM【MySQL数据库(SQLyog软件基本操作、架构设计器)、eclipse(JDBC开发-添加驱动、构建路径、增删改查基本测试)】
[Bootstrap4前端框架+MySQL数据库]前后端综合实训[10天课程 博客汇总表 详细笔记] 目 录 MySQL数据库--建库.建表 新建连接.测试连接 新建news_manager数据库 ...
最新文章
- UITableView 局部刷新
- c盘扩展卷是灰色的_技术丨电脑C盘装太满?这几招轻松释放空间
- Css网格布局-Grid布局
- 地址栏中的问号有什么作用
- 建一个电赛交流群-大鱼机器人公众号专属
- 微信小程序使用函数的方法
- WinFormreportViewer报表[矩阵]的使用(一)(附源码示例) 之配餐系统的开发
- 【编译原理笔记16】代码优化:流图,常用代码优化方法, 基本块的优化
- 11gR2集群件任务角色分离(Job Role Separation)简介
- zeal刷新不出来_热血传奇:计算怪物刷新时间,升级速度立马不同,老玩家笑出了声。...
- 李华锦叔叔:追女生该如何正确的花钱?
- gtasa手机版android7.1,圣安地列斯psp移植版
- Linux查看CPU信息机器型号等硬件信息
- Redis三大特殊类型介绍:GEO,hyperloglog,bitmap,Redis事务
- 电力拖动自动控制系统matlab,基于Matlab的《电力拖动自动控制系统》课程教学改革...
- found 1 high severity vulnerability in 1481 scanned packages run `npm audit fix` to fix 1 of them.
- Windows 11 修改桌面文件路径
- 实时获取当前的时区和时间的方法
- 源生的html属性js,使用源生JS自定义动画(支持多个属性)
- 系统检测到您的账户不符合国家相关法律法规或《支付宝用户服务协议》约定,暂时无法签约当前产品