💕喜欢的朋友可以关注一下,下次更新不迷路!💕(●'◡'●)
目录
一、Mybatis为何物?👌
二、快速入门🤣
1、新建项目😊
2、数据库建表😊
3、导入依赖的jar包😊
4、根据表建pojo类😊
5、编写mapper映射文件(编写sql)😊
6、编写全局配置文件(主要是配置数据源信息)😊
7、测试😊
三、快速入土😢
代理开发😂
1、定义与SQL映射文件同名的Mapper接口,并且将Mapper接口和SQL映射文件放置在同一目录下。
2、设置SQL映射文件的namespace属性为Mapper接口全限定名。
3、在Mapper接口中定义方法,方法名就是SQL映射文件中sql语句的id,并保持参数类型和返回值类型一致。
4、通过SqlSession的getMapper方法获取Mapper接口的代理对象,并调用对应方法。
Mybatis核心配置--mybatis-config.xml😂
1、可以连接多个数据库
2、配置标签
案例😂
1、 建表
2、实体类
3、测试类
4、mybatisx插件
根据方法自动生成mapper映射文件
5、查询(查询所有)
6、查看详情(根据id查询一个)
7、条件查询
根据参数接收(无参/一个参数/两个参数/)
散装参数(模糊匹配)
对象参数
map参数
动态条件查询(用户输入条件时,是否所有条件都会填写。不是,哥们🤣👌)
使用if,choose,when设定条件
8、添加
主键返回
9、修改
修改全部字段
修改动态字段
10、删除
单个删除
批量删除
注解开发😍
一、Mybatis为何物?👌
🤦♂️恶臭的描述: MyBatis 是一个优秀的持久层框架,它对JDBC的操作数据库的过程进行封装,让开发者只需要关注 SQL 本身,而不需要花费精力去处理例如注册驱动、创建connection、创建statement、手动设置参数、结果集检索等JDBC繁琐的过程代码。
❤️舒服的描述:
不需要手动编写 JDBC 代码来执行 SQL 语句,也不需要处理数据库连接的创建和关闭。
所有的数据库操作都被抽象成了简单的 Mapper 方法调用。 (伟大无需多言!)
Mybatis中文官网
二、快速入门🤣
前言:
完整结构图
只需要通过如下几个步骤,即可用mybatis快速进行持久层的开发
- 编写全局配置文件
- 编写mapper映射文件
- 加载全局配置文件,生成SqlSessionFactory
- 创建SqlSession,调用mapper映射文件中的SQL语句来执行CRUD操作
🤣话不多说,直接Mybatis启动!🤣
1、新建项目😊
java8
2、数据库建表😊
3、导入依赖的jar包😊
<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/maven-v4_0_0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.itqingshui</groupId><artifactId>mybatis-test1</artifactId><version>1.0-SNAPSHOT</version><name>Archetype - mybatis-test1</name><url>http://maven.apache.org</url><dependencies><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.6</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.21</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.30</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> <!-- 替换为你的JDK版本 --><target>1.8</target> <!-- 替换为你的JDK版本 --></configuration></plugin></plugins></build></project>
4、根据表建pojo类😊
package pojo;import lombok.*;@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Student{private Integer id;private String name;private Integer score;private Integer age;private Integer gender;
}
@Getter @Setter:省略set,get方法。
@NoArgsConstructor:建立一个无参构造器。
@AllArgsConstructor:建立一个全参构造器。
@ToString:建立一个tostring方法。
5、编写mapper映射文件(编写sql)😊
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="pojo.StudentMapper"><select id="findAll" resultType="pojo.Student">select * from student</select><insert id="insert" parameterType="pojo.Student">insert into student(name,gender,age,score) values(#{name},#{gender},#{age},#{score})</insert><delete id="delete" parameterType="int">delete from student where id=#{id}</delete><update id="update" parameterType="pojo.Student">update student set name=#{name},gender=#{gender},age=#{age},score=#{score} where id=#{id}</update></mapper>
6、编写全局配置文件(主要是配置数据源信息)😊
resources包下
<?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><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/ssm?useSSL=false&serverTimezone=UTC"/><property name="username" value="lovertx"/><property name="password" value="1234567"/></dataSource></environment></environments><mappers><!-- 加载编写的SQL语句 --><mapper resource="StudentMapper.xml"/></mappers>
</configuration>
7、测试😊
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 pojo.Student;import java.io.IOException;
import java.io.InputStream;
import java.util.List;public class MybatisDemo {public static void main(String[] args) throws IOException, ClassNotFoundException {String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();List<Student> student = sqlSession.selectList("pojo.StudentMapper.findAll");for (Student s : student){System.out.println(s);}sqlSession.close();}
}
三、快速入土😢
代理开发😂
对于
List<Student> student = sqlSession.selectList("pojo.StudentMapper.findAll");
目的:
解决原生方式中的硬编码。
简化后期执行SQL
1、定义与SQL映射文件同名的Mapper接口,并且将Mapper接口和SQL映射文件放置在同一目录下。
在resources包下创建mapper包并放入StudentMapper.xml
2、设置SQL映射文件的namespace属性为Mapper接口全限定名。
将
<mapper namespace="pojo.StudentMapper">
改为
<mapper namespace="mapper.StudentMapper">
3、在Mapper接口中定义方法,方法名就是SQL映射文件中sql语句的id,并保持参数类型和返回值类型一致。
StudentMapper中
package mapper;import pojo.Student;import java.util.List;public interface StudentMapper {List<Student> findAll();
}
4、通过SqlSession的getMapper方法获取Mapper接口的代理对象,并调用对应方法。
StudentMapper userMapper = sqlSession.getMapper(StudentMapper.class);
userMapper.findAll().forEach(System.out::println);
Mybatis核心配置--mybatis-config.xml😂
1、可以连接多个数据库
可以配置多个environment,通过default属性切换不同的environment
<?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><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/ssm?useSSL=false&serverTimezone=UTC"/><property name="username" value="lovertx"/><property name="password" value="1234567"/></dataSource></environment></environments><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/ssm?useSSL=false&serverTimezone=UTC"/><property name="username" value="lovertx"/><property name="password" value="1234567"/></dataSource></environment></environments><mappers><!-- 加载编写的SQL语句 --><mapper resource="mapper/StudentMapper.xml"/></mappers>
</configuration>
2、配置标签
案例😂
1、 建表
id:主键
brand_name:品牌名称
company_name:企业名称
ordered:排序字段
description:描述信息
status:状态(0:禁用,1启用)
2、实体类
package pojo;import lombok.*;@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Brand {private Integer id;private String brand_name;private String company_name;private Integer ordered;private String description;private Integer status;
}
3、测试类
4、mybatisx插件
通过点击左边的红色小鸟
可以找到蓝色小鸟
根据方法自动生成mapper映射文件
1、第一步:在StudentMapper中
package mapper;import pojo.Student;import java.util.List;public interface StudentMapper {List<Student> findAll();Student findById(int id);
}
2、使用插件自动生成
<select id="findById" resultType="pojo.Student"></select>
3、补充实际操作
<select id="findById" resultType="pojo.Student">select * from student where id=#{id}</select>
5、查询(查询所有)
1、创建BrandMapper(先写方法,后自动写sql)
package mapper;import pojo.Brand;
import java.util.List;public interface BrandMapper {List<Brand> findAll();
}
2、创建BrandMapper.xml
package mapper;import pojo.Brand;
import java.util.List;public interface BrandMapper {List<Brand> findAll();
}
3、配置映射文件
在mybatis-config.xml添加 <mapper resource="mapper/BrandMapper.xml"/>
<mappers><!-- 加载编写的SQL语句 --><mapper resource="mapper/StudentMapper.xml"/><mapper resource="mapper/BrandMapper.xml"/></mappers>
4、测试类
import mapper.BrandMapper;
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 MybatisDemo3 {public static void main(String[] args) throws IOException, ClassNotFoundException {String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();BrandMapper userMapper = sqlSession.getMapper(BrandMapper.class);userMapper.findAll().forEach(System.out::println);sqlSession.close();}
}
6、查看详情(根据id查询一个)
BrandMapper中写:
Brand findById(int id);
public interface BrandMapper {List<Brand> findAll();Brand findById(int id);
}
BrandMapper.xml中写:
<select id="findById" resultType="pojo.Brand">select * from tb_brand where id = #{id}</select>
测试类中写:
public class MybatisDemo {public static void main(String[] args) throws IOException, ClassNotFoundException {String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);Brand brand = brandMapper.findById(1);System.out.println(brand);sqlSession.close();}
}
7、条件查询
类似于实现这样的功能:
根据参数接收(无参/一个参数/两个参数/)
散装参数(模糊匹配)
因模糊匹配需要处理参数
接口方法
List<Brand> selectByCondition(@Param("status") int status, @Param("company_name") String company_name, @Param("brand_name") String brand_name);
sql语句
<select id="selectByCondition" resultType="pojo.Brand">select * from tb_brandwhere status = #{status}and brand_name like #{brand_name}and company_name like #{company_name}</select>
测试类
public class MybatisDemo {public static void main(String[] args) throws IOException {//接收参数int status = 1;String company_name = "华为";String brand_name = "华为";//因模糊匹配,所有处理参数company_name = "%" + company_name + "%";brand_name = "%" + brand_name + "%";String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);List<Brand> brands = brandMapper.selectByCondition(status, company_name, brand_name);for (Brand brand : brands) {System.out.println(brand);}sqlSession.close();}
}
对象参数
对象的属性名称要和参数占位符名称一致
Mapper接口:
List<Brand> selectByCondition(Brand brand);
sql语句:
<select id="selectByCondition" resultType="pojo.Brand">select * from tb_brandwhere status = #{status}and brand_name like #{brand_name}and company_name like #{company_name}</select>
测试类:
多了个封装对象
public class MybatisDemo {public static void main(String[] args) throws IOException {//接收参数int status = 1;String company_name = "华为";String brand_name = "华为";//因模糊匹配,所有处理参数company_name = "%" + company_name + "%";brand_name = "%" + brand_name + "%";//封装对象Brand brand = new Brand();brand.setStatus(status);brand.setCompany_name(company_name);brand.setBrand_name(brand_name);String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);// List<Brand> brands = brandMapper.selectByCondition(status, company_name, brand_name);List<Brand> brands = brandMapper.selectByCondition(brand);for (Brand brand1 : brands) {System.out.println(brand1);}sqlSession.close();}
}
map参数
Mapper接口:
List<Brand> selectByCondition(Map map);
sql语句:
<select id="selectByCondition" resultType="pojo.Brand">select * from tb_brandwhere status = #{status}and brand_name like #{brand_name}and company_name like #{company_name}</select>
测试类:
public class MybatisDemo {public static void main(String[] args) throws IOException {//接收参数int status = 1;String company_name = "华为";String brand_name = "华为";//因模糊匹配,所有处理参数company_name = "%" + company_name + "%";brand_name = "%" + brand_name + "%";//封装对象
// Brand brand = new Brand();
// brand.setStatus(status);
// brand.setCompany_name(company_name);
// brand.setBrand_name(brand_name);Map map = new HashMap();map.put("status",status);map.put("company_name",company_name);map.put("brand_name",brand_name);String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);// List<Brand> brands = brandMapper.selectByCondition(status, company_name, brand_name);
// List<Brand> brands = brandMapper.selectByCondition(brand);List<Brand> brands = brandMapper.selectByCondition(map);for (Brand brand1 : brands) {System.out.println(brand1);}sqlSession.close();}
}
动态条件查询(用户输入条件时,是否所有条件都会填写。不是,哥们🤣👌)
只需要修改sql语句:
<select id="selectByCondition" resultType="pojo.Brand">select * from tb_brandwhere<if test="status != null">status = #{status}</if><if test="brand_name != null and brand_name != ''">and brand_name like #{brand_name}</if><if test="company_name != null and company_name != ''">and company_name like #{company_name}</if></select>
可是当特殊条件缺少时会出现错误:
Map map = new HashMap();//map.put("status",status);map.put("company_name",company_name);//map.put("brand_name",brand_name);
解决:恒等式
将sql语句修改为:
<select id="selectByCondition" resultType="pojo.Brand">select * from tb_brand<where><if test="status != null">and status = #{status}</if><if test="brand_name != null and brand_name != ''">and brand_name like #{brand_name}</if><if test="company_name != null and company_name != ''">and company_name like #{company_name}</if></where></select>
使用if,choose,when设定条件
<select id="selectByConditionOne" resultType="pojo.Brand">select * from tb_brandwhere<choose><!--相当于switch--><when test="status != null"><!--相当于case-->status = #{status}</when><when test="brand_name != null and brand_name != ''">brand_name like #{brand_name}</when><when test="company_name != null and company_name != ''">company_name like #{company_name}</when><otherwise><!--当用户一个条件都不给-->1=1</otherwise></choose></select>
8、添加
接口方法
void add(Brand brand);
sql语句
<insert id="add">insert into tb_brand(brand_name,company_name,ordered,description,status)values(#{brand_name},#{company_name},#{ordered},#{description},#{status})</insert>
测试类
public class MybatisDemo3 {public static void main(String[] args) throws IOException, ClassNotFoundException {String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();BrandMapper userMapper = sqlSession.getMapper(BrandMapper.class);int status = 1;String company_name = "菠萝手机";String brand_name = "菠萝";int ordered = 1;String description = "美国有苹果,中国有菠萝";Brand brand = new Brand();brand.setStatus(status);brand.setCompany_name(company_name);brand.setBrand_name(brand_name);brand.setOrdered(ordered);brand.setDescription(description);userMapper.add(brand);
//事务提交sqlSession.commit();sqlSession.close();}
}
主键返回
实现可查询主键id的值
因为事务回滚导致少了id=4
因此查询菠萝的id的值为5
将sql语句改为
<insert id="add" useGeneratedKeys="true" keyProperty="id">insert into tb_brand(brand_name,company_name,ordered,description,status)values(#{brand_name},#{company_name},#{ordered},#{description},#{status})</insert>
即添加
useGeneratedKeys="true" keyProperty="id"
9、修改
修改全部字段
实现
Mapper接口
void update(Brand brand);
SQL语句
<update id="update">update tb_brand<set><if test="brand_name != null and brand_name != ''">brand_name = #{brand_name},</if><if test="company_name != null and company_name != ''">company_name = #{company_name},</if><if test="ordered != null">ordered = #{ordered},</if><if test="description != null and description != ''">description =#{description},status = #{status}</if>where id = #{id}</set></update>
测试类
public class UpdateTest {public static void main(String[] args) throws IOException{String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession(true);BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);Brand brand = new Brand();brand.setId(5);brand.setBrand_name("香飘飘");brand.setCompany_name("香飘飘");brand.setDescription("香飘飘");brand.setOrdered(100);brand.setStatus(1);brandMapper.update(brand);sqlSession.close();}
}
修改动态字段
实现修改密码功能(想单独改哪个值就改哪个值)
如果调用接口却不给参数,则数据库会出现null值🤦♂️
实现
只需要在SQL语句中添加条件,添加<set>标签
<update id="update">update tb_brand<set><if test="brand_name != null and brand_name != ''">brand_name = #{brand_name},</if><if test="company_name != null and company_name != ''">company_name = #{company_name},</if><if test="ordered != null">ordered = #{ordered},</if><if test="description != null and description != ''">description =#{description},status = #{status}</if>where id = #{id}</set></update>
10、删除
单个删除
Mapper接口
void delete(int id);
SQL语句
<delete id="delete">delete from tb_brand where id = #{id}</delete>
测试类
public class DeleteTest {public static void main(String[] args) throws IOException, IOException {String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession(true);BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);brandMapper.delete(2);sqlSession.close();}
}
批量删除
实现
传id数组,sql遍历数组,一个一个删掉
Mapper接口
void deleteByIds(@Param("ids") int[] ids);
SQL语句
<delete id="deleteByIds">delete from tb_brand where id in<foreach collection="ids" item="id" open="(" separator="," close=")">#{id}</foreach></delete>
测试类
public class DeleteTest2 {public static void main(String[] args) throws IOException, IOException {String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession(true);BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);int []ids = {5,6};brandMapper.deleteByIds(ids);sqlSession.close();}
}
注解开发😍
优点:对于简单的SQL语句使用注解开发会非常便捷。
@Select("select * from tb_user where id = #{id}")
public User selectById(int id);
查询:@Select
添加:@Insert
修改: @Update
删除:@Delete
缺点:对于复杂的SQL语句应使用xml映射文件编写。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="mapper.BrandMapper"><insert id="add" useGeneratedKeys="true" keyProperty="id">insert into tb_brand(brand_name,company_name,ordered,description,status)values(#{brand_name},#{company_name},#{ordered},#{description},#{status})</insert><update id="update">update tb_brand<set><if test="brand_name != null and brand_name != ''">brand_name = #{brand_name},</if><if test="company_name != null and company_name != ''">company_name = #{company_name},</if><if test="ordered != null">ordered = #{ordered},</if><if test="description != null and description != ''">description =#{description},status = #{status}</if>where id = #{id}</set></update><delete id="delete">delete from tb_brand where id = #{id}</delete><delete id="deleteByIds">delete from tb_brand where id in<foreach collection="ids" item="id" open="(" separator="," close=")">#{id}</foreach></delete><select id="findAll" resultType="pojo.Brand">select * from tb_brand</select><select id="findById" resultType="pojo.Brand">select * from tb_brand where id = #{id}</select><!-- <select id="selectByCondition" resultType="pojo.Brand">-->
<!-- select * from tb_brand-->
<!-- where status = #{status}-->
<!-- and brand_name like #{brand_name}-->
<!-- and company_name like #{company_name}-->
<!-- </select>--><select id="selectByCondition" resultType="pojo.Brand">select * from tb_brand<where><if test="status != null">and status = #{status}</if><if test="brand_name != null and brand_name != ''">and brand_name like #{brand_name}</if><if test="company_name != null and company_name != ''">and company_name like #{company_name}</if></where></select><select id="selectByConditionOne" resultType="pojo.Brand">select * from tb_brandwhere<choose><!--相当于switch--><when test="status != null"><!--相当于case-->status = #{status}</when><when test="brand_name != null and brand_name != ''">brand_name like #{brand_name}</when><when test="company_name != null and company_name != ''">company_name like #{company_name}</when><otherwise><!--当用户一个条件都不给-->1=1</otherwise></choose></select>
</mapper>
💕完结撒花!💕