4. 占位符

zhanglei 2022年06月02日 400次浏览

#{} 的底层是preparedstatement,推荐使用

${} 的底层是statement,会采用字符串拼接的方式,会sql注入

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"/>
            <!--配置数据源:创建Connection对象-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url"
                          value="jdbc:mysql://localhost:3306/bjpowernode?useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="admin"/>
            </dataSource>
        </environment>
    </environments>
    <!--指定其他mapper文件的位置
    找到其他mapper文件的目的是找到sql语句

    使用注意:
        resource="mapper.文件的路径,用/分割"-->

    <mappers>
        <mapper resource="Dao/StudentDao.xml"/>
    </mappers>
</configuration>

StudentDao

package Dao;

import domain.Student;

public interface StudentDao {
    Student selectById(Integer i);

    Student selectByName(String name);
}

StudentDao.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="Dao.StudentDao">

    <!--
        mapper是根标签
        mapper里面可以写<insert>,<update>,<select>等标签
            标签的id属性:正常是需要重写的方法名
            标签的resultType属性:将数据赋值给哪个类型的Java对象
        标签内部都有同名的sql语句
    -->


    <!--
        #{}底层是PreparedStatement:
            推荐使用!
        ${}底层是Statement:
            效率低,占位符的值使用的是字符串拼接的方式,会将传递值的sql关键字也加入编译,曲解了原本sql语句的含义(sql注入)
    -->
    <select id="selectById" resultType="domain.Student">
        select id,name,email,age from student where id=#{id}
    </select>


    <select id="selectByName" resultType="domain.Student">
        select id,name,email,age from student where name=${name}
    </select>
</mapper>

实体类Student

package domain;

public class Student {
    private Integer id;
    private String name;
    private String email;
    private Integer 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 String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "学生实体{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", email='" + email + '\'' +
                ", age=" + age +
                '}';
    }
}

工具类MyBatisUtil

package util;

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

public class MyBatisUtil {
    //获得SqlSessionFactory
    public static SqlSessionFactory sqlSessionFactory;
    static{
        String config="mybatis-config.xml ";
        try {
            InputStream inputStream = Resources.getResourceAsStream(config);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    //获得sqlSession
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}

测试类MyTest

import Dao.StudentDao;
import domain.Student;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import util.MyBatisUtil;

public class MyTest {
    //测试占位符#{}
    @Test
    public void testSelectById(){
        //获取sqlSession
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        //获取dao实现类
        StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        //调用接口中的方法
        Student student = mapper.selectById(1);
        System.out.println(student);
        sqlSession.close();
    }

    //测试占位符${}
    @Test
    public void testSelectByName(){
        //获取sqlSession
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        //获取dao实现类
        StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        //调用接口中的方法
        //重要!!!${}采用字符串拼接的方式!!传字符串的时候要加‘’
        Student student = mapper.selectByName("'张磊'");
        System.out.println(student);
        sqlSession.close();
    }
}

测试结果

//testSelectById
学生实体{id=1, name='张磊', email='zl@163.com', age=23}

//testSelectByName
学生实体{id=1, name='张磊', email='zl@163.com', age=23}