mybatis基础(2)

发布时间 2023-12-19 05:56:59作者: 小喵喵_27

配置式使用mybatis,可以三步走:

  • 读取配置文件,即mybatis-config.xml
  • 通过配置文件来创建SqlSessionFactory
  • 新建SqlSession来执行sql

mybatis 提供了注解和XML两种方式来连接接口方法和sql语句

如果单独使用mybatis ,那么mapper接口必须和.xml配置文件在同一个包中,但是如果使用spring等工具可以不必接收此限制

参数符号

若以#{}作为参数符号,MyBatis则会创建一个预处理语句(PreparedStatement),它会被处理成 ?。如果你不希望使用预处理,那么可以使用${}参数符号,MyBatis 会以字符串的形式进行拼接

In MyBatis, #{} and ${} are two different syntaxes used in SQL statements, and they serve different purposes:

  1. #{} (Parameter Substitution):

    • #{} is used for parameter substitution in prepared statements. It helps prevent SQL injection by automatically handling escaping and quoting of parameters.

    • MyBatis treats values placed inside #{} as bind parameters and automatically applies proper escaping and formatting based on the parameter type.

    • Example:

      xml
      <!-- Using #{parameter} for parameter substitution --> SELECT * FROM users WHERE id = #{userId}
    • In Java code, you would then provide the actual value for userId when executing the SQL statement.

  2. ${} (String Substitution):

    • ${} is used for string substitution in SQL statements. It directly replaces the variable or expression with its string representation.

    • Unlike #{}, ${} does not provide protection against SQL injection because it directly inserts the value into the SQL string without any formatting.

    • Example:

      xml
      <!-- Using ${parameter} for string substitution --> SELECT * FROM users WHERE id = ${userId}
    • In this case, the value of userId will be directly inserted into the SQL string as a string.

Key Differences:

  • Security:

    • #{} is more secure against SQL injection because it handles parameter formatting.
    • ${} is less secure since it directly inserts the string representation of the variable.
  • Prepared Statements:

    • #{} is typically used in prepared statements, where MyBatis handles parameter formatting.
    • ${} is used for string interpolation and is suitable when you want to directly insert a string representation.
  • Data Types:

    • #{} is aware of the data type of the parameter and applies appropriate formatting.
    • ${} does not consider the data type and directly inserts the string representation.
  • Quoting and Escaping:

    • #{} automatically quotes and escapes values, making it suitable for most scenarios.
    • ${} does not quote or escape values, so it's important to ensure that values are properly formatted before using ${} to prevent SQL errors.

In general, it's recommended to use #{} for most cases, especially when dealing with user input or dynamic values, to prevent SQL injection. Use ${} when you need to directly substitute a string and are certain about the safety of the value being inserted.