MyBatis获取参数值的两种方式:${}
和#{}
${}
的本质就是字符串拼接,#{}
的本质就是占位符赋值
${}
使用字符串拼接的方式拼接sql,若为字符串类型或日期类型的字段进行赋值时,需要手动加单引号;但是#{}
使用占位符赋值的方式拼接sql,此时为字符串类型或日期类型的字段进行赋值时,可以自动添加单引号
${}
会产生SQL注入,#{}
不会产生SQL注入问题
新建一个Maven项目,在pom.xml
导入相关依赖
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.mybatisgroupId>
<artifactId>MyBatis_demo2artifactId>
<version>1.0-SNAPSHOTversion>
<packaging>jarpackaging>
<dependencies>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.7version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>testscope>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.3version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.22version>
dependency>
dependencies>
<properties>
<maven.compiler.source>8maven.compiler.source>
<maven.compiler.target>8maven.compiler.target>
properties>
project>
创建数据库,名为mybatis
,并在该库下创表t_user
,简单插入几条数据
在src/main/resources
下导入如下三个文件:
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8
jdbc.username=root
jdbc.password=123456
log4j.xml
DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Encoding" value="UTF-8" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS}
%m (%F:%L) \n" />
layout>
appender>
<logger name="java.sql">
<level value="debug" />
logger>
<logger name="org.apache.ibatis">
<level value="info" />
logger>
<root>
<level value="debug" />
<appender-ref ref="STDOUT" />
root>
log4j:configuration>
mybatis-config.xml
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="jdbc.properties"/>
<typeAliases>
<package name="com.mybatis.pojo"/>
typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
dataSource>
environment>
environments>
<mappers>
<package name="com.mybatis.mapper"/>
mappers>
configuration>
创建pojo实体类,路径在src/main/java/com/mybatis/pojo/User.java
package com.mybatis.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.experimental.Accessors;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@ToString
public class User {
// 指定字段名和属性值一致(反射)
private Integer id;
private String username;
private String password;
private Integer age;
private String sex;
private String email;
}
创建SqlSession工具类,路径在src/main/java/com/mybatis/util/SqlSessionUtil.java
package com.mybatis.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 SqlSessionUtil {
public static SqlSession getSqlSession() {
SqlSession sqlSession = null;
try {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
sqlSession = factory.openSession(true);
} catch (IOException e) {
e.printStackTrace();
}
return sqlSession;
}
}
创建mapper接口,路径在src/main/java/com/mybatis/mapper/ParameterMapper.java
package com.mybatis.mapper;
import com.mybatis.pojo.User;
public interface ParameterMapper {
// 接口
}
创建mapper映射,路径在src/main/resources/com/mybatis/mapper/ParameterMapper.xml
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis.mapper.ParameterMapper">
mapper>
创建测试类,路径在src/test/java/com/mybatis/test/ParameterMapperTest.java
package com.mybatis.test;
public class ParameterMapperTest {
// 待测试方法
}
若mapper接口中的方法参数为单个的字面量类型
此时可以使用${}
和#{}
以任意的名称获取参数的值,注意${}
需要手动加单引号
ParameterMapper
接口添加方法/**
* 根据用户名查询用户信息
* @param userName
* @return
*/
User getUserByUserName(String userName);
ParameterMapper
映射添加查询<select id="getUserByUserName" resultType="User">
select * from t_user where username=#{username}
select>
若使用${},则查询语句为:
<select id="getUserByUserName" resultType="User"> select * from t_user where username='${value}' select>
ParameterMapperTest
添加测试方法@Test
public void testGetUserByUserName(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
User user = mapper.getUserByUserName("柳丰");
System.out.println(user);
}
若mapper接口中的方法参数为多个时
此时MyBatis会自动将这些参数放在一个map集合中,以arg0,arg1…为键,以参数为值;以 param1,param2…为键,以参数为值
因此只需要通过${}
和#{}
访问map集合的键就可以获取相对应的值,注意${}
需要手动加单引号
ParameterMapper
接口添加方法/**
* 验证登录
* @param username
* @param password
* @return
*/
User checkLogin(String username,String password);
ParameterMapper
映射添加查询<select id="checkLogin" resultType="User">
select * from t_user where username=#{arg0} and password=#{arg1}
select>
第二种写法:
<select id="checkLogin" resultType="User"> select * from t_user where username=#{param1} and password=#{param2} select>
注意:arg和param可以混用
ParameterMapperTest
添加测试方法@Test
public void testCheckLogin(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
User user = mapper.checkLogin("高敏","333");
System.out.println(user);
}
若mapper接口中的方法需要的参数为多个时
此时可以手动创建map集合,将这些数据放在map中,只需要通过${}
和#{}
访问map集合的键就可以获取相对应的值,注意${}
需要手动加单引号
ParameterMapper
接口添加方法/**
* 验证登录(参数为Map)
* @param map
* @return
*/
User checkLoginByMap(Map<String,Object> map);
ParameterMapper
映射添加查询<select id="checkLoginByMap" resultType="User">
select * from t_user where username=#{username} and password=#{password}
select>
ParameterMapperTest
添加测试方法@Test
public void testCheckLoginByMap(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
Map<String, Object> map = new HashMap<>();
map.put("username","高敏");
map.put("password","333");
User user = mapper.checkLoginByMap(map);
System.out.println(user);
}
若mapper接口中的方法参数为实体类对象时
此时可以使用${}
和#{}
,通过访问实体类对象中的属性名获取属性值,注意${}
需要手动加单引号
ParameterMapper
接口添加方法/**
* 添加用户信息
* @param user
* @return
*/
int insertUser(User user);
ParameterMapper
映射添加插入<insert id="insertUser">
insert into t_user values(#{id},#{username},#{password},#{age},#{sex},#{email})
insert>
要求实体类中的属性必须要有get和set方法,此处使用Lombok则可以自动生成
ParameterMapperTest
添加测试方法@Test
public void testInsertUser() {
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
int result = mapper.insertUser(new User(null,"张飞","777",26,"男","[email protected]"));
System.out.println(result);
}
id在数据库中自增,故此处设为null
可以通过@Param注解标识mapper接口中的方法参数;除了实体类型和Map集合,其它类型推荐都使用@Param来标识参数
此时,会将这些参数放在map集合中,以@Param注解的value属性值为键,以参数为值;以 param1,param2…为键,以参数为值;只需要通过${}
和#{}
访问map集合的键就可以获取相对应的值, 注意${}
需要手动加单引号
ParameterMapper
接口添加方法/**
* 验证登录(使用@Param)
* @param username
* @param password
* @return
*/
User checkLoginByParam(@Param("username")String username, @Param("password") String password);
ParameterMapper
映射添加查询<select id="checkLoginByParam" resultType="User">
select * from t_user where username=#{username} and password=#{password}
select>
第二种写法:
<select id="checkLoginByParam" resultType="User"> select * from t_user where username=#{param1} and password=#{param2} select>
ParameterMapperTest
添加测试方法@Test
public void testCheckLoginByMap(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
User user = mapper.checkLoginByParam("张飞","777");
System.out.println(user);
}
List或数组参数,也是通过@Param来标识,参考动态SQL–批量删除或添加