😀搭建 MyBatis
mysql
mysql-connector-java
8.0.29
org.mybatis
mybatis
3.5.7
junit
junit
4.12
test
- mapper 接口的全类名和映射文件中的命名空间保持一致
-
mapper 接口中的方法名和映射文件中的 SQL 标签的 id 属性保持一致
-
也可以配置 properties 类型的配置文件,方式不同
😁配置文件详解
配置文件的顺序
配置文件的一些标签可以不写, 但顺序一定不能乱
properties、settings、typeAliases、typeHandlers、objectFactory、objectWrapperFactory、reflectorFactory、plugins、environments、databaseIdProvider、mappers
🤣MyBatis的增删改查(直接写入参数)
insert into user values (null,'大白','12345')
delete from user where id=1
select * from user where id=10
select * from user
updata user set name='张三' where id=5
- select标签必须设置属性resultType或者resultMap,用于设置实体类和数据库表的映射关系
- resultType: 自动映射,用于属性名与表中字段一致的情况
- resultMap: 自定义映射,用于一对多或多对一或属性名与表中字段不一致的情况
- 当查询的数据为多条的时候,不能使用实体类作为返回值,只能使用集合,否则抛出异常TooManyResultsException
😊MyBatis获取参数的两种方式
- 本质是预编译处理
- MyBatis在处理#{}的时候,会把#{}替换为?,调用PerparedStatement的set方法来赋值
- 使用#{}可以有效防止SQL注入,SQL注入是发生在编译阶段,而预编译是提前对SQL语句进行编译,而后注入的参数将不再进行编译,预编译完成之后,SQL结构已经固定,如此可以有效防止SQL注入
-
自动添加单引号
-
本质是字符串替换
- 把${}替换成变量的值
- 若为字符串或日期类型的字段进行赋值时,需手动添加单引号
🧐参数类型
若mapper接口中方法的参数是单个参数,可以使用#{}或${}以任意参数名名称获取
delete from user where id=#{userId}
- 若mapper接口中方法的参数是多个参数,MyBatis会自动的将这些参数放入map集合中
- 以arg0,arg1,…为键,以参数为值
- 以param1,param2,…为键,以参数为值
- 以#{}或${}访问map集合中的键,就可以拿到值
- arg是以arg0开始,param以param1开始
update user set name = #{arg0} where id=#{arg1}
若mapper接口的方法参数为多个时,可以手动创建一个map集合,将参数放入map集合中,使用#{}或${}访问map集合对应的键就可以拿到相应的值
insert into user values (null,#{name},#{password})
若mapper接口方法参数为实体类型时,使用#{}或${}访问实体对象的属性名拿到属性值
insert into user values (null,#{name},#{password})
- 可以通过@Param注解标识mapper接口中的方法参数,会将这些参数放入map集合中
- 以@Param注解的value属性值为键,以参数为值
- 以param1,param2,…为键,以参数为值
- 只需通过#{}或${}访问集合中的键,将能拿到相应的参数值
select * from user where name=#{name} and password=#{password}
😝MyBatis的查询功能
select * from user where id=#{userId}
select * from user
注意将resultType设置为map
select *from user where id=#{userId}
- 方法一
select *from user
- 方法二 使用@MapKey
select *from user
Original: https://www.cnblogs.com/suwuji/p/16556930.html
Author: 苏无及
Title: MyBatis详解
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/611840/
转载文章受原作者版权保护。转载请注明原作者出处!