MyBatisTest.java文件:
package com.teng.test;
import com.teng.mapper.StudentMapper;
import com.teng.pojo.Student;
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 org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MyBatisTest {
@Test
public void testSelectByConditionSingle() throws IOException {
/*模拟参数*/
// String studentName = "张";
String descriptions = "好学生";
/*对参数进行模糊查询处理*/
// studentName = "%" + studentName + "%";
descriptions = "%" + descriptions +"%";
/*将参数封装到Brand对象中*/
Student student = new Student();
// student.setStudentName(studentName);
student.setDescriptions(descriptions);
//加载mybatis的核心配置文件,获取SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//获取SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//获取Mapper接口的代理对象
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
//执行sql方法
List<Student> students = studentMapper.selectByConditionSingle(student);
System.out.println(students);
sqlSession.commit();
sqlSession.close();
}
}
StudentMapper接口:
package com.teng.mapper;
import com.teng.pojo.Student;
import java.util.List;
public interface StudentMapper {
List<Student> selectByConditionSingle(Student student);
}
StudentMapper.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.teng.mapper.StudentMapper">
<resultMap id="studentResultMap" type="student">
<!--
id:完成主键字段的映射
column:表的列名
property:实体类的属性名
result:完成一般字段的映射
column:表的列名
property:实体类的属性名
-->
<result column="student_name" property="studentName"></result>
<result column="department_name" property="departmentName"></result>
</resultMap>
<select id="selectByConditionSingle" resultMap="studentResultMap">
select *
from tb_student
<where>
<choose>
<when test="studentName != null and studentName != ''">
student_name like #{studentName}
</when>
<when test="descriptions != null and descriptions != ''">
descriptions like #{descriptions}
</when>
</choose>
</where>;
</select>
</mapper>
实体类Student:
package com.teng.pojo;
public class Student {
private Integer id;
private String studentName;
private Integer sex;
private Integer age;
private String descriptions;
private String departmentName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getDescriptions() {
return descriptions;
}
public void setDescriptions(String descriptions) {
this.descriptions = descriptions;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", studentName='" + studentName + ''' +
", sex=" + sex +
", age=" + age +
", descriptions='" + descriptions + ''' +
", departmentName='" + departmentName + ''' +
'}';
}
}
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>
<!--日志-->
<settings>
<setting name= "mapUnderscoreToCamelCase" value = "true"/>
<setting name="logImpl" value="STDOUT_LOGGING" />
</settings>
<!-- 别名-->
<typeAliases>
<package name="com.teng.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!-- 数据库连接信息-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<!--在url后添加指定的UTF-8字符编码-->
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
<environment id="test">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!-- 数据库连接信息-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 加载sql映射文件-->
<!-- <mapper resource="com/teng/mapper/UserMapper.xml"/>-->
<!--包扫描-->
<package name="com.teng.mapper"/>
</mappers>
</configuration>
logback.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!--CONSOLE : 表示当前日志信息可以输出到控制台-->
<appender name ="Console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%level] %blue(%d{HH:mm;ss.SSS}) %cyan([%thread]) %boldGreen(%logger{15}) -%msg %n</pattern>
</encoder>
</appender>
<logger name="com.itheima" level="DEBUG" additivity="false">
<appender-ref ref="Console"/>
</logger>
</configuration>
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>org.example</groupId>
<artifactId>mybatis-test</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<!--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>5.1.46</version>
</dependency>
<!--junit 单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<!--添加slf4j日志-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.20</version>
</dependency>
<!--添加logback-classic依赖-->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<!--添加logback-core依赖-->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.2.3</version>
</dependency>
</dependencies>
</project>
创建tb_student表的sql:
drop table if exists tb_student;
create table tb_student
(
id int primary key auto_increment,
student_name varchar(20),
sex int,
age int,
descriptions varchar(100),
department_name varchar(20)
);
insert into tb_student(student_name,sex,age,descriptions,department_name)
values('张三',1,18,'好学生,成绩优异,品学兼优','计算机系'),
('李四',0,20,'中等偏上,聪明贪玩','信息安全系'),
('王五',1,21,'成绩较差,心思不在学习上','自动化系'),
('张飞',1,19,'好学生,身体也超棒,长跑冠军','软件工程系');
执行查询运行结果: