之前我们介绍了mybatis中参数的使用,本篇我们在此基础上介绍Mybatis中使用参数时$与#的区别。
如果您对mybatis中参数的使用不太了解,建议您先进行了解后再阅读本篇,可以参考:
Mybatis参数(parameterType)https://blog.csdn.net/m1729339749/article/details/132548838
在cn.horse.demo下创建UserInfo、UserInfoQuery类
UserInfo类:
- package cn.horse.demo;
-
- public class UserInfo {
- private Integer id;
- private String name;
- private Integer age;
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public Integer getId() {
- return id;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getName() {
- return name;
- }
-
- public void setAge(Integer age) {
- this.age = age;
- }
-
- public Integer getAge() {
- return age;
- }
-
- @Override
- public String toString() {
- StringBuilder stringBuilder = new StringBuilder();
- stringBuilder.append('{');
- stringBuilder.append("id: " + this.id);
- stringBuilder.append(", ");
- stringBuilder.append("name: " + this.name);
- stringBuilder.append(", ");
- stringBuilder.append("age: " + this.age);
- stringBuilder.append('}');
- return stringBuilder.toString();
- }
- }
UserInfoQuery类:
- package cn.horse.demo;
-
- public class UserInfoQuery {
-
- private Integer startAge;
- private Integer endAge;
- private Integer start;
- private Integer limit;
-
- public void setStartAge(Integer startAge) {
- this.startAge = startAge;
- }
-
- public Integer getStartAge() {
- return startAge;
- }
-
- public void setEndAge(Integer endAge) {
- this.endAge = endAge;
- }
-
- public Integer getEndAge() {
- return endAge;
- }
-
- public void setStart(Integer start) {
- this.start = start;
- }
-
- public Integer getStart() {
- return start;
- }
-
- public void setLimit(Integer limit) {
- this.limit = limit;
- }
-
- public Integer getLimit() {
- return limit;
- }
- }
在cn.horse.demo下创建UserInfoMapper接口
UserInfoMapper接口:
- package cn.horse.demo;
-
- import org.apache.ibatis.annotations.*;
-
- import java.util.List;
-
- public interface UserInfoMapper {
-
- List
find(@Param("query") UserInfoQuery query); - }
在resources下创建cn/horse/demo目录,并在此目录下创建UserInfoMapper.xml配置文件
UserInfoMapper.xml配置:
- "1.0" encoding="UTF-8" ?>
- mapper
- PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
- "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <mapper namespace="cn.horse.demo.UserInfoMapper">
-
- <resultMap id="userInfoMap" type="cn.horse.demo.UserInfo">
- <result column="ID" property="id" />
- <result column="USERNAME" property="name"/>
- <result column="AGE" property="age"/>
- resultMap>
-
- <select id="find" parameterType="cn.horse.demo.UserInfoQuery" resultMap="userInfoMap">
- SELECT
- ID,
- USERNAME,
- AGE
- FROM ${userTableName}
- <where>
- <if test="null != query.startAge">
- AND AGE >= #{query.startAge}
- if>
- <if test="null != query.endAge">
- AND AGE <= #{query.endAge}
- if>
- where>
- LIMIT ${query.start}, ${query.limit}
- select>
- mapper>
配置中我们使用${userTableName}获取用户表名称,使用${query.start}、${query.limit}获取分页信息,使用#{query.startAge}、#{query.endAge}获取查询条件信息
在resources下新建mybatis-config.xml配置文件,并引入UserInfoMapper映射器。
- "1.0" encoding="UTF-8" ?>
- configuration
- PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-config.dtd">
- <configuration>
-
- <properties>
- <property name="userTableName" value="T_USER"/>
- properties>
-
- <settings>
- <setting name="logImpl" value="JDK_LOGGING"/>
- settings>
-
- <environments default="development">
- <environment id="development">
- <transactionManager type="JDBC"/>
- <dataSource type="POOLED">
- <property name="driver" value="org.gjt.mm.mysql.Driver"/>
- <property name="url" value="jdbc:mysql://localhost:3306/demo?useUnicode=true&useSSL=false&characterEncoding=utf8&allowMultiQueries=true"/>
- <property name="username" value="root"/>
- <property name="password" value="horse"/>
- dataSource>
- environment>
- environments>
-
- <mappers>
- <mapper class="cn.horse.demo.UserInfoMapper" />
- mappers>
- configuration>
这里,我们在mybatis中定义了属性名为userTableName属性值为T_USER的属性,并使用mapper引入了映射器。
这里我们直接使用脚本初始化数据库中的数据
- -- 如果数据库不存在则创建数据库
- CREATE DATABASE IF NOT EXISTS demo DEFAULT CHARSET utf8;
- -- 切换数据库
- USE demo;
- -- 创建用户表
- CREATE TABLE IF NOT EXISTS T_USER(
- ID INT PRIMARY KEY,
- USERNAME VARCHAR(32) NOT NULL,
- AGE INT NOT NULL
- );
- -- 插入用户数据
- INSERT INTO T_USER(ID, USERNAME, AGE)
- VALUES(1, '张三', 20),(2, '李四', 22),(3, '王五', 24);
创建了一个名称为demo的数据库;并在库里创建了名称为T_USER的用户表并向表中插入了数据
在cn.horse.demo包下新建SqlSessionUtils工具类
- package cn.horse.demo;
-
- 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.Objects;
-
- public class SqlSessionUtils {
-
- private static final SqlSessionFactory sqlSessionFactory;
- static {
- // 读取mybatis配置文件
- InputStream inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("mybatis-config.xml");
- // 根据配置创建SqlSession工厂
- sqlSessionFactory = new SqlSessionFactoryBuilder()
- .build(inputStream);
- }
-
- /**
- * 开启会话
- * @return
- */
- public static SqlSession openSession() {
- return sqlSessionFactory.openSession();
- }
-
- /**
- * 关闭会话
- * @param sqlSession
- */
- public static void closeSession(SqlSession sqlSession) {
- if(Objects.nonNull(sqlSession)) {
- sqlSession.close();
- }
- }
- }
在resources的目录下新建logging.properties配置文件
- handlers=java.util.logging.ConsoleHandler
- .level=INFO
-
- cn.horse.demo.level=FINER
- java.util.logging.ConsoleHandler.level=ALL
- java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter
- java.util.logging.SimpleFormatter.format=%1$tY-%1$tm-%1$td %1$tT.%1$tL %4$s %3$s - %5$s%6$s%n
在cn.horse.demo下创建JdkLogConfig类
JdkLogConfig类:
- package cn.horse.demo;
-
- import java.io.IOException;
- import java.io.InputStream;
- import java.util.logging.LogManager;
-
- public class JdkLogConfig {
-
- public JdkLogConfig() {
- try {
- InputStream inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("logging.properties");
- LogManager.getLogManager().readConfiguration(inputStream);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- }
- package cn.horse.demo;
-
- import org.apache.ibatis.session.SqlSession;
-
- import java.util.List;
- import java.util.function.Consumer;
- import java.util.logging.Logger;
-
- public class Main {
-
- private static final Logger LOGGER;
-
- static {
- // 引入JDK日志配置
- System.setProperty("java.util.logging.config.class", "cn.horse.demo.JdkLogConfig");
- LOGGER = Logger.getLogger("cn.horse.demo.Main");
- }
-
- public static void main(String[] args) throws InterruptedException {
-
- execute((UserInfoMapper userInfoMapper) -> {
- UserInfoQuery query = new UserInfoQuery();
- query.setStartAge(0);
- query.setEndAge(24);
- query.setStart(0);
- query.setLimit(1);
- List
userInfoList = userInfoMapper.find(query); - for (UserInfo userInfo: userInfoList) {
- LOGGER.info(userInfo.toString());
- }
- });
- }
-
- private static void execute(Consumer
function) { - SqlSession sqlSession = null;
- try {
- sqlSession = SqlSessionUtils.openSession();
- function.accept(sqlSession.getMapper(UserInfoMapper.class));
- sqlSession.commit();
- } finally {
- SqlSessionUtils.closeSession(sqlSession);
- }
- }
- }
execute方法用于执行操作,方法中使用sqlSession.getMapper方法获取映射器对象,然后将映射器对象具体的执行操作委托给了Consumer对象。
执行后的结果如下:
现象:
从日志打印的SQL语句中可以看出参数${userTableName}被替换成了T_USER,${query.start}被替换成了0,${query.limit}被替换成了1;而#{query.startAge}、#{query.endAge}被替换成了?;
结论:
使用$获取参数时在执行SQL语句时参数会被替换,使用$获取的参数可以是在mybatis中定义的属性。
使用#获取参数时在执行SQL语句时会进行预处理以避免SQL注入。