文章目录
- 1.MyBatis介绍
- 2.MyBatis快速入门
- 3.Mapper代理开发
- 4.MyBatis核心配置文件
- 5.配置文件完成增删改查
- 5.1 查询
- 5.2 添加/修改
- 5.3 删除
- 6.MyBatis参数传递
- 7.注解完成增删改查
1.MyBatis介绍
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
2.持久层
- 负责将数据到保存到 数据库 的那一层代码
- JavaEE三层架构:表现层、业务层、持久层
3.框架
- 框架就是一个半成品软件,是一套可重用的、通用的、软件基础代码模型
- 在框架的基础之上构建软件编写更加高效、规范、通用、可扩展
2.MyBatis快速入门
查询 user 表中所有数据
1、添加依赖:
2、编写mybatis-config.xml配置文件
3.编写sql语句映射文件(UserMapper.xml)
4.获取工厂构造的对象,执行sql语句
3.Mapper代理开发
1.定义接口,返回值类型、方法名对应映射文件
2.maper映射文件放置相同目录下,名称空间为接口全限定名
3.mapper代理方式mybatis-config.xml可以使用包扫描的方式加载映射文件
4.获取 Mapper 接口对象,调用相应方法执行sql语句
4.MyBatis核心配置文件
配置的属性应符合以下顺序(官网),否则报错
<?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><!-- 给该包下的类起别名,为类名,不区分大小写 --><typeAliases><package name="com.eve.pojo"/></typeAliases><!--environments: 配置数据库连接环境信息, 通过default设置:development、test--><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="abc123"/></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:///testdb?useSSL=false"/><property name="username" value="root"/><property name="password" value="abc123"/></dataSource></environment></environments><mappers><!-- 加载sql映射文件 --><!--<mapper resource="com/eve/mapper/UserMapper.xml"/>--><!-- mapper代理方式(包扫描的方式) --><package name="com.eve.mapper"/> <!-- 扫描些目录下的所有映射文件 --></mappers>
</configuration>
5.配置文件完成增删改查
MyBatis动态Sql:
MyBatisX插件:
5.1 查询
1、表列和与属性名不一样(resultMap标签)、特殊字符处理(转义字符、CDATA区)
<?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="com.eve.mapper.BrandMapper"><!--数据库表中属性的名称和实体类属性名不一样:* 起别名:对不一样的别名起和pojo实体类相同的名称(每次查询都要起别名)* sql片断: 定义一个sql片断,然后导入(不灵活)* resultMap: id唯一标识,type映射的类型,column列名,property实体类属性类参数占位符:1. #{}: 会替换为 ? 占位符, 为防止 SQL 注入2. ${}: 拼SQL, 存在 SQL 注入问题3. 参数传递时使用 #{}4. 表名或列名不固定的情况下可以使用 ${}5. 参数类型: parameterType, 可以不写6. 特殊字符: 如 < 在这里是标签的起始符,* 转义字符: < >* CDATA区: <![CDATA[ ______ ]]> (纯文本处理)--><resultMap id="brandResultMap" type="com.eve.pojo.Brand"><!-- id: 主键字段的映射,result: 一般字段的映射 --><result column="brand_name" property="brandName"/><result column="company_name" property="companyName"/></resultMap><select id="selectAll" resultMap="brandResultMap">select *from tb_brand;</select><select id="selectById" resultMap="brandResultMap">select *from tb_brand where id = #{id};</select><select id="selectById1" resultMap="brandResultMap">select *from tb_brand where id<![CDATA[]]>#{id};</select></mapper>
2、多参数传递(多个参数、对象、集合)
public class BrandMapperTest {@Testpublic void selectByCondition() throws IOException {// 接收参数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);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.selectByCondition(map);System.out.println(brands);}
}
2、动态条件查询
多条件动态查询:
单条件查询:
5.2 添加/修改
添加:
返回主键(两个属性)
修改:
动态修改(set标签)
5.3 删除
批量删除(foreach标签)
6.MyBatis参数传递
封装:
MyBatis封装参数方法源码:
public Object getNamedParams(Object[] args) {int paramCount = this.names.size();if (args != null && paramCount != 0) {if (!this.hasParamAnnotation && paramCount == 1) {Object value = args[(Integer)this.names.firstKey()];return wrapToMapIfCollection(value, this.useActualParamName ? (String)this.names.get(0) : null);} else {Map<String, Object> param = new MapperMethod.ParamMap();int i = 0;for(Iterator var5 = this.names.entrySet().iterator(); var5.hasNext(); ++i) {Map.Entry<Integer, String> entry = (Map.Entry)var5.next();param.put(entry.getValue(), args[(Integer)entry.getKey()]);String genericParamName = "param" + (i + 1);if (!this.names.containsValue(genericParamName)) {param.put(genericParamName, args[(Integer)entry.getKey()]);}}return param;}} else {return null;}
}
&、map传递时,如何取出里面的User对象里的username、password值
<select id="selectBrandByName" resultMap="brandResultMap">select *from tb_brandwhere brand_name = #{brand.brandName}and company_name = #{brand.companyName};
</select>
7.注解完成增删改查
使用注解来映射简单语句会使代码显得更加简洁,但对于稍微复杂一点的语句,Java注解不仅力不从心,还会让你本就复杂的SQL语句更加混乱不堪。因此,如果你需要做一些很复杂的操作,最好用XML来映射语句。
选择何种方式来配置映射,以及认为是否应该要统一映射语句定义的形式,完全取决于你和你的团队。换句话说,永远不要拘泥于一种方式,你可以很轻松的在基于注解和ML的语句映射方式间自由移植和切换。