当前位置: 首页 > news >正文

Spring Data JPA 与 MyBatisPlus的比较

前言

JPA(Java Persistence API)和MyBatis Plus是两种不同的持久化框架,它们具有不同的特点和适用场景。

JPA是Java官方的持久化规范,它提供了一种基于对象的编程模型,可以通过注解或XML配置来实现对象与数据库的映射关系。JPA的优点是可以对数据库进行更高级的操作,如查询、更新、删除等,同时也支持事务管理和缓存机制,能够更好地支持复杂的业务逻辑。

MyBatis Plus (MPP) 是在MyBatis基础上进行封装的增强版本,它提供了更简单易用的API和更高效的性能。MyBatis Plus通过XML或注解的方式来配置数据库映射关系,并提供了丰富的查询、更新、删除操作的方法。相对于JPA,MyBatis Plus配置简单、易于上手,同时也灵活性较高,能够更好地满足项目的特定需求。

如果只是针对单表的增删改查,两者十分相似,本质上都算ORM框架,那么到底什么时候适合用JPA,什么时候用MyBatisPlus,下面做下这两者的详细对比。

POM依赖

JPA

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

MPP

<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>

Entity定义

JPA

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.GeneratedValue;@Entity
@Table(name = "dept")
public class Dept {@Id@Column(name = "id")@GeneratedValue(strategy = GenerationType.AUTO)private Long id;@Column(name = "code")private String code;@Column(name = "name")private String name;
}

MPP

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;@TableName(value = "dept")
public class Dept {@TableId(value = "id", type = IdType.AUTO)private Long id;@TableField(value = "code")private String code;@TableField(value = "name")private String name;
}

DAO定义

基础CRUD

JPA

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;@Repository
public interface DeptRepository extends JpaRepository<Dept, Long> {
}

MPP

import org.apache.ibatis.annotations.Mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;@Mapper
public interface DeptMapper extends BaseMapper<Dept> {
}

基类主要方法

方法JpaRepositoryBaseMapper
插入一条记录save(T entity)insert(T entity)
插入多条记录saveAll(Iterable entities)insertBatchSomeColumn(List entityList)
根据 ID 删除deleteById(ID id)deleteById(Serializable id)
根据实体(ID)删除delete(T entity)deleteById(T entity)
根据条件删除记录-delete(Wrapper queryWrapper)
删除(根据ID或实体 批量删除)deleteAllById(Iterable<? extends ID> ids)deleteBatchIds(Collection<?> idList)
根据 ID 修改save(T entity)updateById(T entity)
根据条件更新记录-update(Wrapper updateWrapper)
根据 ID 查询findById(ID id)selectById(Serializable id)
查询(根据ID 批量查询)findAllById(Iterable ids)selectBatchIds(Collection<? extends Serializable> idList)
根据条件查询一条记录-selectOne(Wrapper queryWrapper)
根据条件判断是否存在记录exists(Example example)exists(Wrapper queryWrapper)
根据条件查询总记录数count(Example example)selectCount(Wrapper queryWrapper)
根据条件查询全部记录findAll(Example example, Sort sort)selectList(Wrapper queryWrapper)
根据条件查询分页记录findAll(Example example, Pageable pageable)selectPage(P page, Wrapper queryWrapper)

Example、Specification VS Wrapper

JPA使用Example和Specification 类来实现范本数据的查询,而MPP使用QueryWrapper来设置查询条件

JPA Example
Dept dept = new Dept();
dept.setCode("100");
dept.setName("Dept1");// select * from dept where code = '100' and name = 'Dept1';
List<Dept> deptList = deptRepository.findAll(Example.of(dept)); 

默认是生成的条件都是 “=”,如果要设置其他比较符,需要使用ExampleMatcher

Dept dept = new Dept();
dept.setCode("100");
dept.setName("Dept1");// select * from dept where code like '100%' and name like '%Dept1%';
List<Dept> deptList = deptRepository.findAll(Example.of(dept, ExampleMatcher.matching().withMatcher("code", ExampleMatcher.GenericPropertyMatchers.startsWith()).withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains()))); 

Example仅能实现对字符串类型的匹配模式,如果要设置其他类型的字段,可以实现JpaSpecificationExecutor接口来完成:

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;@Repository
public interface DeptRepository extends JpaRepository<Dept, Long>, JpaSpecificationExecutor<Dept>  {
}

增加以上接口后,会增加以下查询方法:

  • findOne(Specification spec)
  • findAll(Specification spec)
  • findAll(Specification spec, Pageable pageable)
  • count(Specification spec)
  • exists(Specification spec)

使用示例:

Dept dept = new Dept();
dept.setCode("100");
dept.setName("Dept1");// select * from dept where code like '100%' and name like '%Dept1%';
Specification<Dept> spec = new Specification<Dept>() {@Overridepublic Predicate toPredicate(Root<Dept> root, CriteriaQuery<?> query, CriteriaBuilder cb) {List<Predicate> predicates = new ArrayList<>();//  模糊查询(前缀匹配)if (dept.getCode() != null && !dept.getCode().isEmpty()) {predicates.add(cb.like(root.get("code"), dept.getCode() + "%"));}//  模糊查询if (dept.getName() != null && !dept.getName().isEmpty()) {predicates.add(cb.like(root.get("code"), '%' + dept.getCode() + "%"));}return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();}
};
List<Dept> deptList = deptRepository.findAll(Example.of(dept)); 

除了equalnotEqual, 针对日期、数字类型,还有gtgeltle等常用比较符。

自定义接口

JPA

JPA支持接口规范方法名查询,一般查询方法以 find、findBy、read、readBy、get、getBy为前缀,JPA在进行方法解析的时候会把前缀取掉,然后对剩下部分进行解析。例如:

@Repository
public interface DeptRepository extends JpaRepository<Dept, Long> {// 调用此方法时,会自动生成 where code = ? 的条件Dept getByCode(String code);
}

常用的方法命名有:

关键字方法命名sql where字句
DistinctfindDistinctByLastnameAndFirstnameselect distinct …​ where x.lastname = ?1 and x.firstname = ?2
AndfindByNameAndPwdwhere name= ? and pwd =?
OrfindByNameOrSexwhere name= ? or sex=?
Is,EqualsfindById, findByIdIs, findByIdEqualswhere id= ?
BetweenfindByIdBetweenwhere id between ? and ?
LessThanfindByIdLessThanwhere id < ?
LessThanEqualsfindByIdLessThanEqualswhere id <= ?
GreaterThanfindByIdGreaterThanwhere id > ?
GreaterThanEqualsfindByIdGreaterThanEqualswhere id > = ?
AfterfindByIdAfterwhere id > ?
BeforefindByIdBeforewhere id < ?
IsNullfindByNameIsNullwhere name is null
isNotNull,NotNullfindByNameNotNullwhere name is not null
LikefindByNameLikewhere name like ?
NotLikefindByNameNotLikewhere name not like ?
StartingWithfindByNameStartingWithwhere name like ‘?%’
EndingWithfindByNameEndingWithwhere name like ‘%?’
ContainingfindByNameContainingwhere name like ‘%?%’
OrderByfindByIdOrderByXDescwhere id=? order by x desc
NotfindByNameNotwhere name <> ?
InfindByIdIn(Collection<?> c)where id in (?)
NotInfindByIdNotIn(Collection<?> c)where id not in (?)
TruefindByEnabledTuewhere enabled = true
FalsefindByEnabledFalsewhere enabled = false
IgnoreCasefindByNameIgnoreCasewhere UPPER(name)=UPPER(?)
First,TopfindFirstByOrderByLastnameAscorder by lastname limit 1
FirstN,TopNfindTop3ByOrderByLastnameAscorder by lastname limit 3

MPP

MyBatisPlus没有JPA那样可以根据接口的方法名自动组装查询条件,但是可以利用Java8的接口默认实现来达到同样的目的,只不过需要编写少量的代码:

import org.apache.ibatis.annotations.Mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;@Mapper
public interface DeptMapper extends BaseMapper<Dept> {default Dept getByCode(String code) {return selectOne(Wrappers.<Dept>lambdaWrapper().eq(Dept::getCode, code));}
}

自定义SQL

JPA支持通过@Query注解和XML的形式实现自定义SQL,而MyBatis支持通过@Select、@Delete、@Update、@Script注解和XML的形式实现自定义SQL。

JPA

JPA的自定义SQL分为JPQL(Java Persistence Query Language Java 持久化查询语言)和原生SQL两种。
JPQL:

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;@Repository
public interface DeptRepository extends JpaRepository<Dept, Long> {@Query(value = "select d from Dept d where d.code = ?1")Dept getByCode(String code);@Modifying@Query(value = "delete from Dept d where d.code = :code")int deleteByCode(@Param("code") String code);
}

原生SQL

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;@Repository
public interface DeptRepository extends JpaRepository<Dept, Long> {@Query(value = "SELECT * FROM dept WHERE name = ?1", countQuery = "SELECT count(*) FROM dept WHERE name = ?1", nativeQuery = true)Page<Dept> findByName(@Param("name") String name, Pageable pageable);
}

XML形式:
/resource/META-INFO/orm.xml

<named-query name="Dept.getByCode"><query> select d from Dept d where d.code = ?1</query>
</named-query>
<named-native-query name="Dept.deleteByCode"><query> DELETE FROM dept WHERE code = ?1</query>
</named-native-query>

MyBatis

JPA的自定义SQL分为注解形式和XML形式
注解形式:

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;@Mapper
public interface DeptMapper extends BaseMapper<Dept> {@Select(value = "SELECT * FROM dept WHERE code = #{code}")Dept getByCode(@Param("code") String code);@Delete("DELETE FROM dept WHERE code = #{code}")int deleteByCode(@Param("code") String code);@Select(value = "SELECT * FROM dept WHERE name = #{name}")IPage<Dept> findByName(@Param("name") String name, IPage<Dept> page);
}

XML形式:
/resource/mapper/DeptMapper.xml

<select id = "getByCode", resultType = "Dept">SELECT * FROM dept WHERE code = #{code}
</select>
<delete id = "deleteByCode">DELETE FROM dept WHERE code = #{code}
</select>
<select id = "findByName">SELECT * FROM dept WHERE name = #{name}
</select>
http://www.lryc.cn/news/344921.html

相关文章:

  • 【C++】STL-list的使用
  • 进度条(小程序)
  • PyCharm安装教程(超详细图文教程)
  • 金蝶BI应收分析报表:关于应收,这样分析
  • salmon使用体验
  • Ubuntu 20.04 安装 Ansible
  • TypeScript学习笔记:强类型JavaScript的优雅之旅
  • 监控异地组网怎么组网?
  • 将本地托管模型与 Elastic AI Assistant 结合使用的好处
  • Linux的内核态和用户态
  • springboot利用Redis的Geo数据类型,获取附近店铺的坐标位置和距离列表
  • Vitis HLS 学习笔记--理解串流Stream(2)
  • Golang | Leetcode Golang题解之第80题删除有序数组中的重复项II
  • uniapp自定义websocket类实现socket通信、心跳检测、连接检测、重连机制
  • Hive UDTF之explode函数、Lateral View侧视图
  • 智慧公厕打造智慧城市新标杆
  • 字节发布文生图模型PuLID:高效身份ID特征定制,单张图像克隆AI虚拟分身
  • SpringBoot启动流程分析之创建SpringApplication对象(一)
  • SSH简介 特点以及作用
  • MQTT服务搭建及python使用示例
  • Ubuntu如何设置中文输入法
  • PostgreSQL的pg_dump和 pg_dumpall 异同点
  • 【Ping】Windows 网络延迟测试 ping 、telnet、tcping 工具
  • DuDuTalk:4G桌面拾音设备在银行网点服务场景的应用价值
  • QT 设置窗口不透明度
  • 如何在Python中实现文本相似度比较?
  • 韩顺平0基础学Java——第7天
  • 性能远超GPT-4!谷歌发布Med-Gemini医疗模型;李飞飞首次创业瞄准空间智能;疫苗巨头联合OpenAl助力AI医疗...
  • 中国科技大航海时代,“掘金”一带一路
  • ffmpeg7.0 flv支持hdr