草庐IT

jpa整合mybatis模板解析、hibernate整合mybatis模板解析

lingkang 2023-04-16 原文

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模板解析的更多相关文章

  1. Ruby 解析字符串 - 2

    我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?

  2. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  3. ruby - 用逗号、双引号和编码解析 csv - 2

    我正在使用ruby​​1.9解析以下带有MacRoman字符的csv文件#encoding:ISO-8859-1#csv_parse.csvName,main-dialogue"Marceu","Giveittohimóhe,hiswife."我做了以下解析。require'csv'input_string=File.read("../csv_parse.rb").force_encoding("ISO-8859-1").encode("UTF-8")#=>"Name,main-dialogue\r\n\"Marceu\",\"Giveittohim\x97he,hiswife.\"\

  4. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

  5. ruby-on-rails - 我更新了 ruby​​ gems,现在到处都收到解析树错误和弃用警告! - 2

    简而言之错误:NOTE:Gem::SourceIndex#add_specisdeprecated,useSpecification.add_spec.Itwillberemovedonorafter2011-11-01.Gem::SourceIndex#add_speccalledfrom/opt/local/lib/ruby/site_ruby/1.8/rubygems/source_index.rb:91./opt/local/lib/ruby/gems/1.8/gems/rails-2.3.8/lib/rails/gem_dependency.rb:275:in`==':und

  6. ruby-on-rails - Mandrill API 模板 - 2

    我正在使用Mandrill的RubyAPIGem并使用以下简单的测试模板:testastic按照Heroku指南中的示例,我有以下Ruby代码:require'mandrill'm=Mandrill::API.newrendered=m.templates.render'test-template',[{:header=>'someheadertext',:main_section=>'Themaincontentblock',:footer=>'asdf'}]mail(:to=>"JaysonLane",:subject=>"TestEmail")do|format|format.h

  7. ruby - Chef Ruby 遍历 .erb 模板文件中的属性 - 2

    所以这可能有点令人困惑,但请耐心等待。简而言之,我想遍历具有特定键值的所有属性,然后如果值不为空,则将它们插入到模板中。这是我的代码:属性:#===DefaultfileConfigurations#default['elasticsearch']['default']['ES_USER']=''default['elasticsearch']['default']['ES_GROUP']=''default['elasticsearch']['default']['ES_HEAP_SIZE']=''default['elasticsearch']['default']['MAX_OP

  8. ruby - 用 YAML.load 解析 json 安全吗? - 2

    我正在使用ruby2.1.0我有一个json文件。例如:test.json{"item":[{"apple":1},{"banana":2}]}用YAML.load加载这个文件安全吗?YAML.load(File.read('test.json'))我正在尝试加载一个json或yaml格式的文件。 最佳答案 YAML可以加载JSONYAML.load('{"something":"test","other":4}')=>{"something"=>"test","other"=>4}JSON将无法加载YAML。JSON.load("

  9. ruby - 如何使用 Nokogiri 解析纯 HTML 表格? - 2

    我想用Nokogiri解析HTML页面。页面的一部分有一个表,它没有使用任何特定的ID。是否可以提取如下内容:Today,3,455,34Today,1,1300,3664Today,10,100000,3444,Yesterday,3454,5656,3Yesterday,3545,1000,10Yesterday,3411,36223,15来自这个HTML:TodayYesterdayQntySizeLengthLengthSizeQnty345534345456563113003664354510001010100000344434113622315

  10. python - 帮我找到合适的 ruby​​/python 解析器生成器 - 2

    我使用的第一个解析器生成器是Parse::RecDescent,它的指南/教程很棒,但它最有用的功能是它的调试工具,特别是tracing功能(通过将$RD_TRACE设置为1来激活)。我正在寻找可以帮助您调试其规则的解析器生成器。问题是,它必须用python或ruby​​编写,并且具有详细模式/跟踪模式或非常有用的调试技术。有人知道这样的解析器生成器吗?编辑:当我说调试时,我并不是指调试python或ruby​​。我指的是调试解析器生成器,查看它在每一步都在做什么,查看它正在读取的每个字符,它试图匹配的规则。希望你明白这一点。赏金编辑:要赢得赏金,请展示一个解析器生成器框架,并说明它的

随机推荐