1.介绍:
Mybatis是一个java编写的轻量级(使用方式简单)的半自动(sql自己写,其他框架做)的ORM映射的Dao层框架。
Dao(Database Access Object):指java程序中专门用于访问数据库的对象:
实现目的:解决繁琐的jdbc连接数据库的过程,只需要编写代码即可
2.数据准备
mysql中建库
CREATE DATABASE `Mybatis`CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;
CREATE TABLE employee(
id INT(11) PRIMARY KEY AUTO_INCREMENT,
last_name VARCHAR(255),
gender VARCHAR(10),
email VARCHAR(255)
);
INSERT INTO employee(last_name,gender,email) VALUES('Tom','male','Tom@163.com');
INSERT INTO employee(last_name,gender,email) VALUES('Jack','male','Jack@163.com');
INSERT INTO employee(last_name,gender,email) VALUES('Marry','female','Tom@163.com');
3. 新建工程
idea里新建maven project
idea的设置里,可以设置每次新建文件都先生成文档注释,方便笔记
4.pox.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">
<parent>
<artifactId>dibackground</artifactId>
<groupId>org.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>MybatisDemo</artifactId>
<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.4.6</version>
</dependency>
<!--导入数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
<!--提供lombok注解,使用注解,为类提供增强的插件-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<scope>provided</scope>
</dependency>
<!--提供junit,单元测试依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
5.创建Employee类
package com.atguigu.mybatis.bean; /** * @Data: 这是一个组合注解,相当于同时应用了@ToString, @EqualsAndHashCode, @Getter, @Setter和@RequiredArgsConstructor(如果存在无参构造器则为@NoArgsConstructor)。它极大地简化了Java类的声明,使得无需手动编写这些常见的样板代码。 * @NoArgsConstructor: 该注解会在编译时为类生成一个无参构造器。如果你的类中所有字段都有默认值或者允许为null,那么这个注解可以确保即使没有自定义构造器,也能创建该类的实例。 * @AllArgsConstructor: 该注解会在编译时为类生成一个全参数构造器,其参数列表包含类中所有字段。这样可以通过一次性传入所有字段的值来初始化对象。 * @Data: 已在上面解释过。 * 综上所述,这段代码在一个Java类中使用了Lombok注解,目的是自动化生成常用的 getter/setter 方法、无参构造器和全参构造器,以及 toString、equals 和 hashCode 方法,从而减少手动编写这些重复性代码的工作量,提高开发效率。在实际项目中,只需将这些注解放到类定义上方,编译时Lombok插件会自动处理这些逻辑。记得确保项目已正确引入Lombok库,并在IDE中安装对应的Lombok插件以支持注解的解析和提示。 */ import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class Employee { private Integer id; private String lastName; private String email; private String gender; }
6.设置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"/> </settings> <!--设置连接数据库的环境,通过default引用当前使用环境的id--> <environments default="development"> <environment id="development"> <!--定义单个环境,为环境设置唯一的引用id--> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/Mybatis?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <!--告知mybatis sql语句编写的位置--> <mappers> <!--对应一个sql语句编写的文件, class指sql语句编写在一个类的文件里--> <mapper class="com.atguigu.mybatis.mapper.EmployeeMapper"/> </mappers> </configuration>
7.编写Dao层接口
Dao层接口在Mybatis中习惯称为Mapper。
在接口上使用@Select注解表明当前方法被调用时,会执行一个Select语句。
在接口上使用@Delete注解表明当前方法被调用时,会执行一个Delete语句。
在接口上使用@Update注解表明当前方法被调用时,会执行一个Update语句。
在接口上使用@Insert注解表明当前方法被调用时,会执行一个Insert语句。
package com.atguigu.mybatis.mapper; import com.atguigu.mybatis.bean.Employee; import org.apache.ibatis.annotations.*; import java.util.List; /* 定义数据库的增删改查方法 jdbc的占位符是? mybatis中的占位符使用#{xxx} 1.如果sql语句中只有一个占位符,mybatis会自动将参数值设置到占位符中 2.如果多个占位符,需要从方法传入的bean中获取值 在公司中有两种情况: 简单查询sql,不经常更新,我们编写在接口类中 如果sql语句经常更新,不推荐将sql写在接口类中,可以将sql更新在xml文件中,通过配置动态引入 */ public interface EmployeeMapper { //查询单个员工 // @Select("select * from employee where id = ?") @Select("select * from employee where id = #{id}") Employee getEmpById(Integer id); //查询所有员工 @Select("select * from employee") List<Employee> getAll(); //插入员工信息 @Insert("insert into employee (last_name,gender,email)values(#{lastName},#{gender},#{email})") void insertEmployee(Employee e); //更新员工信息 @Update("update employee set last_name=#{lastName},gender=#{gender},email=#{email}"+ "where id = #{id}") void updateEmployee(Employee e); //删除员工信息 // @Delete("delete from employee where id = ?") @Delete("delete from employee where id = #{id}") void deleteEmployeeById(Integer id); /* 如果方法中有多个参数 ①把多个参数封装为bean,xxx还写bean的属性名皆可 ②把多个参数封装为一个Map集合, xxx写map集合中key的名字 ③使用@Param注解, xxx写参数名,标注在参数前 */ @Select("select * from employee where id > #{b} and gender =#{a}") // Param经常用于修饰当方法位置有多个参数,并且参数也是常见的字面量 List<Employee> getEmpByCondition(@Param("a") String gender, @Param("b") Integer id); }
8.调用接口中的方法
右键接口的类名,右键goto- test ,生成测试用例
在这里调用,传参数
8.1公用的,读取配置文件
package com.atguigu.mybatis.mapper; import com.atguigu.mybatis.bean.Employee; 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; import static org.junit.Assert.*; /** * jdbc获取数据库连接 * Connection * * mybatis中获取数据库连接 * SQlsessionFactory中获取 * * mybatis提供了动态代理模式 * * SqlSession由于不是线程安全的,因此不能作为静态变量或实例变量,而应该在每个方法中单独获取,并且使用完成后关闭。不可以在多个方法中共享sqlSession。 **/ public class EmployeeMapperTest { private SqlSessionFactory sqlSessionFactory; { //读取配置文件 InputStream is = null; try { is = Resources.getResourceAsStream("mybatis.xml"); }catch (IOException e ){ e.printStackTrace(); } //从配置文件中构造SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); }
8.2 读取单条数据
@Test public void getEmpById() { SqlSession sqlSession = sqlSessionFactory.openSession(); try { //编写业务代码 //创建mapper的对象,利用sqlSession创建的mapper对象 EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class); //这里就是调用了mapper接口中的方法,查询查询单个员工信息,然后#{}里传入的1,就是sql语句中的where id = Employee employee = mapper.getEmpById(1); System.out.println(employee); }finally { sqlSession.close(); } }
8.3 读取全部
@Test public void getAll() { SqlSession sqlSession = sqlSessionFactory.openSession(); try { EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class); //以一个list集合[],将内容包起来返回 List<Employee> employees = mapper.getAll(); System.out.println("全部数据为"+employees); }finally { sqlSession.close(); } }
8.4 增加数据
/* 读:查询 写: 增删改 写操作必须要提交事务的 在jdbc中是默认提交事务的 但在mybatis中是需要设置的 */ @Test public void insertEmployee() { //在openSession里面写ture ,就是给底层autoCommit这个属性赋值true SqlSession sqlSession = sqlSessionFactory.openSession(true); try { EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class); //这里因为建表的时候有主键自增,所以null即可 Employee employee = new Employee(null,"王五","56789","female"); //调用mapper的插入方法,传入的参数是employee里的表信息 mapper.insertEmployee(employee); System.out.println("插入数据成功,新的数据为"+employee); }finally { sqlSession.close(); } }
8.5 更新数据
@Test public void updateEmployee() { SqlSession sqlSession = sqlSessionFactory.openSession(true); try { EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class); Employee employee = mapper.getEmpById(4); employee.setLastName("老四"); mapper.updateEmployee(employee); System.out.println("更新成功"); }finally { sqlSession.close(); } }
8.6 删除数据
/* 读:查询 写: 增删改 写操作必须要提交事务的 在jdbc中是默认提交事务的 但在mybatis中是需要设置的 */ @Test public void deleteEmployee() { //在openSession里面写ture ,就是给底层autoCommit这个属性赋值true SqlSession sqlSession = sqlSessionFactory.openSession(true); try { EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class); //Mysql中的delete删不了主键自增,只能truncate 清空表才能删自增 mapper.deleteEmployeeById(3); System.out.println("删除成功"); }finally { sqlSession.close(); } }
8.7 多个条件的查询数据
这是mapper方法里的
@Test public void selectByCondition() { SqlSession sqlSession = sqlSessionFactory.openSession(); try { EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class); //@Select("select * from employee where id > #{b} and gender =#{a}") List<Employee> emps =mapper.getEmpByCondition("male",1); System.out.println("查询成功"+emps); }finally { sqlSession.close(); } } }