【JavaWeb 之mybatis】一篇文字带你快速入门Mybatis

🌈博客主页:屠一乐的博客
📅 发文时间:2022.07.04
📕好文推荐Java网络编程
🎈 一定存在只有你才能做成的事
🌹 博主水平有限,如有错误,欢迎指正
欢迎各位👍收藏💎评论✉
在这里插入图片描述

MyBatis

什么是MyBatis?
。MyBatis是一款优秀的特久层框架,用于简化JDBC开发
MyBatis本是Apache的一个开源项目iBatis,2010年这个项目由apache software foundation迁移到了google code,并且改名为MyBatis。2013年11月迁移到Github
官网:https:l/mybatis.org/mybatis-3/zh/index.html
mybatis

持久层

负责将数据到保存到数据库的那一层代码
JavaEE三层架构:表现层、业务层、持久层

框架

框架就是一个半成品软件,是一套可重用的、通用的、软件基础代码模型
在框架的基础之上构建软件编写更加高效、规范、通用、可扩展

MyBatis快速入门

查询user表中所有数据
1.创建user表,添加数据
2.创建模块,导入坐标
3.编写MyBatis核心配置文件->替换连接信息解决硬编码问题
4.编写SQL映射文件->统一管理sq语句,解决硬编码问题
5.编码

<select id="selectAll" resultType="com.pojo.user"
select * from tb_user
</select>

1.定义P0J0类
2.加载核心配置文件,获取SqlSessionFactory对象
3.获取SqlSession对象,执行SQL语句
4.释放资源

导入connection,mybatis,logback等坐标

编写mybatis核心配置文件 mybatis-config.xml

<?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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/db14"/>
                <property name="username" value="root"/>
                <property name="password" value="value"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="UserMapper.xml"/>
    </mappers>
</configuration>

编写SQL映射文件 xxMapper.xml

<?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">
<mapper namespace="test">
    <select id="selectAll" resultType="com.pojo.User">
        select * from tb_user;
    </select>
</mapper>

编码

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.InputStream;
import java.util.List;

public class MybatisDemo {
    public static void main(String[] args) throws Exception{
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        SqlSession sqlSession = sqlSessionFactory.openSession();
        List<User> users = sqlSession.selectList("test.selectAll");
        System.out.println(users);
        sqlSession.close();
    }
}

Mapper 代理开发

使用 Mapper 代理方式完成入门案例
1.定义与SQL映射文件同名的Mapper接口,并且将Mapper接口和SQL映射文件放置在同一目录下
2.设置SQL映射文件的namespace属性为Mapper接口全限定名(包名+接口名)
3.在 Mapper 接口中定义方法,方法名就是SQL映射文件中sql语句的id,并保持参数类型和返回值类型一致
4.编码
1.通过SqISession 的 getMapper方法获取 Mapper接口的代理对象
2.调用对应方法完成sqI的执行
细节:如果Mapper接口名称和SQL映射文件名称相同,并在同一目录下,则可以使用包扫描的方式简化SQL映射文件的加载

<mappers>
<!--加载sqL的映射文件-->
<!--<mapper resource="com/itheima/mapper2/UserMapper.xml"/>-->
<package name="com.itheima.mapper"/>
</mappers>

MyBatis 核心配置文件详解

MyBatis核心配置文件的顶层结构如下:

  • configuration(配置)
  • properties(属性)
  • settings(设置)
  • typeAliases(类型别名)
  • typeHandlers(类型处理器)
  • objectFactory(对象工厂)
  • plugins(插件)
  • environments(环境配置)
    "environment(环境变量)
    ·transactionManager(事务管理器)
    • dataSource(数据源)
      databaseldProvider(数据库厂商标识)
      mappers(映射器)
      类型别名(typeAliases)
<typeAliases>
<package name="com.itheima.pojo"/>
</typeAliases>

细节:配置各个标签时,需要遵守前后顺序

配置文件完成查询所有

练习
查询-查询所有数据
1.编写接口方法:Mapper接口ListselectAll();
参数:无
结果:List
2.编写SQL语句:SQL映射文件:
3.执行方法,测试

<select id="selectAll"resultType="brand">
select from tb_brand;
</select>

实体类属性名和数据库表列名不一致,不能自动封装数据
1)起别名:在$QL语句中,对不一样的列名起别名,别名和实体类属性名一样
*可以定义片段,提升复用性
2)定义resultMap:完成不一致的属性名和列名的映射

<mapper namespace="com.mapper.BrandMapper">

    <!--    <select id="selectAll" resultType="brand">-->
    <!--        select id, brand_name as brandName, company_name  companyName, ordered, description, status-->
    <!--        from tb_brand;-->
    <!--    </select>-->
    <!--    resultMap:  1.定义<resultMap:>标签
                        2.在<select>标签中,使用resultMap属性替换resultType,属性
    id:唯一标识
    type:映射到类型,支持别名-->
    <resultMap id="brandResultMap" type="brand">
        <!--
                id:完成主键字段的映射
                column:表的列名
                property:实体类的属性名
                result:完成一般字段的映射
                coLumn:表的列名
                property:实体类的属性名-->
        <result column="brand_name" property="brandName"/>
        <result column="company_name" property="companyName"/>
    </resultMap>

    <select id="selectAll" resultMap="brandResultMap">
        select *
        from tb_brand;
    </select>
</mapper>

配置文件完成根据id查询

查询-查看详情
1.编写接口方法:Mapper接口Brand selectByld(int id);

参数:id
结果:Brand

2.编写SQL语句:SQL映射文件
3.执行方法,测试

<select id="selectByld"parameterType="int"resultType="brand">select from tb_brand where id =#id);
</select>
<select id="selectById" resultMap="brandResultMap">
        <!--
        *参数占位符:
        1.#{}:会将其替换为?,为了防止SQL注入
        2.${}:拼sqL,会存在SQL注入问题
        3.使用时机:
            *参数传递,都使用#{}
            *如果要对表名、列名进行动态设置,只能使用$进行sq拼接。
         2.parameterType:
            *用于设置参数类型,该参数可以省略
         3.SQL语句中特殊字符处理:
            *转义字符
            *<I[CDATA[内容]>
                    -->
        select *
        from tb_brand where id = #{id};
    </select>

配置文件完成条件查询

1.编写接口方法:Mapper接口
参数:所有查询条件
结果:List
2.编写SQL语句:SQL映射文件
3.执行方法,测试

List<Brand>selectByCondition(@Param("status")int status,@Param("companyName")String
companyName,@Param("brandName")String brandName);
    <!--1.参数查询,2.实体类封装,3.map-->
List<Brand>selectByCondition(Brand brand);
    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>

SQL语句设置多个参数有几种方式?
1)散装参数:需要使用@Parar(“SQL中的参数占位符名称”)
2)实体类封装参数
*只需要保证SQL中的参数名和实体类属性名对应上,即可设置成功
3)map集合
*只需要保证SQL中的参数名和map集合的键的名称对应上,即可设置成功

动态SQL

SQL语句会随着用户的输入或外部条件的变化而变化,我们称为动态SQL

<select id="selectByCondition" resultMap="brandResultMap">
        select *
        from tb_brand
        # where
        <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>
        </where>
    </select>

·MyBatis对动态SQL有很强大的支撑:
if
choose (when,otherwise)
trim (where,set)
foreach
if:用于判断参数是否有值,使用test属性进行条件判断
*存在的问题:第一个条件不需要逻辑运算符
*解决方案:
1)使用恒等式让所有条件格式都一样
2)标签替换where关键字

配置文件完成动态条件查询

查询-单条动态条件查询
从多个条件中选择一个
choose(when,otherwise):选择,类似于Java中的switch语句

<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 !=''">
            company_name like #(companyName}
         </when>
        <when test="brandName != null and brandName !=''">
           brand_name like #brandName}
        </when>
        <otherwise><!--类似于default-->
            1=1
        </otherwise>
    </choose>
</select>

配置文件完成添加

1.编写接口方法:Mapper接口void add(Brandbrand);
参数:除了id之外的所有数据
结果:void
2.编写SQL语句:SQL映射文件
3.执行方法,测试

<insert id="add">
insert into tb_brand (brand_name,company_name,ordered,description,status)
values (#{brandName},#{companyName},#{ordered},#{description},#{status})
</insert>

MyBatis事务:

openSession():默认开启事务,进行增删改操作后需要使用sqlSession.commit();手动提交事务
openSession(true):可以设置为自动提交事务(关闭事务)

添加一主键返回

在数据添加成功后,需要获取插入数据库数据的主键的值

比如:添加订单和订弹项
1.添加订单
2.添加订单项,订单项中需要设置所属订单的id

<insert id="addOrder"useGeneratedKeys="true"keyProperty="id">
insert into tb_order(payment,payment_type,status)
values(#payment),#paymentType),#(status));
</insert>
<insert id="addOrderltem">
	insert into 	tb_order_item(goods_name,goods_price,count,order_id)
	values (#goodsName),#(goodsPrice),#(count),#orderld});
</insert>

修改-修改全部字段

1.编写接口方法:Mapperf接口void update(Brand brand);
参数:所有数据
结果:void
2.编写SQL语句:SQL映射文件
3.执行方法,测试

<update id="update">
	update tb brand
	set brand_name =#(brandName),
        company_name =#(companyName},
        ordered #fordered),
        description =#(description),
        status =#(status}
    where id =#id);
</update>

修改-修改动态字段

1.编写接口方法:Mapper接口
参数:部分数据,封装到对象中
结果:void
2.编写SQL语句:SQL映射文件
3.执行方法,测试

<update id="Update">
            update tb_brand
            set brand_name   =#{brandName},
                company_name =#{companyName},
                description  =#{description},
                ordered      =#{ordered}
            where id = #{id}
        </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">
                status =#{status},
            </if>
        </set>
        where id =#{id};
    </update>

批量删除

1.编写接口方法:Mapper接口void deleteBylds(@Param(“ids”)int[]ids);
参数:id数组
结果:void
2.编写SQL语句:SQL映射文件
3.执行方法,测试

<delete id="deleteBylds">
delete from tb brand
where id in (?,?,?)
</delete>
<delete id="deleteBylds">
    delete from tb brand
    where id in
    <foreach collection="ids"item="id"separator=","open="("close=")">
    #{id}
    </foreach>
</delete>

MyBatis参数封装:MyBatis接口方法中可以接收各种各样的参数,MyBatis底层对于这些参数进行不同的封装处理方式
MyBatis参数封装:
*单个参数:
1.P0J0类型:直接使用,属性名和参数占位符名称一致
2.Map集合:直接使用,键名和参数占位符名称一致
3.Collection:封装为Map集合,可以使用@Param:注解,替换Map集合中默认的arg键名
map.put(“argo”,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(“argo”,数组);
map.put(“array”,数组);
6.其他类型:直接使用
*多个参数:封装为Map集合,可以使用@Param:注解,替换Map集合中默认的arg键名
map.put(“arg0”,参数值1)
map.pUt(“param1”,参数值1)
map.pUt(“param:2”,参数值2)
map.pUt(“agr1”,参数值2)
----aParam(“username”)
map.put(“username”,参数值1)
map.put(“param1”,参数值1)
map.put(“param2”,参数值2)

MyBatisa提供了ParamNameResolver类来进行参数封装

注解完成增删改查

使用注解开发会比配置文件开发更加方便
@Select(“select from tb_user where id =#{id}”)
public User selectByld(int id);
●查询:@Select
●添加:@Insert
●修改:@Update
删除:@Delete

提示:配置文件完成复杂功能
注解完成简单功能

使用注解来映射简单语句会使代码显得更加简洁,但对于稍微复杂一点的语句,Jva注解不仅力不从心,还会让你本就复杂的SQL语句更加混乱不堪。因此,如果你需要做一些很复杂的操作,最好用XML来映射语句。
选择何种方式来配置映射,以及认为是否应该要统一映射语句定义的形试,完全取决于你和你的团队。换句话说,永远不要拘泥于一种方式,你可以很轻松的在基于注解和XML的语句映射方式间自由移植和切换。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值