mybatis 中的#{} ${}
#{} 在mybatis中,底层是用PreparedStatement方法,调用pojo类的set() 来赋值的。MyBatis在处理#{ }时,它会将sql中的#{ }替换为?
优点:防止SQL注入。
缺点:执行效率低。
${} 在mybatis中。底层是用字符串拼接实现的。
优点:执行效率高
缺点:不能防止SQL注入。
注意:${} 比 #{} 快很多,当数据量很高时,SQL查询使用 #{} 会导致数据库cpu飙高、查询超时。因此要慎重使用 #{}
扩展:spring el表达式的#{} ${}
${} 一般是类@PropertySource(value=“classpath:user.properties”) 加上成员变量@Value(“name”),配合user.properties配置文件使用
这个很常用,就不举例了。
#{} 一般是一个pojo类注入另一个pojo类的参数,这里要注意被注入的类的注解
@Component
@Data
public class Pet {
@Value("猫")
private String species;
@Value("22")
private Integer age;
}
@Component
@Data
@NoArgsConstructor
@AllArgsConstructor
//@ConfigurationProperties(prefix = "user")
//@PropertySource(value="classpath:user.properties")
public class User {
@Value("#{pet.age}")
private Integer id;
@Value("#{pet.species}")
private String name;
private Integer age;
private String email;
private String username;
private String password;
private Date birthday;
}