jpa整合mybatis模板解析、hibernate整合mybatis模板解析
jpa整合mybatis模板解析、hibernate整合mybatis模板解析
jpa是hibernate的封装,主要用于spring全家桶套餐。
hibernate难以编写复杂的SQL。例如一个订单查询,查询条件有时间纬度、用户纬度、状态纬度、搜> 索、分页........... 等等。正常开发你可能首先想到用一堆if判断再拼接SQL执行。这样会导致一个方法一堆> 代码,代码可读性、可维护性差、
于是模板引擎应运而生,mybatis更是佼佼者。通过在xml中编写if、for等操作实现复杂查询。
现在就有了这篇文章,在用hibernate的情况下使用mybatis 的xml解析实现复杂查询、
什么?你是说为什么不直接用mybatis?抱歉,接手项目就是用jpa、hibernate。难道要我用mybatis重新写上百个表映射实体对象吗?
依赖
在hibernate的项目中,引入mybatis的依赖
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.11</version>
</dependency>
代码封装
我这里直接将代码封装为spring的一个组件
import cn.com.agree.aweb.pojo.ParamObject;
import cn.com.agree.aweb.pojo.SqlResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.ParameterMode;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import java.util.ArrayList;
import java.util.List;
/**
* @author lingkang
* Created by 2022/10/10
* 之前发现使用freemarker进行SQL模板使用,个人觉得代码可读性低。
* hibernate缺少比较好的模板引擎,这里封装mybatis的模板引擎
* 编写复杂SQL时,可以通过 mybatis 的 xml 进行编写hibernate的sql语句
* 增加代码可读性和可维护性
* 对应模板id:命名空间.id
* 需要注意id的全局唯一性
*/
@Slf4j
@Component
public class MybatisTemplate {
private Configuration configuration = new Configuration();
@Autowired
private EntityManager em;
@Value("${spring.jpa.show-sql:false}")
private boolean showSql;
@PostConstruct
public void init() {
new XMLMapperBuilder(
MybatisTemplate.class.getClassLoader().getResourceAsStream("mapper/mapper.xml"),
configuration, null, null
).parse();// 解析
}
public Session getSession() {
return em.unwrap(Session.class);
}
/**
* @param id mapper.xml中的查询id,命名空间.id
* @param param 入参
* @param <T>
* @return
*/
public <T> List<T> selectForList(String id, ParamObject param) {
return selectForQuery(id, param).list();
}
/**
* @param id mapper.xml中的查询id,命名空间.id
* @param param 入参
* @return
*/
public Query selectForQuery(String id, ParamObject param) {
SqlResult sql = getSql(id, param);
Query query = getSession().createQuery(sql.getSql());
if (param != null && !param.isEmpty()) {
int i = 1;
for (Object val : sql.getParams()) {
query.setParameter(i, val);
i++;
}
}
return query;
}
public SqlResult getSql(String id, ParamObject param) {
MappedStatement mappedStatement = configuration.getMappedStatement(id);
BoundSql boundSql = mappedStatement.getBoundSql(param);
return getSqlResult(boundSql, mappedStatement, param);
}
private SqlResult getSqlResult(BoundSql boundSql, MappedStatement mappedStatement, ParamObject paramObject) {
SqlResult sqlResult = new SqlResult();
sqlResult.setSql(sqlParamAddIndex(boundSql.getSql()));
sqlResult.setParams(getParam(boundSql, mappedStatement, paramObject));
if (showSql) {
log.info(sqlResult.toString());
}
return sqlResult;
}
private List<Object> getParam(BoundSql boundSql, MappedStatement mappedStatement, ParamObject paramObject) {
List<Object> params = new ArrayList<>();
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
TypeHandlerRegistry typeHandlerRegistry = mappedStatement.getConfiguration().getTypeHandlerRegistry();
for (ParameterMapping parameterMapping : parameterMappings) {
if (parameterMapping.getMode() != ParameterMode.OUT) {
Object value;
String propertyName = parameterMapping.getProperty();
if (boundSql.hasAdditionalParameter(propertyName)) {
value = boundSql.getAdditionalParameter(propertyName);
} else if (paramObject == null) {
value = null;
} else if (typeHandlerRegistry.hasTypeHandler(paramObject.getClass())) {
value = paramObject;
} else {
MetaObject metaObject = configuration.newMetaObject(paramObject);
value = metaObject.getValue(propertyName);
}
params.add(value);
}
}
if ((paramObject == null || paramObject.isEmpty()) && !params.isEmpty()) {
throw new IllegalArgumentException("解析xml入参不匹配,xml需要的参数变量数:" + params.size() + " 入参:" + paramObject);
}
return params;
}
/**
* @param sql select user from user where id=? and status=?
* @return select user from user where id=?1 and status=?2
*/
private String sqlParamAddIndex(String sql) {
StringBuffer buffer = new StringBuffer(sql);
int i = 1, index = 0;
while ((index = buffer.indexOf("?", index)) != -1) {
buffer.insert(index + 1, i);
index++;
i++;
}
return buffer.toString();
}
}
import java.util.Arrays;
import java.util.HashMap;
/**
* @author lingkang
* Created by 2022/10/11
* 对参数简单封装
*/
public class ParamObject extends HashMap<String, Object> {
public ParamObject add(String key, String value) {
put(key, value);
return this;
}
public ParamObject addList(String key, Object... item) {
put(key, Arrays.asList(item));
return this;
}
}
import lombok.Data;
import java.util.List;
/**
* @author lingkang
* Created by 2022/10/10
*/
@Data
public class SqlResult {
private String sql;
private List<Object> params;
}
mapper.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="mapper">
<select id="getFileMenuAFA">
select po
from ServiceVersionResourceVersionToFilePO po where po.serviceVersionResourceVersion.serviceVersion.service.id is not null
and po.file.id is not null
and po.file.platformVersion.id is not null
<if test="tenantId">
and po.file.tenantId = #{tenantId}
</if>
</select>
<select id="getFileMenuAFE">
select po
from GroupVerToFilePO po
where po.groupVersion.group.id is not null
and po.file.id is not null
and po.file.platformVersion.id is not null
<if test="tenantId">
and po.file.tenantId = #{tenantId}
</if>
</select>
<select id="getFileList">
select
<!--是否使用分页-->
<if test="!usePage">
po
</if>
<if test="usePage">
count(*)
</if>
from FilePO po
where 1=1
<!--文件类型-->
<if test="fileType != null and fileType.size > 0">
and po.type in
<foreach collection="fileType" open="(" close=")" item="item" separator=",">
#{item}
</foreach>
</if>
<!-- 租户 -->
<if test="tenantId">
and po.tenantId = #{tenantId}
</if>
<!-- 类型:服务、平台 -->
<if test="type">
<if test="'platform' == type">
and po.platformVersion.platform.id = #{id}
</if>
<if test="'platformVersion' == type">
and po.platformVersion.id = #{id}
</if>
<if test="'system' == type">
<if test="id.endsWith('-afa')">
and po.id in (select svrvfp.file.id
from ServiceVersionResourceVersionToFilePO svrvfp
where svrvfp.serviceVersionResourceVersion.serviceVersion.service.system.id = #{id})
</if>
<if test="!id.endsWith('-afa')">
and po.id in
(select gvfp.file.id from GroupVerToFilePO gvfp where gvfp.groupVersion.group.system.id = #{id})
</if>
</if>
<if test="'service' == type">
<if test="id.startsWith('grp')">
and po.id in (select gvfp.file.id from GroupVerToFilePO gvfp where gvfp.groupVersion.group.id = #{id})
</if>
<if test="!id.startsWith('grp')">
and po.id in (select svrvfp.file.id
from ServiceVersionResourceVersionToFilePO svrvfp
where svrvfp.serviceVersionResourceVersion.serviceVersion.service.id = #{id})
</if>
</if>
</if>
<!-- 搜索 -->
<if test="search != null and search != ''">
and (po.name like #{search}
or po.customName like #{search}
or po.des like #{search}
or
po.platformVersion.platform.name like #{search})
</if>
<if test="!usePage">
order by po.createTime desc
</if>
</select>
</mapper>
调用
@Autowired
private MybatisTemplate mybatisTemplate;
TenantVo tenant = UserUtils.getCurrentTenant();
ParamObject conditions = new ParamObject();
if (tenant != null) {
conditions.put("tenantId", tenant.getId());
}
// 注意id为 命名空间.id,也可以直接用id,只要复核mybatis 的规范即可
List<ServiceVersionResourceVersionToFilePO> afa = mybatisTemplate.selectForList("mapper.getFileMenuAFA", conditions);
jpa整合mybatis模板解析、hibernate整合mybatis模板解析的更多相关文章
- Hibernate和Mybatis的对比
http://blog.csdn.net/jiuqiyuliang/article/details/45378065 Hibernate与Mybatis对比 1. 简介 Hibernate:Hiber ...
- Spring与Hibernate、Mybatis整合
在Web项目中一般会把各个web框架结合在一起使用,比如spring+hibernate,spring+ibatis等,如此以来将其他的框架整合到spring中来,便有些少许的不便,当然spring已 ...
- Java Web开发之Spring | SpringMvc | Mybatis | Hibernate整合、配置、使用
1.Spring与Mybatis整合 web.xml: <?xml version="1.0" encoding="UTF-8"?> <web ...
- SSM(Spring+SpringMVC+Mybatis)框架环境搭建(整合步骤)(一)
1. 前言 最近在写毕设过程中,重新梳理了一遍SSM框架,特此记录一下. 附上源码:https://gitee.com/niceyoo/jeenotes-ssm 2. 概述 在写代码之前我们先了解一下 ...
- JPA、SpringData JPA 、Hibernate和Mybatis 的区别和联系
一.JPA 概述 1. Java Persistence API(Java 持久层 API):用于对象持久化的 API 2. 作用:使得应用程序以统一的方式访问持久层 3. 前言中提到了 Hibern ...
- 【SpringMVC学习04】Spring、MyBatis和SpringMVC的整合
前两篇springmvc的文章中都没有和mybatis整合,都是使用静态数据来模拟的,但是springmvc开发不可能不整合mybatis,另外mybatis和spring的整合我之前学习mybati ...
- (转)SpringMVC学习(四)——Spring、MyBatis和SpringMVC的整合
http://blog.csdn.net/yerenyuan_pku/article/details/72231763 之前我整合了Spring和MyBatis这两个框架,不会的可以看我的文章MyBa ...
- 【Java EE 学习 79 下】【动态SQL】【mybatis和spring的整合】
一.动态SQL 什么是动态SQL,就是在不同的条件下,sql语句不相同的意思,曾经在“酒店会员管理系统”中写过大量的多条件查询,那是在SSH的环境中,所以只能在代码中进行判断,以下是其中一个多条件查询 ...
- 由“单独搭建Mybatis”到“Mybatis与Spring的整合/集成”
在J2EE领域,Hibernate与Mybatis是大家常用的持久层框架,它们各有特点,在持久层框架中处于领导地位. 本文主要介绍Mybatis(对于较小型的系统,特别是报表较多的系统,个人偏向Myb ...
- Spring3 + Spring MVC+ Mybatis 3+Mysql 项目整合(注解及源码)
Spring3 + Spring MVC+ Mybatis 3+Mysql 项目整合(注解及源码) 备注: 之前在Spring3 + Spring MVC+ Mybatis 3+Mysql 项目整合中 ...
随机推荐
- Linux升级至glibc-2.14步骤
Linux升级至glibc-2.14步骤 查看gcc版本命令: strings /lib64/libc.so.6 |grep GLIBC_ glibc安装 首先, 点击此处下载glibc2.14下载, ...
- Go语言系列——11-数组和切片、12-可变参数函数、13-Maps、14-字符串、15-指针、16-结构体、17-方法、18-接口(一)、19-接口(二)、19-自定义集合类型、20-并发入门
文章目录 11-数组和切片 数组 数组的声明 数组是值类型 数组的长度 使用 range 迭代数组 多维数组 切片 创建一个切片 切片的修改 切片的长度和容量 使用 make 创建一个切片 追加切片元 ...
- android图片缩放双击旋转效果
需要jar源码的请留言吧. 部分源码 demo下载地址 package uk.co.senab.photoview.sample; import android.app.ListActivity ...
- 【sqli-labs】学习--待续
预备知识: 数字型注入: 这种sql语句中处理的是整型,不需要使用单引号来闭合变量的值. 首先输入id=1',此时因为不是整型,sql语句会执行出错,抛出异常. 然后输入id=1 and 1=1,此时 ...
- 从零用VitePress搭建博客教程(2) –VitePress默认首页和头部导航、左侧导航配置
2. 从零用VitePress搭建博客教程(2) –VitePress默认首页和头部导航.左侧导航配置 接上一节: 从零用VitePress搭建博客教程(1) – VitePress的安装和运行 四. ...
- 产品代码都给你看了,可别再说不会DDD(八):应用服务与领域服务
这是一个讲解DDD落地的文章系列,作者是<实现领域驱动设计>的译者滕云.本文章系列以一个真实的并已成功上线的软件项目--码如云(https://www.mryqr.com)为例,系统性地讲 ...
- KubeEdge v1.15.0发布!新增5大特性
本文分享自华为云社区<KubeEdge v1.15.0发布!新增Windows 边缘节点支持,基于物模型的设备管理,DMI 数据面支持等功能>,作者:云容器大未来 . 北京时间2023年1 ...
- 银河麒麟V10 修改文件夹权限
并不建议修改系统文件夹的权限,防止终端失效 指令:获取所有权限 指令:写入可执行权限 chmod +x filename//filename 是文件路径 TRANSLATE with x Englis ...
- JS异步任务的并行、串行,以及二者结合
让多个异步任务按照我们的想法执行,是开发中常见的需求.今天我们就来捋一下,如何让多个异步任务并行,串行,以及并行串行相结合. 一.并行 并行是使用最多的方式,多个相互间没有依赖关系的异步任务,并行执行 ...
- spring---面向切面(AOP @Pointcut 表达式篇)
AOP(面向切面编程),可以说是OOP(面向对象编程)的补充和完善.OOP引入封装.继承和多态性等概念来建立一种对象层次结构,用以模拟公共行为的一个集合. 当我们需要为分散的对象引入公共行为的时候,O ...