javaweb Mybatis 配置 代理开发 案例分析 增删改查 动态SQL

什么是MyBatis?

MyBatis 是一款优秀的持久层框架,用于简化 JDBC 开发

MyBatis 本是 Apache 的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。2013年11月迁移到Github

官网:https://mybatis.org/mybatis-3/zh/index.html

持久层

负责将数据到保存到数据库的那一层代码

JavaEE三层架构:表现层、业务层、持久层

框架

框架就是一个半成品软件,是一套可重用的、通用的、软件基础代码模型

在框架的基础之上构建软件编写更加高效、规范、通用、可扩展

JDBC缺点:

硬编码 注册驱动,获取连接 SQL 语句

操作繁琐 手动设置参数 手动封装结果集

mybatis 快速入门

 

创建mybatis_config.xml文件并配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//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:///db1?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="123"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
<!--        加载sql映射文件-->
        <mapper resource="brandMapper.xml"/>
    </mappers>
</configuration>

编写sql映射文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="test">
<!--    resultType放对应类的路径-->
    <select id="selectAll" resultType="com.ruler.pojo.Brand">
        select * from tb_brand;
    </select>
</mapper>

测试类:

public class Mybatis_test {
    public static void main(String[] args) throws IOException {
        //加载核心配置文件 获取sqlSessionFactory对象
        String resource = "mybatis_config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //获取sqlSession对象 执行sql语句
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //用名称空间的名字.select的id 作为参数
        List<Brand> list = sqlSession.selectList("test.selectAll");
        System.out.println(list);
        sqlSession.close();

    }
}

Mapper代理开发

1.定义与SQL映射文件同名的Mapper接口,并且将Mapper接口和SQL映射文件放置在同一目录下

为了保证代码的整洁性,我们在java文件夹下的com.ruler下创建一个mapper包,在mapper包中定义接口。然后再resources文件夹下创建一样的路径 写的时候要用 \ 而不是.  如 com\ruler\mapper,

这样就能保证编译出来Mapper接口和SQL映射文件在同一目录了

 

 

2.设置SQL映射文件的namespace属性为Mapper接口全限定名

<mapper namespace="com.ruler.mapper.brandMapper">
<!--    resultType放对应类的路径-->
    <select id="selectAll" resultType="com.ruler.pojo.Brand">
        select * from tb_brand;
    </select>
</mapper>

3.在 Mapper 接口中定义方法,方法名就是SQL映射文件中sql语句的id,并保持参数类型和返回值类型一致

public interface brandMapper {
    List<Brand> selectAll();
}

4.编码

通过 SqlSession 的 getMapper方法获取Mapper接口的代理对象

调用对应方法完成sql的执行

public static void main(String[] args) throws IOException {
    //加载核心配置文件 获取sqlSessionFactory对象
    String resource = "mybatis_config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    //获取sqlSession对象 
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //获取brandMapper接口的代理对象 执行语句
    brandMapper brandMapper = sqlSession.getMapper(brandMapper.class);
    List<Brand> brands = brandMapper.selectAll();
    System.out.println(brands);
    sqlSession.close();

}

 这样不管添加多少个mapper文件,都只需要这么一行代码就够了

mybatis 核心配置文件

 配置了别名之后,后面的包扫描只需要用文件名就可以了 ,且不区分大小写

environments:配置数据库连接环境信息,可以配置多个environment,通过default属性切换不同的environment

配置文件完成增删改查

下载mybatisx 插件 方便mapper跟对应接口的对照

查询

由于mysql的字段用_连接  跟JAVA字段不一样的时候 会设置不了数据 

1.起别名 ,用sql片段 

<sql id="brand_column" >
    id, brand_name as brandName, company_name as companyName, ordered, description, status
</sql>
<select id="selectAll" resultType="com.ruler.pojo.Brand">
    select <include refid="brand_column" />
    from tb_brand;
</select>

2.最常用的resultMap:定义<resultMap> 完成不一致的属性名和列名的映射

<mapper namespace="com.ruler.mapper.BrandMapper">
    
    <resultMap id="brandResultMap" type="brand">
        <result column="brand_name" property="brandName"></result>
        <result column="company_name" property="companyName"></result>
    </resultMap>
     //使用resultMap属性替换原来的resultType
    <select id="selectAll" resultMap="brandResultMap">
        select * from tb_brand;
    </select>
</mapper>

详情

 

1. 参数占位符:    

1)#{}:执行SQL时,会将#{}占位符替换为?,将来自动设置参数值    

2)${}:拼SQL。会存在SQL注入问题    

3) 使用时机:        

* 参数传递,都使用#{}        

* 如果要对表名、列名进行动态设置,只能使用${}进行sql拼接。

2. parameterType:    

* 用于设置参数类型,该参数可以省略  (在select尖括号内写)

3. SQL 语句中特殊字符处理:  

 * 转义字符  

 *  <![CDATA[ 内容 ]]>:  输入CD回车自动生成纯文本区域

条件查询

多条件查询

 创建方法时,一共有三种参数设置方式

接收参数

int status =1;

String companyName="华为";

String brandName="华为";

1.散装参数:如果方法中有多个参数,需要使用@Param(“SQL参数占位符名称”)

2.对象参数:对象属性名称要和参数占位符一致

3.map集合参数:只需要保证SQL中的参数名和map集合的键的名称对应上,即可设置成功

Map map =new HashMap();

map.put("status",status);

map.put("companyName",companyName);

map.put("brandName",brandName);

但是我们的SQL语句都是写死的,如果用户只输入其中两个参数,那么我们就完成不了了

动态条件查询

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

MyBatis 对动态SQL有很强大的支撑

if

choose (when, otherwise)

trim (where, set)

foreach

if:用于判断参数是否有值,使用test属性进行条件判断     

* 存在的问题:第一个条件不需要逻辑运算符     

* 解决方案:       

1) 使用恒等式让所有条件格式都一样   where 1=1 and 后面每个都有and就不会条件出错                         

2) <where> 标签替换 where 关键字 (居多)

示例:

<select id="selectByCondition" resultMap="brandResultMap">
    select *
    from tb_brand
    <where>
    and
    <if test="status!=null">status = #{status}</if>
    and
    <if test="companyName!=null and companyName!=''">company_name like #{companyName}</if>
    and
    <if test="brandName!=null and brandName!= ''">brand_name like #{brandName}</if>;
    </where>
</select>

单条件动态查询  choose (when, otherwise)   类似于Switch case 组合

先封装个brand对象,这样每个值的默认值都是null

<select id="selectByConditionSingle" resultMap="brandResultMap">
    select *
    from tb_brand
    where
    <choose>
    <when test="status!=null">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>1=1</otherwise>//保底 防止出错 或者直接用where 标签
    </choose>
</select>

添加

Brand brand =new Brand("旺旺雪饼","旺旺公司",1000,"你旺我旺大家旺",1);

brandMapper.add(brand);
//手动提交事务
sqlSession.commit();

这里图快,直接在构造方法里输入属性了

记得手动提交事务,或者直接设置自动提交事务

添加:主键返回  也就是返回添加属性的id值

需要在insert标签的时候添加两个属性就可以了

<insert  useGeneratedKeys="true" keyProperty="id">

这样我们就可以通过brand对象 调用get方法获取新插入数据的id了

修改

修改全部字段 

 修改动态字段

 

 用set标签代替原来的set字符,可以避免逗号引起错误

删除

删除一个

批量删除

 我们把传入的id 放进一个数组中作为参数

然后用foreach标签遍历,

mybatis会将数组参数封装成一个Map集合。

1.默认array = 数组  所以我们在collection要写成 “array”

2.但是我们也可以用@Param注解改变map集合的默认key的名称,collection 直接写“ids”

item等于得到的每一个数据为id ,

sepatator代表用逗号分割数组

open="("   在开始的时候拼一个左括号

close=")"  在结束的时候拼一个有括号  这样更美观

mybatis 参数传递 

mybatis 接口方法中可以接收各种各样的参数如下:

多个参数

单个参数:单个参数又可以是如下类型

Pojo类型:直接使用 属性名和参数占位符一致

Map集合类型  键名和参数占位符名称一致

Collection集合类型  封装为Map集合  可使用@Param注解替换 arg键名

          map.put("arg0",collection集合);

          map.put("collection",collection集合);

List集合类型  封装为Map集合  可使用@Param注解替换 arg键名

        map.put("arg0",list集合)

        map.put("collection",list集合)

        map.put("list",list集合)

Array类型 封装为Map集合  可使用@Param注解替换 arg键名

       map.put("arg0",数组);

       map.put("array",数组);

其他类型:直接使用

当有多个参数时,mybatis会把多个参数封装为Map集合

map.put("arg0",参数值1)

map.put("param1",参数值1)

map.put("arg1",参数值2)

map.put("param2",参数值2)

我们可以用 arg0 或者 param1来代表参数值1

@Param也就是替换 Map集合中默认的arg键名

注解开发

 直接在接口用注解写好方法就行了,可以用来完成简单功能

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值