MyBatis获取参数值的两种方式:${} 和#{}
${} 的本质就是字符串拼接,#{} 的本质就是占位符赋值
${} 使用字符串拼接的方式拼接sql,若为字符串类型或日期类型的字段进行赋值时,需要手动加单引号;但是#{} 使用占位符赋值的方式拼接sql,此时为字符串类型或日期类型的字段进行赋值时,可以自动添加单引号
${} 会产生SQL注入,#{} 不会产生SQL注入问题
1、准备工作
新建一个Maven项目,在pom.xml 导入相关依赖
<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>
<groupId>com.mybatis</groupId>
<artifactId>MyBatis_demo2</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.3</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.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
<?xml version="1.0" encoding="UTF-8" ?>
<!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
<?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>
<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
<?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="com.mybatis.mapper.ParameterMapper">
</mapper>
创建测试类,路径在src/test/java/com/mybatis/test/ParameterMapperTest.java
package com.mybatis.test;
public class ParameterMapperTest {
}
2、单个字面量类型的参数
若mapper接口中的方法参数为单个的字面量类型
此时可以使用${} 和#{} 以任意的名称获取参数的值,注意${} 需要手动加单引号
a>在ParameterMapper 接口添加方法
User getUserByUserName(String userName);
b>在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>
c>在ParameterMapperTest 添加测试方法
@Test
public void testGetUserByUserName(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
User user = mapper.getUserByUserName("柳丰");
System.out.println(user);
}
d>运行结果
3、多个字面量类型的参数
若mapper接口中的方法参数为多个时
此时MyBatis会自动将这些参数放在一个map集合中,以arg0,arg1…为键,以参数为值;以 param1,param2…为键,以参数为值
因此只需要通过${} 和#{} 访问map集合的键就可以获取相对应的值,注意${} 需要手动加单引号
a>在ParameterMapper 接口添加方法
User checkLogin(String username,String password);
b>在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可以混用
c>在ParameterMapperTest 添加测试方法
@Test
public void testCheckLogin(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
User user = mapper.checkLogin("高敏","333");
System.out.println(user);
}
d>运行结果
4、map集合类型的参数
若mapper接口中的方法需要的参数为多个时
此时可以手动创建map集合,将这些数据放在map中,只需要通过${} 和#{} 访问map集合的键就可以获取相对应的值,注意${} 需要手动加单引号
a>在ParameterMapper 接口添加方法
User checkLoginByMap(Map<String,Object> map);
b>在ParameterMapper 映射添加查询
<select id="checkLoginByMap" resultType="User">
select * from t_user where username=#{username} and password=#{password}
</select>
c>在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);
}
d>运行结果
5、实体类类型的参数
若mapper接口中的方法参数为实体类对象时
此时可以使用${} 和#{} ,通过访问实体类对象中的属性名获取属性值,注意${} 需要手动加单引号
a>在ParameterMapper 接口添加方法
int insertUser(User user);
b>在ParameterMapper 映射添加插入
<insert id="insertUser">
insert into t_user values(#{id},#{username},#{password},#{age},#{sex},#{email})
</insert>
要求实体类中的属性必须要有get和set方法,此处使用Lombok则可以自动生成
c>在ParameterMapperTest 添加测试方法
@Test
public void testInsertUser() {
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
int result = mapper.insertUser(new User(null,"张飞","777",26,"男","ttt@gmail.com"));
System.out.println(result);
}
id在数据库中自增,故此处设为null
d>运行结果
查看数据库
6、使用@Param标识参数
可以通过@Param注解标识mapper接口中的方法参数
此时,会将这些参数放在map集合中,以@Param注解的value属性值为键,以参数为值;以 param1,param2…为键,以参数为值;只需要通过${} 和#{} 访问map集合的键就可以获取相对应的值, 注意${} 需要手动加单引号
a>在ParameterMapper 接口添加方法
User checkLoginByParam(@Param("username")String username, @Param("password") String password);
b>在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>
c>在ParameterMapperTest 添加测试方法
@Test
public void testCheckLoginByMap(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
User user = mapper.checkLoginByParam("张飞","777");
System.out.println(user);
}
d>运行结果
|