【愚公系列】2023年04月 Java教学课程 120-Mybatis(构建sql)


一、构建sql

1.SQL构建对象介绍

  • 对于前面开发相关 SQL 语句都是自己直接拼写的。一些关键字写起来比较麻烦、而且容易出错。
  • MyBatis 给我们提供了 org.apache.ibatis.jdbc.SQL 功能类,专门用于构建 SQL 语句
    在这里插入图片描述

2.查询功能的实现

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

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

    type 属性:生成 SQL 语句功能类对象

    method 属性:指定调用方法

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

3.新增功能的实现

  • 定义功能类并提供获取新增的 SQL 语句的方法。

  • @InsertProvider:生成新增用的 SQL 语句注解。

    type 属性:生成 SQL 语句功能类对象

    method 属性:指定调用方法

//定义方法,返回新增的sql语句
public String getInsert(Student stu) {
    
    
    return new SQL() {
    
    
        {
    
    
            INSERT_INTO("student");
            INTO_VALUES("#{id},#{name},#{age}");
        }
    }.toString();
}
//新增功能
//@Insert("INSERT INTO student VALUES (#{id},#{name},#{age})")
@InsertProvider(type = ReturnSql.class , method = "getInsert")
public abstract Integer insert(Student stu);

4.修改功能的实现

  • 定义功能类并提供获取修改的 SQL 语句的方法。

  • @UpdateProvider:生成修改用的 SQL 语句注解。

    type 属性:生成 SQL 语句功能类对象

    method 属性:指定调用方法

//定义方法,返回修改的sql语句
public String getUpdate(Student stu) {
    
    
    return new SQL() {
    
    
        {
    
    
            UPDATE("student");
            SET("name=#{name}","age=#{age}");
            WHERE("id=#{id}");
        }
    }.toString();
}
//修改功能
//@Update("UPDATE student SET name=#{name},age=#{age} WHERE id=#{id}")
@UpdateProvider(type = ReturnSql.class , method = "getUpdate")
public abstract Integer update(Student stu);

5.删除功能的实现

  • 定义功能类并提供获取删除的 SQL 语句的方法。

  • @DeleteProvider:生成删除用的 SQL 语句注解。

    type 属性:生成 SQL 语句功能类对象

    method 属性:指定调用方法

//定义方法,返回删除的sql语句
public String getDelete(Integer id) {
    
    
    return new SQL() {
    
    
        {
    
    
            DELETE_FROM("student");
            WHERE("id=#{id}");
        }
    }.toString();
}
//删除功能
//@Delete("DELETE FROM student WHERE id=#{id}")
@DeleteProvider(type = ReturnSql.class , method = "getDelete")
public abstract Integer delete(Integer id);

二、完整代码

1.Student类

package com.itheima.bean;

public class Student {
    
    
    private Integer id;
    private String name;
    private Integer age;

    public Student() {
    
    
    }

    public Student(Integer id, String name, Integer age) {
    
    
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public Integer getId() {
    
    
        return id;
    }

    public void setId(Integer id) {
    
    
        this.id = id;
    }

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public Integer getAge() {
    
    
        return age;
    }

    public void setAge(Integer age) {
    
    
        this.age = age;
    }

    @Override
    public String toString() {
    
    
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

2.StudentMapper类

package com.itheima.mapper;

import com.itheima.bean.Student;
import com.itheima.sql.ReturnSql;
import org.apache.ibatis.annotations.DeleteProvider;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.annotations.UpdateProvider;

import java.util.List;

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);
}

3.ReturnSql类

package com.itheima.sql;

import com.itheima.bean.Student;
import org.apache.ibatis.jdbc.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();
    }
}

4.服务类

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

public class Test01 {
    
    

    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.获取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();
    }


    public void insert() 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.获取StudentMapper接口的实现类对象
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);

        //5.调用实现类对象中的方法,接收结果
        Student stu = new Student(4,"赵六",26);
        Integer result = mapper.insert(stu);

        //6.处理结果
        System.out.println(result);

        //7.释放资源
        sqlSession.close();
        is.close();
    }


    public void update() 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.获取StudentMapper接口的实现类对象
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);

        //5.调用实现类对象中的方法,接收结果
        Student stu = new Student(4,"赵六",36);
        Integer result = mapper.update(stu);

        //6.处理结果
        System.out.println(result);

        //7.释放资源
        sqlSession.close();
        is.close();
    }


    public void delete() 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.获取StudentMapper接口的实现类对象
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);

        //5.调用实现类对象中的方法,接收结果
        Integer result = mapper.delete(4);

        //6.处理结果
        System.out.println(result);

        //7.释放资源
        sqlSession.close();
        is.close();
    }
}

5.配置类

<?xml version="1.0" encoding="UTF-8" ?>
<!--MyBatis的DTD约束-->
<!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"></transactionManager>
            <!-- 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>
        <package name="com.itheima"/>
    </mappers>
</configuration>

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/aa2528877987/article/details/129836367