> 文章列表 > mybatis模糊查询以及结果封装详解

mybatis模糊查询以及结果封装详解

mybatis模糊查询以及结果封装详解

mybatis模糊查询以及结果封装详解

创建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.etime</groupId><artifactId>day09</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></properties><dependencies>
<!--        添加lombok依赖工具使用其中的注解方法可以让实体类中get,set,以及实体类中操作少一些--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.16</version></dependency><!--        添加和引入mybatis的版本号等依赖--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.1</version></dependency><!--        这里添加mysql依赖--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.11</version><scope>runtime</scope></dependency><!--        如果不需要也可不进行单元测试的依赖引入--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency></dependencies></project>

编写核心配置文件加载所需要的资源

编写config.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--    配置 mybatis的环境--><environments default="development">
<!--        配置环境--><environment id="development">
<!--            配置事物类型--><transactionManager type="JDBC"></transactionManager>
<!--            配置连接数据库的信息:用的是数据源[连接池]--><dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<!--                jdbc:mysql://localhost:3306/db_school?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC-->
<!--                和javaWeb servlet三层架构中的区别这里是只需要设置时区就可以了--><property name="url" value="jdbc:mysql://localhost:3306/db_school?serverTimezone=UTC"/><property name="username" value="root"/><property name="password" value="h123456"/></dataSource></environment></environments>
<!--    注册StudentDao接口映射文件位置--><mappers><mapper resource="mapper/StudentMapper.xml"/></mappers>
</configuration>

创建工厂连接数据处理工具SqlSessionUtil.java

SqlSessionUtil.java

package com.etime.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 {private static  SqlSession sqlSession =null;static {//加载配置文件InputStream inputStream = null;try {inputStream = Resources.getResourceAsStream("config.xml");} catch (IOException e) {e.printStackTrace();}//用于读取配置文件内容,生成SqlSessionFactorySqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);//获取SqlSession对象sqlSession = sqlSessionFactory.openSession();}public SqlSession getSqlSession(){return sqlSession;}
}

创建学生实体类对象Student.java

package com.etime.pojo;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;//添加无参构造函数
@NoArgsConstructor
//添加全参数构造函数
@AllArgsConstructor
//添加所有需要的get,set等方法
@Data
public class Student {private int sid;private String sname;private String sgender;private int sage;private String semail;private String sphoto;
}

模糊查询在开发中是一项不可缺少的重要内容。对于mybatis实现模糊查询有三种方式:

1、添加模糊查询的接口方法:getStudentSname;

//模糊查询根据学生名子姓或者名查询所有学生信息List<Student> getStudentBySname1(String sname);List<Student> getStudentBySname2(String sname);List<Student> getStudentBySname3(String sname);

2、配置接口方法对应的sql文件

1、配置占位符方式#{}

 <select id="getStudentBySname1" parameterType="String" resultType="com.etime.pojo.Student">select * from student where sname like #{sname}</select>

2、配置拼接字符串方式${}

 <select id="getStudentBySname2" parameterType="String" resultType="com.etime.pojo.Student">select * from student where sname like '%${value}%'</select>

我们在上面将原来的#{}占位符,改成了 v a l u e 。注意如果用模糊查询的这种写法,那么 {value}。注意如果用模糊查询的这种写法,那么 value。注意如果用模糊查询的这种写法,那么{value}的写法就是固定的,不能写成其它名字。

3、配置mysql函数式concat

<select id="getStudentBySname3" parameterType="String" resultType="com.etime.pojo.Student">select * from student where sname like concat('%',#{sname},'%')</select>

测试:

@Testpublic void t09(){SqlSession sqlSession = sqlSessionUtil.getSqlSession();StudentDao studentDao = sqlSession.getMapper(StudentDao.class);String sname="%高%";List<Student> list = studentDao.getStudentBySname1(sname);System.out.println(list);sqlSession.close();}@Testpublic void t10(){SqlSession sqlSession = sqlSessionUtil.getSqlSession();StudentDao studentDao = sqlSession.getMapper(StudentDao.class);Map<String,Object> map = new HashMap<>();List<Student> list = studentDao.getStudentBySname2("高");System.out.println(list);sqlSession.close();}@Testpublic void t11(){SqlSession sqlSession = sqlSessionUtil.getSqlSession();StudentDao studentDao = sqlSession.getMapper(StudentDao.class);List<Student> list = studentDao.getStudentBySname3("高");System.out.println(list);sqlSession.close();}

配置占位符方式#{}:

在这里插入图片描述

配置拼接字符串方式${}

在这里插入图片描述

配置mysql函数式concat

在这里插入图片描述

三次测试结果一样,说明三种方式都是ok的

mybatis结果封装

resultMap标签介绍

resultMap 标签可以建立查询的列名和实体类的属性名称不一致时建立对应关系。从而实现封装。在 select 标签中使用 resultMap 属性指定引用即可。同时 resultMap 可以实现将查询结果映射为复杂类型的 pojo,比如在查询结果映射对象中包括 pojo 和 list 实现一对一查询和一对多查询。

resultMap的使用

在接口中定义方法:

List<Student> getAllStudentsInfo();

在StudentMapper.xml中用resultMap编写

 <resultMap id="stuMap" type="com.etime.pojo.Student"><id property="sid" column="sid"></id><result property="sname" column="sname"></result><result property="sgender" column="sgender"></result><result property="sage" column="sage"></result><result property="semail" column="semail"></result><result property="sphoto" column="sphoto"></result></resultMap>

测试类MybatisTest.java中编写测试方法

@Testpublic void t013(){SqlSession sqlSession = sqlSessionUtil.getSqlSession();//获取StudentDao对象StudentDao studentDao = sqlSession.getMapper(StudentDao.class);//调用方法获取结果List<Student> list = studentDao.getAllStudentsInfo();for (Student student:list) {System.out.println(student);}sqlSession.close();}

运行结果:
在这里插入图片描述