java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Mybatis构建SQL语句

Mybatis如何构建SQL语句

作者:金鳞踏雨

这篇文章主要介绍了Mybatis如何构建SQL语句问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

SQL构建对象介绍

我们之前通过注解开发时,相关 SQL 语句都是自己直接拼写的。

一些关键字写起来比较麻烦、而且容易出错

MyBatis 给我们提供了 org.apache.ibatis.jdbc.SQL 功能类,专门用于构建 SQL 语句。

就是使用方法调用来代替之前繁琐的SQL编写。 

我们来使用一下Mybatis提供的SQL功能类

package com.itheima.sql;
import org.apache.ibatis.jdbc.SQL;
 
public class sqlTest {
    public static void main(String[] args) {
        String sql = getSql();
        System.out.println(sql);
        // 输出
        // SELECT *
        // FROM student
    }
 
    public static String getSql() {
        String sql = new SQL() {
            {
                SELECT("*");
                FROM("student");
            }
        }.toString();
        return sql;
    }
}

我们可以查看一下SQL功能类

package org.apache.ibatis.jdbc;
public class SQL extends AbstractSQL<SQL> {
    public SQL() {
    }
    public SQL getSelf() {
        return this;
    }
}

再查看一下它的父类

显然,这些大家都应该很熟悉,都是SQL中的关键字,使用SQL功能类,可以降低在开发中的出错率。

查询功能的实现

定义功能类并提供获取查询的 SQL 语句的方法。

@SelectProvider:生成查询用的 SQL 语句注解

ReturnSql类

这里面创建SQL的功能类

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

StudentMapper类

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

这里的type的值就是生成 SQL 语句功能类对象——ReturnSqlmethod的值就是功能类中的方法

——getSelectAll

Test类

public class Test01 {
    @Test
    public void selectAll() throws IOException {
        // 1.加载核心配置文件
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
        // 2.获取SqlSession工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        // 3.通过工厂对象获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        // 4.获取StudentMapper接口的实现类对象
        // 通过StudentMapper的字节对象 来得到实现类对象
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        // 5.调用实现类对象中的方法
        List<Student> list = mapper.selectAll();
        // 6.处理结果
        for (Student student : list) {
            System.out.println(student);
        }
        // 7.释放资源
        sqlSession.close();
        is.close();
    }
}

新增、修改、删除功能的实现

其实这些都是大同小异,比起之前的Mybatis框架前面的学习不值一提,只要调用函数就可以实现。

完整代码展现

项目骨架

bean包下的Student类

映射配置文件StudentMapper接口

我们使用注解的方式将SQL工具类引入

public interface StudentMapper {
    // 查询全部
    //@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);
}

sql包下的ReturnSql类

里面编写了SQL功能类

public class ReturnSql {
    // 定义方法,返回用来查询的SQL语句
    public String getSelectAll() {
        return new SQL() {
            {
                SELECT("*");
                FROM("student");
            }
        }.toString();
    }
 
    public String getInsert(Student stu) {
        return new SQL() {
            {
                INSERT_INTO("student");
                INTO_VALUES("#{id},#{name},#{age}");
            }
        }.toString();
    }
 
    public String getUpdate(Student stu) {
        return new SQL() {
            {
                UPDATE("student");
                SET("name=#{name}","age=#{age}");
                WHERE("id=#{id}");
            }
        }.toString();
    }
 
    public String getDelete(Integer id) {
        return new SQL() {
            {
                DELETE_FROM("student");
                WHERE("id=#{id}");
            }
        }.toString();
    }
}

测试方法

package com.itheima.test;
 
import com.itheima.bean.Student;
import com.itheima.mapper.StudentMapper;
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 org.junit.Test;
 
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
 
public class Test01 {
    @Test
    public void selectAll() throws IOException {
        // 1.加载核心配置文件
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
        // 2.获取SqlSession工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        // 3.通过工厂对象获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        // 4.获取StudentMapper接口的实现类对象
        // 通过StudentMapper的字节对象 来得到实现类对象
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        // 5.调用实现类对象中的方法
        List<Student> list = mapper.selectAll();
        // 6.处理结果
        for (Student student : list) {
            System.out.println(student);
        }
        // 7.释放资源
        sqlSession.close();
        is.close();
    }
 
    @Test
    public void insert() throws IOException {
        // 1.加载核心配置文件
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
        // 2.获取SqlSession工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        // 3.通过工厂对象获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        // 4.获取StudentMapper接口的实现类对象
        // 通过StudentMapper的字节对象 来得到实现类对象
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        // 5.调用实现类对象中的方法
        Student stu = new Student(9,"张九",90);
        Integer result = mapper.insert(stu);
 
        // 6.处理结果
        System.out.println(result);
        // 7.释放资源
        sqlSession.close();
        is.close();
    }
 
    @Test
    public void update() throws IOException {
        // 1.加载核心配置文件
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
        // 2.获取SqlSession工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        // 3.通过工厂对象获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        // 4.获取StudentMapper接口的实现类对象
        // 通过StudentMapper的字节对象 来得到实现类对象
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        // 5.调用实现类对象中的方法
        Student stu = new Student(9,"张九",1000);
        Integer result = mapper.update(stu);
 
        // 6.处理结果
        System.out.println(result);
        // 7.释放资源
        sqlSession.close();
        is.close();
    }
 
    @Test
    public void delete() throws IOException {
        // 1.加载核心配置文件
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
        // 2.获取SqlSession工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        // 3.通过工厂对象获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        // 4.获取StudentMapper接口的实现类对象
        // 通过StudentMapper的字节对象 来得到实现类对象
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        // 5.调用实现类对象中的方法
        Integer result = mapper.delete(9);
 
        // 6.处理结果
        System.out.println(result);
        // 7.释放资源
        sqlSession.close();
        is.close();
    }
}

随便附上核心配置文件MyBatisConfig.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 核心根标签-->
<configuration>
 
    <!-- 引入数据库连接的配置文件 -->
    <properties resource="jdbc.properties"/>
 
    <!-- 配置log4j -->
    <settings>
        <setting name="logImpl" value="log4j"/>
    </settings>
 
    <!-- 使用通用的配置方式起别名 ,别名默认是类名 -->
    <typeAliases>
        <package name="com.itheima.bean"/>
    </typeAliases>
 
    <!--environments配置数据库环境,环境可以有多个。default属性指定使用的是哪个-->
    <environments default="mysql">
        <!--environment配置数据库环境  id属性唯一标识-->
        <environment id="mysql">
            <!-- transactionManager事务管理。  type属性,采用JDBC默认的事务-->
            <transactionManager type="JDBC"/>
            <!-- dataSource数据源信息   type属性 连接池-->
            <dataSource type="POOLED">
                <!-- property获取数据库连接的配置信息 -->
                <property name="driver" value="${driver}" />
                <property name="url" value="${url}" />
                <property name="username" value="${username}" />
                <property name="password" value="${password}" />
            </dataSource>
        </environment>
    </environments>
 
    <!-- mappers引入映射配置文件 -->
    <mappers>
        <!-- mapper 引入指定的映射配置文件 resource属性指定映射配置文件的名称 -->
        <!-- package 的name属性用来指定包的路径-->
        <package name="com.itheima.mapper"/>
    </mappers>
 
</configuration>
 

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文