Mybatis构建sql语法

构建sql:
  • 之前通过注解开发时,相关 SQL 语句都是自己直接拼写的。一些关键字写起来比较麻烦、而且容易出错。
  • MyBatis 给我们提供了 org.apache.ibatis.jdbc.SQL 功能类,专门用于构建 SQL 语句

常用方法:
在这里插入图片描述

查询功能的实现:
  • @SelectProvider:生成查询用的 SQL语句注解
    • type 属性:生成 SQL 语句功能类对象
    • method 属性:指定调用方法
新增功能的实现:
  • @InsertProvider:生成新增用的 SQL 语句注解。
    • type 属性:生成 SQL 语句功能类对象
    • method 属性:指定调用方法
修改功能的实现:
  • @UpdateProvider:生成修改用的 SQL 语句注解。
    • type 属性:生成 SQL 语句功能类对象
    • method 属性:指定调用方法
删除功能的实现:
  • @DeleteProvider:生成删除用的 SQL 语句注解
    • type 属性:生成 SQL 语句功能类对象
    • method 属性:指定调用方法
演示:

SQL类:

public class ReturnSql {
    //定义方法,返回查询的sql语句
    public String getSelectAll() {
        return new SQL() {
            {
                SELECT("*");
                FROM("student");
            }
        }.toString();
    }

    //定义方法,返回新增的sql语句
    public String getInsert(Student stu) {
        return new SQL() {
            {
                INSERT_INTO("student");
                INTO_VALUES("#{id},#{name},#{age}");
            }
        }.toString();
    }

    //定义方法,返回修改的sql语句
    public String getUpdate(Student stu) {
        return new SQL() {
            {
                UPDATE("student");
                SET("name=#{name}","age=#{age}");
                WHERE("id=#{id}");
            }
        }.toString();
    }

    //定义方法,返回删除的sql语句
    public String getDelete(Integer id) {
        return new SQL() {
            {
                DELETE_FROM("student");
                WHERE("id=#{id}");
            }
        }.toString();
    }
}

接口:

public interface PersonMapper {
    //查询全部
    //@Select("SELECT * FROM student")
    @SelectProvider(type = ReturnSql.class , method = "getSelectAll")
    public abstract List<Student> selectAll();

    //新增功能
    //@Insert("INSERT INTO student VALUES (#{id},#{name},#{age})")
    @InsertProvider(type = ReturnSql.class , method = "getInsert")
    public abstract Integer insert(Student stu);

    //修改功能
    //@Update("UPDATE student SET name=#{name},age=#{age} WHERE id=#{id}")
    @UpdateProvider(type = ReturnSql.class , method = "getUpdate")
    public abstract Integer update(Student stu);

    //删除功能
    //@Delete("DELETE FROM student WHERE id=#{id}")
    @DeleteProvider(type = ReturnSql.class , method = "getDelete")
    public abstract Integer delete(Integer id);
}

测试:

    @Test
    public void selectAll() throws Exception {
        //1.加载核心配置文件
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");

        //2.获取SqlSession工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

        //3.通过工厂对象获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);

        //4.获取One接口的实现类对象
        PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);

        //5.调用实现类的方法,接收结果
        List<Student> list = mapper.selectAll();

        //6.处理结果
        for (Student c : list) {
            System.out.println(c);
        }

        //7.释放资源
        sqlSession.close();
        is.close();
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
MyBatis是一款优秀的持久层框架,它支持使用动态SQL语句,灵活地构建SQL语句,使得开发者能够更加方便地实现复杂的业务逻辑。下面介绍一些MyBatis动态SQL使用的技巧: 1. if标签 if标签用于判断条件是否成立,从而决定是否拼接SQL语句。if标签的语法如下: ```xml <select id="findUsers" resultType="User"> select * from user <where> <if test="username != null"> and username = #{username} </if> <if test="email != null"> and email = #{email} </if> </where> </select> ``` 上面的代码中,如果传入的username或email不为null,就会拼接相应的SQL语句。这样可以避免拼接过多的无用SQL语句。 2. choose、when、otherwise标签 choose、when、otherwise标签用于实现多重条件判断。当条件成立时,执行对应的SQL语句。choose、when、otherwise标签的语法如下: ```xml <select id="findUsers" resultType="User"> select * from user <where> <choose> <when test="username != null"> and username = #{username} </when> <when test="email != null"> and email = #{email} </when> <otherwise> and 1=1 </otherwise> </choose> </where> </select> ``` 上面的代码中,如果传入的username不为null,就会执行第一个when标签中的SQL语句;如果传入的email不为null,就会执行第二个when标签中的SQL语句;如果传入的username和email都为null,就会执行otherwise标签中的SQL语句。 3. foreach标签 foreach标签用于遍历集合,将集合中的元素拼接成SQL语句。foreach标签的语法如下: ```xml <update id="batchUpdate"> update user set username = #{username}, email = #{email} where id in <foreach collection="ids" item="id" separator="," open="(" close=")"> #{id} </foreach> </update> ``` 上面的代码中,将传入的ids集合中的元素拼接成SQL语句,实现批量更新操作。 4. bind标签 bind标签用于将表达式的值绑定到指定的变量上。bind标签的语法如下: ```xml <select id="findUsers" resultType="User"> <bind name="pattern" value="'%' + username + '%'"/> select * from user where username like #{pattern} </select> ``` 上面的代码中,将传入的username值绑定到pattern变量上,并将pattern变量拼接到SQL语句中,实现模糊查询操作。 以上是MyBatis动态SQL使用的一些技巧,可以帮助开发者更加灵活地构建SQL语句,实现复杂的业务逻辑。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

itzhuzhu.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值