一、认识MyBatis
MyBatis 是一款优秀的持久层框架,是一个访问数据库的Java组件。它支持定制化 SQL、存储过程以及高级映射。
二、在哪儿使用Mybatis?
三、使用Mybatis
1.在数据库中建一个库为mybatis_db,再建立一个emp表。
create database mybatis_db;
create table emp(
e_id varchar(20) primary key,
e_name varchar(50) not null,
e_sal decimal(8,2) not null,
e_date date not null
);
insert into emp values('001','emp1','8000',date_sub(now(),interval 50 day) );
insert into emp values('002','emp2','7000',date_sub(now(),interval 30 day) );
insert into emp values('003','emp3','8600',date_sub(now(),interval 150 day) );
insert into emp values('004','emp4','5700',date_sub(now(),interval 350 day) );
insert into emp values('005','emp5','6600',date_sub(now(),interval 850 day) );
insert into emp values('006','emp6','9876',date_sub(now(),interval 500 day) );
insert into emp values('007','emp7','8988',date_sub(now(),interval 660 day) );
insert into emp values('008','emp8','5632',date_sub(now(),interval 550 day) );
insert into emp values('009','emp9','3688',date_sub(now(),interval 510 day) );
2.建一个maven项目,名为mybatis01,在pom文件中导入响应的jar包。mysql驱动包,mybatis包,junit测试,log4j日志。
pom文件如下:
<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>ztt.mybatis</groupId>
<artifactId>mybatis01</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
<!-- mybatis包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.3</version>
</dependency>
<!-- junit测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- log4j日志输出 -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.13.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<!-- 编译器配置 -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
3.创建mybatis.xml和log4j.xml文件,在src/main/resources文件下,文件内容分别为:
mybatis.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>
<!-- 默认数据环境 -->
<environments default="development">
<!-- 其中的一个数据环境 -->
<environment id="development">
<!-- 通过jdbc管理事务 -->
<transactionManager type="JDBC"/>
<!-- 数据环境采用数据池 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis_db"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 映射器所在包名 -->
<package name="ztt.mybatis.Mapper"/>
</mappers>
</configuration>
log4j2.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<!-- 映射器的包名 -->
<Logger name="ztt.mybatis.Mapper" level="trace" additivity="false">
<AppenderRef ref="Console"/>
</Logger>
<Root level="error">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
4.创建JavaBean,在ztt.mybatis.model包下,文件如下:
package ztt.mybatis.model;
import java.util.Date;
public class Employee {
private String e_id;
private String e_name;
private Double e_sal;
private Date e_date;
public Employee() {
super();
// TODO Auto-generated constructor stub
}
public Employee(String e_id, String e_name, Double e_sal, Date e_date) {
super();
this.e_id = e_id;
this.e_name = e_name;
this.e_sal = e_sal;
this.e_date = e_date;
}
public String getE_id() {
return e_id;
}
public void setE_id(String e_id) {
this.e_id = e_id;
}
public String getE_name() {
return e_name;
}
public void setE_name(String e_name) {
this.e_name = e_name;
}
public Double getE_sal() {
return e_sal;
}
public void setE_sal(Double e_sal) {
this.e_sal = e_sal;
}
public Date getE_date() {
return e_date;
}
public void setE_date(Date e_date) {
this.e_date = e_date;
}
}
package ztt.mybatis.model;
public class EmployeeDto {
private Double start_sal;
private Double end_sal;
public EmployeeDto(Double start_sal, Double end_sal) {
super();
this.start_sal = start_sal;
this.end_sal = end_sal;
}
public Double getStart_sal() {
return start_sal;
}
public void setStart_sal(Double start_sal) {
this.start_sal = start_sal;
}
public Double getEnd_sal() {
return end_sal;
}
public void setEnd_sal(Double end_sal) {
this.end_sal = end_sal;
}
}
5.创建Mapper接口,在ztt.mybatis.mapper包下
package ztt.mybatis.Mapper;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import ztt.mybatis.model.Employee;
import ztt.mybatis.model.EmployeeDto;
public interface EmployeeMapper {
// 1.查询表中所有的数据
@Select("select * from emp")
public List<Employee> findEmployeeList();
// 2.根据名称查询
@Select("select * from emp where e_name like concat('%',#{name},'%')")
public List<Employee> findEmployeeList1(String name);
// 3.根据工资范围来查(两个参数)
@Select("select * from emp where e_sal >=#{start_sal} and e_sal <=#{end_sal}")
public List<Employee> findEmployeeList2(@Param("start_sal") Double start_sal, @Param("end_sal") Double end_sal);
// 4.根据工资范围来查(两个参数),通过javaBean,占位符
@Select("select * from emp where e_sal >=#{start_sal} and e_sal <=#{end_sal}")
public List<Employee> findEmployeeList3(EmployeeDto dto);
// 5.根据工资范围来查(两个参数),通过javaBean,$
@Select("select * from emp where e_sal >=${start_sal} and e_sal <=${end_sal}")
public List<Employee> findEmployeeList4(EmployeeDto dto);
// 6.插入数据
@Insert("insert into emp(e_id,e_name,e_sal,e_date) values (#{e_id},#{e_name},#{e_sal},#{e_date})")
public int insertEmployeeList5(Employee emp);
//7.删除数据(全删)
@Delete("delete from emp")
public int deleteAllEmployeeList6();
//8.删除数据(根据名称删除)
@Delete("delete from emp where e_name like concat('%',#{name},'%')")
public List<Employee> deleteEmployeeList7(String name);
// 9.根据工资范围来删除(两个参数)
@Delete("delete from emp where e_sal >=#{start_sal} and e_sal <=#{end_sal}")
public List<Employee> deleteEmployeeList8(@Param("start_sal") Double start_sal, @Param("end_sal") Double end_sal);
//10.更新工资,全部加3333
@Update("update emp set e_sal=e_sal+3333 ")
public List<Employee> updateEmployeeList9();
}
6.创建Junit测试,在ztt.mybatis.test包下。
package ztt.mybatis.test;
import static org.junit.Assert.*;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import ztt.mybatis.Mapper.EmployeeMapper;
import ztt.mybatis.model.Employee;
import ztt.mybatis.model.EmployeeDto;
public class EmployeeTest {
private static SqlSessionFactory sqlSessionFactory;
@BeforeClass // 所有测试开始之前需要需要一次性执行的代码
public static void setUpBeforeClass() throws Exception {
// 加载配置文件
InputStream is = Resources.getResourceAsStream("mybatis.xml");
// 创建SqlSessionFactory
sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
}
@AfterClass // 所有测试结束之后需要需要一次性执行的代码
public static void tearDownAfterClass() throws Exception {
}
private SqlSession session;
private EmployeeMapper mapper;
@Before
public void setUp() throws Exception {
session = sqlSessionFactory.openSession(ExecutorType.REUSE);
mapper = session.getMapper(EmployeeMapper.class);
}
@After // 每一个测试方法执行之后都需要执行的代码
public void tearDown() throws Exception {
session.commit();
session.close();
}
@Test // 全查
public void test() {
List<Employee> list = mapper.findEmployeeList();
// for(Employee e:list) {
// System.out.println(e.getE_id()+","+e.getE_name()+","+e.getE_sal()+","+e.getE_date());
// }
}
@Test // 根据名称查询
public void test1() {
mapper.findEmployeeList1("8");
}
@Test // 根据工资范围来查查询
public void test2() {
mapper.findEmployeeList2(3000.0, 5000.0);
}
@Test // 根据工资范围来查查询,javabean的形式
public void test3() {
mapper.findEmployeeList3(new EmployeeDto(3000.0, 5000.0));
}
@Test // 根据工资范围来查查询,javabean的形式
public void test4() {
mapper.findEmployeeList4(new EmployeeDto(3000.0, 5000.0));
}
@Test // 5.插入数据
public void test5() {
for (int i = 201; i < 302; i++) {
mapper.insertEmployeeList5(
new Employee(String.valueOf(i), "新员工" + i, Math.random() * 5000 + 2000, new Date()));
}
}
@Test // 6.删除数据
public void test6() {
mapper.deleteAllEmployeeList6();
}
@Test // 7.根据名称删除
public void test7() {
mapper.deleteEmployeeList7("8");
}
@Test // 8.根据工资范围来删除
public void test8() {
mapper.deleteEmployeeList8(3000.0, 5000.0);
}
@Test // 10.更新工资,全部加3333
public void test9() {
mapper.updateEmployeeList9();
}
}
7.运行junit文件或其中的一个方法。
8.运行结果