5、Mybatis之获取参数值
5.1、创建新module
5.1.1、右击SSM文件夹,创建新module
5.1.2、选择maven
5.1.3、配置module名称和路径
5.1.4、module初始状态
5.1.5、复制打包方式和依赖
<?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>org.rain</groupId>
<artifactId>mybatis_parameter</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<!-- Mybatis核心 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<!-- junit测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- MySQL驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
<!-- log4j日志 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
</project>
5.1.6、复制配置文件
- jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
- 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>
5.1.7、复制并修改Mybatis核心配置文件
注意:别名包值和映射文件包值,目前是悬空状态
<?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=""/>
</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=""/>
</mappers>
</configuration>
5.1.8、创建mapper接口和映射文件
- mapper接口
- 映射文件目录
注意目录分隔符是“/”,而且路径和mapper接口路径一致
- 映射文件
注意:映射文件名称要和mapper接口名称一致,映射文件mapper标签的namespace属性值是对应mapper接口的全限定名
<?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="org.rain.mybatis.mapper.UserMapper">
</mapper>
5.1.9、创建实体类
++++++++++++++++++++++++++++++++分割线++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++分割线++++++++++++++++++++++++++++++++
package org.rain.mybatis.pojo;
/**
* @author liaojy
* @date 2023/5/22 - 23:56
*/
public class User {
private Integer id;
private String username;
private String password;
private Integer age;
private String gender;
private String email;
public User() {
}
public User(Integer id, String username, String password, Integer age, String gender, String email) {
this.id = id;
this.username = username;
this.password = password;
this.age = age;
this.gender = gender;
this.email = email;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", age=" + age +
", gender='" + gender + '\'' +
", email='" + email + '\'' +
'}';
}
}
5.1.10、更新核心配置文件的包引用
5.1.11、创建SqlSession工具类
package org.rain.mybatis.utils;
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;
/**
* @author liaojy
* @date 2023/5/19 - 7:41
*/
public class SqlSessionUtils {
public static SqlSession getSqlSession(){
SqlSession sqlSession = null;
try {
//读取MyBatis核心配置文件的输入流
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
//创建SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//通过核心配置文件所对应的字节输入流创建工厂类SqlSessionFactory,用于生产SqlSession对象
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
//创建自动提交事务的SqlSession对象
sqlSession = sqlSessionFactory.openSession(true);
} catch (IOException e) {
e.printStackTrace();
}
return sqlSession;
}
}
5.1.12、创建测试类
5.2、单个字面量类型的参数
字面量:基本数据类型及其包装类,和字符串都属于字面量
5.2.1、接口方法
package org.rain.mybatis.mapper;
import org.rain.mybatis.pojo.User;
/**
* @author liaojy
* @date 2023/5/22 - 23:53
*/
public interface UserMapper {
User getUserByUsername(String username);
}
5.2.2、映射文件
实际上,mybatis只知道方法传的参数值,而不知道参数名,所以可以用任意名获取参数值,如${abc};
但为了可读性,推荐使用方法的参数名${username}。
<!--User getUserByUsername(String username);-->
<select id="getUserByUsername" resultType="User">
select * from t_user where username = #{username}
</select>
5.2.3、测试方法
注意:在这个示例中,数据库中username字段的值只能有一个“root”
package org.rain.mybatis.test;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import org.rain.mybatis.mapper.UserMapper;
import org.rain.mybatis.pojo.User;
import org.rain.mybatis.utils.SqlSessionUtils;
/**
* @author liaojy
* @date 2023/5/23 - 7:54
*/
public class ParameterTest {
@Test
public void testGerUserByUsername(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.getUserByUsername("root");
System.out.println(user);
sqlSession.close();
}
}
5.2.4、执行效果
从控制台的sql日志可知,#{}的本质是占位符赋值
5.2.5、字符串赋值
从上图控制台的sql日志可知,${}的本质是字符串拼接,会存在字符串参数值的单引号问题;解决方法见下图,手动加单引号
5.3、多个字面量类型的参数
5.3.1、接口方法
User checkLogin(String username,String password);
5.3.2、映射文件
注意:当mapper接口方法的参数为多个字面量时,mybatis会以两种map集合的形式存储参数值;
一种map集合的键为arg0、arg1等,另一种map集合的键为param1、param2等;
<!--User checkLogin(String username,String password);-->
<select id="checkLogin" resultType="User">
select * from t_user where username = #{arg0} and password = #{arg1}
</select>
5.3.3、测试方法
@Test
public void testCheckLogin(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.checkLogin("root","123");
System.out.println(user);
sqlSession.close();
}
5.3.4、执行效果
5.3.5、字符串拼接
5.4、map集合类型的参数
5.4.1、接口方法
User checkLoginByMap(Map<String,Object> map);
5.4.2、测试方法
@Test
public void testCheckLoginByMap(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
Map<String,Object> map = new HashMap<String, Object>();
map.put("username","root");
map.put("password","123");
User user = userMapper.checkLoginByMap(map);
System.out.println(user);
sqlSession.close();
}
5.4.3、映射文件
注意:可以自定义map集合,然后通过自定义map集合中的键来获取参数值
<!--User checkLoginByMap(Map<String,Object> map);-->
<select id="checkLoginByMap" resultType="User">
select * from t_user where username = #{username} and password = #{password}
</select>
5.4.4、执行效果
5.5、实体类类型的参数
5.5.1、接口方法
void insertUser(User user);
5.5.2、测试方法
@Test
public void testInsertUser(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
Map<String,Object> map = new HashMap<String, Object>();
User user = new User();
user.setUsername("zhangsan");
user.setPassword("123");
user.setAge(55);
user.setGender("男");
user.setEmail("123@qq.com");
userMapper.insertUser(user);
sqlSession.close();
}
5.5.3、映射文件
通过用${}和#{}访问实体类对象中的属性名来获取对应的属性值;
注意:属性名是实体类的getter或setter方法去掉get或set之后的首字母小写部分,和成员变量无关
<!--void insertUser(User user);-->
<insert id="insertUser">
insert into t_user values (null ,#{username},#{password},#{age},#{gender},#{email});
</insert>
5.5.4、执行效果
+++++++++++++++++++++++++++++分割线+++++++++++++++++++++++++++++
5.6、使用@Param标识参数
5.6.1、接口方法
用@Param注解标识mapper接口中的方法参数,可以自定义mybatis中map集合的键;
这样,只需要通过${}或#{}访问map集合的自定义键就可以获取对应的参数值
User checkLoginByParam(@Param("username") String username, @Param("password") String password);
5.6.2、映射文件
<!--User checkLoginByParam(@Param("username") String username, @Param("param") String password);-->
<select id="checkLoginByParam" resultType="User">
select * from t_user where username = #{username} and password = #{password}
</select>
5.6.3、测试方法
@Test
public void testCheckLoginByParam(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.checkLoginByParam("root","123");
System.out.println(user);
sqlSession.close();
}
5.6.4、执行效果
本文来自博客园,作者:Javaer1995,转载请注明原文链接:https://www.cnblogs.com/Javaer1995/p/17419649.html