目录
一:MyBatis参数处理
1. 单个简单类型参数
2. Map参数
3. 实体类参数(PoJo类)
4. 多参数
5. @Param注解(命名参数)
一:MyBatis参数处理
接口中方法的参数专栏!
1. 单个简单类型参数
简单类型包括:
①基本数据类型:byte 、short、 int、 long、 float、 double、 char
②对应的包装类型:Byte、 Short、 Integer、 Long、 Float、 Double、 Character
③字符串:String
④util包下的Date:java.util.Date
⑤sql包下的Date:java.sql.Date
(1)数据的准备t_student表
①创建表的结构
②向表中插入数据
(2)把结构搭起来
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.bjpowernode</groupId>
<artifactId>mybatis-007-param</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<!--引入依赖-->
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.10</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.23</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.11</version>
</dependency>
</dependencies>
<!--编译和运行环境-->
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
</project>
①java下mapper包的StudentMapper接口,编写抽象的方法(三兄弟之一)
package com.bjpowernode.mybatis.mapper;
public interface StudentMapper {
}
②java下pojo包的Student类,用来封装对象
package com.bjpowernode.mybatis.pojo;
import java.util.Date;
public class Student {
private Long id;
private String name;
private Integer age;
private Double height;
private Date birth;
private Character sex;
public Student() {
}
public Student(Long id, String name, Integer age, Double height, Date birth, Character sex) {
this.id = id;
this.name = name;
this.age = age;
this.height = height;
this.birth = birth;
this.sex = sex;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Double getHeight() {
return height;
}
public void setHeight(Double height) {
this.height = height;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public Character getSex() {
return sex;
}
public void setSex(Character sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", height=" + height +
", birth=" + birth +
", sex=" + sex +
'}';
}
}
③java下utils包的工具类SqlSessionUtils,用来连接数据库的
package com.bjpowernode.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;
public class SqlSessionUtils {
// 工具类的构造方法一般都是私有化的,防止创建对象
public SqlSessionUtils() {
}
// SqlSessionFactory对象,一个SqlSessionFactory对应一个environment,一个environment对应一个数据库
private static SqlSessionFactory sqlSessionFactory;
static {
try {
sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis-config.xml"));
} catch (IOException e) {
e.printStackTrace();
}
}
// 定义一个方法,获取会话对象
public static SqlSession openSession(){
return sqlSessionFactory.openSession();
}
}
① resources下mapper包的StudetMapper.xml,编写sql语句(三兄弟之二)
<?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.bjpowernode.mybatis.mapper.StudentMapper">
</mapper>
②resource下的jdbc.properties,连接数据库的配置信息
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=123
③resource下的logback.xml,日志配置文件
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
<!--定义⽇志⽂件的存储地址-->
<property name="LOG_HOME" value="/home"/>
<!-- 控制台输出 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化输出:%d表示⽇期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:⽇志消息,%n是换⾏符-->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<!--mybatis log configure-->
<logger name="com.apache.ibatis" level="TRACE"/>
<logger name="java.sql.Connection" level="DEBUG"/>
<logger name="java.sql.Statement" level="DEBUG"/>
<logger name="java.sql.PreparedStatement" level="DEBUG"/>
<!-- ⽇志输出级别,logback⽇志级别包括五个:TRACE < DEBUG < INFO < WARN < ERROR -->
<root level="DEBUG">
<appender-ref ref="STDOUT"/>
<appender-ref ref="FILE"/>
</root>
</configuration>
④resource下的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.bjpowernode.mybatis.pojo"/>
</typeAliases>
<environments default="dev">
<environment id="dev">
<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.bjpowernode.mybatis.mapper"/>
</mappers>
</configuration>
① test包下的java的StudeMapperTest,编写测试方法,用来测试(三兄弟之三)
package com.bjpowernode.mybatis.test;
public class StudentMapperTest {
}
(3)MyBatis参数之单个参数Long类型
需求:根据id查、根据name查、根据birth查、根据sex查
三兄弟之一:StudentMapper接口,编写方法
package com.bjpowernode.mybatis.mapper;
import com.bjpowernode.mybatis.pojo.Student;
import java.util.*;
public interface StudentMapper {
// 当接口中的方法的参数只有一个(单个参数),并且参数的类型是简单类型
List<Student> selectById(Long id);
List<Student> selectByName(String name);
List<Student> selectByBirth(Date birth);
List<Student> selectBySex(Character sex);
}
三兄弟之二:StudentMapper.xml文件,编写sql语句
①实际上select标签还有一个属性paraterType,作用是告诉MyBatis框架,方法的参数类型是什么;也可以省略不写,因为MyBatis框架自身带有类型自动推断机制!
②注意:MyBatis框架实际上也内置了很多别名,可以参考开发手册配置_MyBatis中文网
,例如:java.lang.Long的别名就是long
③注意:实际上#{}里面除了写变量名,也有其它属性,例如:
javaType用来指定类型 、jdbcType用来指定在数据库表中的类型,都可以省略!
④总结:javaType、jdbcType、parameterType这些参数都是可以省略的,加上以后可能效率会更高一些,因为省去了MyBatis去自动类型推断!
<?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.bjpowernode.mybatis.mapper.StudentMapper">
<!--<select id="selectById" resultType="student" parameterType="long">-->
<select id="selectById" resultType="student">
select * from t_student where id = #{id};
</select>
<select id="selectByName" resultType="student">
<!--select * from t_student where name = #{name,javaType=String,jdbcType=VARCHAR};-->
select * from t_student where name = #{name};
</select>
<select id="selectByBirth" resultType="student">
select * from t_student where birth = #{birth};
</select>
<select id="selectBySex" resultType="student">
select * from t_student where sex = #{sex};
</select>
</mapper>
三兄弟之三:StudentMappeTest类,用来编写测试类
package com.bjpowernode.mybatis.test;
import com.bjpowernode.mybatis.mapper.StudentMapper;
import com.bjpowernode.mybatis.pojo.Student;
import com.bjpowernode.mybatis.utils.SqlSessionUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* @Author:朗朗乾坤
* @Package:com.bjpowernode.mybatis.test
* @Project:mybatis
* @name:StudentMapperTest
* @Date:2023/1/4 16:33
*/
public class StudentMapperTest {
@Test
public void testSelectById(){
SqlSession sqlSession = SqlSessionUtils.openSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List<Student> students = mapper.selectById(1L);
students.forEach(student -> System.out.println(student));
sqlSession.close();
}
@Test
public void testSelectByName(){
SqlSession sqlSession = SqlSessionUtils.openSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List<Student> students = mapper.selectByName("张三");
students.forEach(student -> System.out.println(student));
sqlSession.close();
}
@Test
public void testSelectByBirth() throws Exception{
SqlSession sqlSession = SqlSessionUtils.openSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
// 把一个字符串转化为Date类型
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date birth = sdf.parse("1999-06-04");
List<Student> students = mapper.selectByBirth(birth);
students.forEach(student -> System.out.println(student));
sqlSession.close();
}
@Test
public void testSelectBySex(){
SqlSession sqlSession = SqlSessionUtils.openSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
// 把一个char类型转化为包装类Character
Character sex = Character.valueOf('男');
List<Student> students = mapper.selectBySex(sex);
students.forEach(student -> System.out.println(student));
sqlSession.close();
}
}
2. Map参数
三兄弟之一:StudentMapper接口,编写方法
传的参数是一个Map集合:key是String类型,value是具体的值
package com.bjpowernode.mybatis.mapper;
import com.bjpowernode.mybatis.pojo.Student;
import java.util.*;
public interface StudentMapper {
// 保存学生信息,通过Map参数(单个参数),并且参数的类型不是简单类型,是Map集合
int insertStringByMap(Map<String,Object> map);
}
三兄弟之二:StudentMapper.xml文件,编写sql语句
注意:这里参数的变量名必须是Map集合的key!
<?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.bjpowernode.mybatis.mapper.StudentMapper">
<insert id="insertStringByMap">
insert into t_student(id,name,age,height,birth,sex)
values(null,#{name},#{age},#{height},#{birth},#{sex});
</insert>
</mapper>
三兄弟之三:StudentMappeTest类,用来编写测试类
需要创建一个Map集合,然后往这个集合里面存数据,最后把这个集合传进去。
注:一定要手动提交,MyBatis是需要手动提交数据的!
package com.bjpowernode.mybatis.test;
import com.bjpowernode.mybatis.mapper.StudentMapper;
import com.bjpowernode.mybatis.pojo.Student;
import com.bjpowernode.mybatis.utils.SqlSessionUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class StudentMapperTest {
@Test
public void testInsertStringByMap(){
SqlSession sqlSession = SqlSessionUtils.openSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
// 创建一个Map集合,往Map集合当中存数据
Map<String,Object> map = new HashMap<>();
map.put("name","王五");
map.put("age",20);
map.put("height",1.81);
map.put("birth",new Date());
map.put("sex",'男');
mapper.insertStringByMap(map);
sqlSession.commit();
sqlSession.close();
}
}
3. 实体类参数(PoJo类)
所谓的实体类,就是前面我们写的Student类,用来封装对象的
三兄弟之一:StudentMapper接口,编写方法
把Student类作为参数传过去!
package com.bjpowernode.mybatis.mapper;
import com.bjpowernode.mybatis.pojo.Student;
import java.util.*;
public interface StudentMapper {
// 保存学生信息,通过PoJo参数(单个参数),并且参数的类型不是简单类型,是Student类
int insertStudentByPOJO(Student student);
}
三兄弟之二:StudentMapper.xml文件,编写sql语句
注意:#{} ⾥⾯写的是属性名字;这个属性名其本质上是:set/get⽅法名去掉set/get之后全部小写的名字;不仅仅只是属性名,要有对应的setter和getter方法!
<?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.bjpowernode.mybatis.mapper.StudentMapper">
<insert id="insertStudentByPOJO">
insert into t_student(id,name,age,height,birth,sex)
values(null,#{name},#{age},#{height},#{birth},#{sex});
</insert>
</mapper>
三兄弟之三:StudentMappeTest类,用来编写测试类
需要创建一个student对象,调用无参或者有参构造方法都可以,并给每个属性赋上值!最后把这个student对象传过去!
package com.bjpowernode.mybatis.test;
import com.bjpowernode.mybatis.mapper.StudentMapper;
import com.bjpowernode.mybatis.pojo.Student;
import com.bjpowernode.mybatis.utils.SqlSessionUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class StudentMapperTest {
@Test
public void testInsertStudentByPOJO(){
SqlSession sqlSession = SqlSessionUtils.openSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
// 创建一个Student类
Student student = new Student();
// 存放数据
student.setName("赵六");
student.setAge(22);
student.setHeight(1.7);
student.setBirth(new Date());
student.setSex('男');
mapper.insertStudentByPOJO(student);
sqlSession.commit();
sqlSession.close();
}
}
4. 多参数
三兄弟之一:StudentMapper接口,编写方法
所谓的多参数就是根据多个字段进行查询,例如:通过name和sex这两个字段进行查询!
package com.bjpowernode.mybatis.mapper;
import com.bjpowernode.mybatis.pojo.Student;
import java.util.*;
public interface StudentMapper {
// 根据name和sex查询Student信息
List<Student> selectByNameAndSex(String name,Character sex);
}
三兄弟之二:StudentMapper.xml文件,编写sql语句
如果是多个参数的话,MyBatis底层是怎样做的呢?MyBatis框架会自动创建一个Map集合,并且Map集合是这种方式存储参数的:
①第一种:map.put("arg0",name)和map.put("arg1",sex);下标是从0开始
②第二种:map.put("param1",name)和map.put("param2",sex);下标从1开始
注意:也可以两个参数混合着用;对于低版本的MyBatis中,使用的是:#{0}和#{1}形式...
<?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.bjpowernode.mybatis.mapper.StudentMapper">
<select id="selectByNameAndSex" resultType="student">
select * from t_student
<!--where name = #{arg0} and sex = #{arg1};-->
<!--where name = #{arg0} and sex = #{param2};-->
where name = #{param1} and sex = #{param2};
</select>
</mapper>
三兄弟之三:StudentMappeTest类,用来编写测试类
按照变量对应的类型,进行传参!
package com.bjpowernode.mybatis.test;
import com.bjpowernode.mybatis.mapper.StudentMapper;
import com.bjpowernode.mybatis.pojo.Student;
import com.bjpowernode.mybatis.utils.SqlSessionUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class StudentMapperTest {
@Test
public void testSelectByNameAndSex(){
SqlSession sqlSession = SqlSessionUtils.openSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List<Student> students = mapper.selectByNameAndSex("张三", '男');
students.forEach(student -> System.out.println(student));
sqlSession.close();
}
}
5. @Param注解(命名参数)
可以不使⽤arg0、arg1, param1、param2吗?这个map集合的key我们可以⾃定义当然。使⽤ @Param注解即可,这样可以增强可读性。
三兄弟之一:StudentMapper接口,编写方法
编写sql语句时,使用@Param注解的方式对参数进行重命名,其中属性名是value可以省略;重命名后MyBatis框架底层的实现原理:map.put("name",name),map.put("sex",sex)
package com.bjpowernode.mybatis.mapper;
import com.bjpowernode.mybatis.pojo.Student;
import org.apache.ibatis.annotations.Param;
import java.util.*;
public interface StudentMapper {
// 使用@Param注解的方式重命名
List<Student> selectByNameAndSexParam(@Param(value = "name") String name,
@Param("sex") Character sex);
}
三兄弟之二:StudentMapper.xml文件,编写sql语句
使用@Param注解重名后,只有arg0、arg1这种方式失效了,还是有两种存储方式:
第一种:map.put("name",name)和map.put("sex",sex);使用自己定义的名字作为key
第二种:map.put("param1",name)和map.put("param2",sex);这种方式还是能使用
<?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.bjpowernode.mybatis.mapper.StudentMapper">
<select id="selectByNameAndSexParam" resultType="student">
select * from t_student
<!--where name = #{param1} and sex = #{param2};-->
where name = #{name} and sex = #{sex};
</select>
</mapper>
三兄弟之三:StudentMappeTest类,用来编写测试类
package com.bjpowernode.mybatis.test;
import com.bjpowernode.mybatis.mapper.StudentMapper;
import com.bjpowernode.mybatis.pojo.Student;
import com.bjpowernode.mybatis.utils.SqlSessionUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class StudentMapperTest {
@Test
public void testSelectByNameAndSexParam(){
SqlSession sqlSession = SqlSessionUtils.openSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List<Student> students = mapper.selectByNameAndSexParam("张三", '男');
students.forEach(student -> System.out.println(student));
sqlSession.close();
}
}