springboot3.2.4+Mybatis-plus在graalvm21环境下打包exe

2024-03-31 22:52

本文主要是介绍springboot3.2.4+Mybatis-plus在graalvm21环境下打包exe,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

springboot3.2.4+Mybatis-plus在graalvm21环境下打包exe

  • 前提条件为之前已经能直接打包springboot3.2.4项目了
  • 然后在此基础上接入Mybatis-plus,然后能够正常进行打包exe并且执行,参考之前的文章进行打包

核心配置如下

package com.example.demo.config;import com.baomidou.mybatisplus.annotation.IEnum;
import com.baomidou.mybatisplus.core.MybatisParameterHandler;
import com.baomidou.mybatisplus.core.MybatisXMLLanguageDriver;
import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.handlers.CompositeEnumTypeHandler;
import com.baomidou.mybatisplus.core.handlers.MybatisEnumTypeHandler;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.core.toolkit.support.SerializedLambda;
import com.baomidou.mybatisplus.extension.handlers.FastjsonTypeHandler;
import com.baomidou.mybatisplus.extension.handlers.GsonTypeHandler;
import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.annotations.DeleteProvider;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.annotations.UpdateProvider;
import org.apache.ibatis.cache.decorators.FifoCache;
import org.apache.ibatis.cache.decorators.LruCache;
import org.apache.ibatis.cache.decorators.SoftCache;
import org.apache.ibatis.cache.decorators.WeakCache;
import org.apache.ibatis.cache.impl.PerpetualCache;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.executor.statement.BaseStatementHandler;
import org.apache.ibatis.executor.statement.RoutingStatementHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.javassist.util.proxy.ProxyFactory;
import org.apache.ibatis.javassist.util.proxy.RuntimeSupport;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.commons.JakartaCommonsLoggingImpl;
import org.apache.ibatis.logging.jdk14.Jdk14LoggingImpl;
import org.apache.ibatis.logging.log4j2.Log4j2Impl;
import org.apache.ibatis.logging.nologging.NoLoggingImpl;
import org.apache.ibatis.logging.slf4j.Slf4jImpl;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.reflection.TypeParameterResolver;
import org.apache.ibatis.scripting.defaults.RawLanguageDriver;
import org.apache.ibatis.scripting.xmltags.XMLLanguageDriver;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.aot.BeanFactoryInitializationAotContribution;
import org.springframework.beans.factory.aot.BeanFactoryInitializationAotProcessor;
import org.springframework.beans.factory.aot.BeanRegistrationExcludeFilter;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor;
import org.springframework.beans.factory.support.RegisteredBean;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportRuntimeHints;
import org.springframework.core.ResolvableType;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;/*** @author lyk* @since 2024-03-30*/
@Configuration(proxyBeanMethods = false)
@ImportRuntimeHints(MyBatisNativeConfiguration.MyBaitsRuntimeHintsRegistrar.class)
public class MyBatisNativeConfiguration {@BeanMyBatisBeanFactoryInitializationAotProcessor myBatisBeanFactoryInitializationAotProcessor() {return new MyBatisBeanFactoryInitializationAotProcessor();}@Beanstatic MyBatisMapperFactoryBeanPostProcessor myBatisMapperFactoryBeanPostProcessor() {return new MyBatisMapperFactoryBeanPostProcessor();}static class MyBaitsRuntimeHintsRegistrar implements RuntimeHintsRegistrar {@Overridepublic void registerHints(RuntimeHints hints, ClassLoader classLoader) {Stream.of(RawLanguageDriver.class,// TODO 增加了MybatisXMLLanguageDriver.classXMLLanguageDriver.class, MybatisXMLLanguageDriver.class,RuntimeSupport.class,ProxyFactory.class,Slf4jImpl.class,Log.class,JakartaCommonsLoggingImpl.class,Log4j2Impl.class,Jdk14LoggingImpl.class,StdOutImpl.class,NoLoggingImpl.class,SqlSessionFactory.class,PerpetualCache.class,FifoCache.class,LruCache.class,SoftCache.class,WeakCache.class,//TODO 增加了MybatisSqlSessionFactoryBean.classSqlSessionFactoryBean.class, MybatisSqlSessionFactoryBean.class,ArrayList.class,HashMap.class,TreeSet.class,HashSet.class).forEach(x -> hints.reflection().registerType(x, MemberCategory.values()));Stream.of("org/apache/ibatis/builder/xml/*.dtd","org/apache/ibatis/builder/xml/*.xsd").forEach(hints.resources()::registerPattern);hints.serialization().registerType(SerializedLambda.class);hints.serialization().registerType(SFunction.class);hints.serialization().registerType(java.lang.invoke.SerializedLambda.class);hints.reflection().registerType(SFunction.class);hints.reflection().registerType(SerializedLambda.class);hints.reflection().registerType(java.lang.invoke.SerializedLambda.class);hints.proxies().registerJdkProxy(StatementHandler.class);hints.proxies().registerJdkProxy(Executor.class);hints.proxies().registerJdkProxy(ResultSetHandler.class);hints.proxies().registerJdkProxy(ParameterHandler.class);//        hints.reflection().registerType(MybatisPlusInterceptor.class);hints.reflection().registerType(AbstractWrapper.class,MemberCategory.values());hints.reflection().registerType(LambdaQueryWrapper.class,MemberCategory.values());hints.reflection().registerType(LambdaUpdateWrapper.class,MemberCategory.values());hints.reflection().registerType(UpdateWrapper.class,MemberCategory.values());hints.reflection().registerType(QueryWrapper.class,MemberCategory.values());hints.reflection().registerType(BoundSql.class,MemberCategory.DECLARED_FIELDS);hints.reflection().registerType(RoutingStatementHandler.class,MemberCategory.DECLARED_FIELDS);hints.reflection().registerType(BaseStatementHandler.class,MemberCategory.DECLARED_FIELDS);hints.reflection().registerType(MybatisParameterHandler.class,MemberCategory.DECLARED_FIELDS);hints.reflection().registerType(IEnum.class,MemberCategory.INVOKE_PUBLIC_METHODS);// register typeHandlerhints.reflection().registerType(CompositeEnumTypeHandler.class, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS);hints.reflection().registerType(FastjsonTypeHandler.class, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS);hints.reflection().registerType(GsonTypeHandler.class, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS);hints.reflection().registerType(JacksonTypeHandler.class, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS);hints.reflection().registerType(MybatisEnumTypeHandler.class, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS);}}static class MyBatisBeanFactoryInitializationAotProcessorimplements BeanFactoryInitializationAotProcessor, BeanRegistrationExcludeFilter {private final Set<Class<?>> excludeClasses = new HashSet<>();MyBatisBeanFactoryInitializationAotProcessor() {excludeClasses.add(MapperScannerConfigurer.class);}@Override public boolean isExcludedFromAotProcessing(RegisteredBean registeredBean) {return excludeClasses.contains(registeredBean.getBeanClass());}@Overridepublic BeanFactoryInitializationAotContribution processAheadOfTime(ConfigurableListableBeanFactory beanFactory) {String[] beanNames = beanFactory.getBeanNamesForType(MapperFactoryBean.class);if (beanNames.length == 0) {return null;}return (context, code) -> {RuntimeHints hints = context.getRuntimeHints();for (String beanName : beanNames) {BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName.substring(1));PropertyValue mapperInterface = beanDefinition.getPropertyValues().getPropertyValue("mapperInterface");if (mapperInterface != null && mapperInterface.getValue() != null) {Class<?> mapperInterfaceType = (Class<?>) mapperInterface.getValue();if (mapperInterfaceType != null) {registerReflectionTypeIfNecessary(mapperInterfaceType, hints);hints.proxies().registerJdkProxy(mapperInterfaceType);hints.resources().registerPattern(mapperInterfaceType.getName().replace('.', '/').concat(".xml"));registerMapperRelationships(mapperInterfaceType, hints);}}}};}private void registerMapperRelationships(Class<?> mapperInterfaceType, RuntimeHints hints) {Method[] methods = ReflectionUtils.getAllDeclaredMethods(mapperInterfaceType);for (Method method : methods) {if (method.getDeclaringClass() != Object.class) {ReflectionUtils.makeAccessible(method);registerSqlProviderTypes(method, hints, SelectProvider.class, SelectProvider::value, SelectProvider::type);registerSqlProviderTypes(method, hints, InsertProvider.class, InsertProvider::value, InsertProvider::type);registerSqlProviderTypes(method, hints, UpdateProvider.class, UpdateProvider::value, UpdateProvider::type);registerSqlProviderTypes(method, hints, DeleteProvider.class, DeleteProvider::value, DeleteProvider::type);Class<?> returnType = MyBatisMapperTypeUtils.resolveReturnClass(mapperInterfaceType, method);registerReflectionTypeIfNecessary(returnType, hints);MyBatisMapperTypeUtils.resolveParameterClasses(mapperInterfaceType, method).forEach(x -> registerReflectionTypeIfNecessary(x, hints));}}}@SafeVarargsprivate <T extends Annotation> void registerSqlProviderTypes(Method method, RuntimeHints hints, Class<T> annotationType, Function<T, Class<?>>... providerTypeResolvers) {for (T annotation : method.getAnnotationsByType(annotationType)) {for (Function<T, Class<?>> providerTypeResolver : providerTypeResolvers) {registerReflectionTypeIfNecessary(providerTypeResolver.apply(annotation), hints);}}}private void registerReflectionTypeIfNecessary(Class<?> type, RuntimeHints hints) {if (!type.isPrimitive() && !type.getName().startsWith("java")) {hints.reflection().registerType(type, MemberCategory.values());}}}static class MyBatisMapperTypeUtils {private MyBatisMapperTypeUtils() {// NOP}static Class<?> resolveReturnClass(Class<?> mapperInterface, Method method) {Type resolvedReturnType = TypeParameterResolver.resolveReturnType(method, mapperInterface);return typeToClass(resolvedReturnType, method.getReturnType());}static Set<Class<?>> resolveParameterClasses(Class<?> mapperInterface, Method method) {return Stream.of(TypeParameterResolver.resolveParamTypes(method, mapperInterface)).map(x -> typeToClass(x, x instanceof Class ? (Class<?>) x : Object.class)).collect(Collectors.toSet());}private static Class<?> typeToClass(Type src, Class<?> fallback) {Class<?> result = null;if (src instanceof Class<?>) {if (((Class<?>) src).isArray()) {result = ((Class<?>) src).getComponentType();} else {result = (Class<?>) src;}} else if (src instanceof ParameterizedType) {ParameterizedType parameterizedType = (ParameterizedType) src;int index = (parameterizedType.getRawType() instanceof Class&& Map.class.isAssignableFrom((Class<?>) parameterizedType.getRawType())&& parameterizedType.getActualTypeArguments().length > 1) ? 1 : 0;Type actualType = parameterizedType.getActualTypeArguments()[index];result = typeToClass(actualType, fallback);}if (result == null) {result = fallback;}return result;}}static class MyBatisMapperFactoryBeanPostProcessor implements MergedBeanDefinitionPostProcessor, BeanFactoryAware {private static final org.apache.commons.logging.Log LOG = LogFactory.getLog(MyBatisMapperFactoryBeanPostProcessor.class);private static final String MAPPER_FACTORY_BEAN = "org.mybatis.spring.mapper.MapperFactoryBean";private ConfigurableBeanFactory beanFactory;@Overridepublic void setBeanFactory(BeanFactory beanFactory) {this.beanFactory = (ConfigurableBeanFactory) beanFactory;}@Overridepublic void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {if (ClassUtils.isPresent(MAPPER_FACTORY_BEAN, this.beanFactory.getBeanClassLoader())) {resolveMapperFactoryBeanTypeIfNecessary(beanDefinition);}}private void resolveMapperFactoryBeanTypeIfNecessary(RootBeanDefinition beanDefinition) {if (!beanDefinition.hasBeanClass() || !MapperFactoryBean.class.isAssignableFrom(beanDefinition.getBeanClass())) {return;}if (beanDefinition.getResolvableType().hasUnresolvableGenerics()) {Class<?> mapperInterface = getMapperInterface(beanDefinition);if (mapperInterface != null) {// Exposes a generic type information to context for prevent early initializingConstructorArgumentValues constructorArgumentValues = new ConstructorArgumentValues();constructorArgumentValues.addGenericArgumentValue(mapperInterface);beanDefinition.setConstructorArgumentValues(constructorArgumentValues);beanDefinition.setTargetType(ResolvableType.forClassWithGenerics(beanDefinition.getBeanClass(), mapperInterface));}}}private Class<?> getMapperInterface(RootBeanDefinition beanDefinition) {try {return (Class<?>) beanDefinition.getPropertyValues().get("mapperInterface");}catch (Exception e) {LOG.debug("Fail getting mapper interface type.", e);return null;}}}
}
package com.example.demo.config;import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/*** @author lyk* @since 2024-03-30*/
@Configuration
//TODO 如果使用这个方式的话,记得一定要指定sqlSessionTemplateRef或sqlSessionFactoryRef https://github.com/mybatis/spring-boot-starter/wiki/Quick-Start-for-building-native-image#how-to-use-mapperscan
@MapperScan(basePackages = "com.example.demo.mapper", sqlSessionTemplateRef = "sqlSessionTemplate")
public class MybatisPlusConfig {@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor(){MybatisPlusInterceptor plusInterceptor = new MybatisPlusInterceptor();//plusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));//TODO 3.5.3.1 以下插件多的话,可能会报异常,这个在最新版本修改.  https://github.com/baomidou/mybatis-plus/issues/5532
//        plusInterceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
//        plusInterceptor.addInnerInterceptor(new IllegalSQLInnerInterceptor());
//        plusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());return plusInterceptor;}}

demo地址如下

https://gitee.com/lgbisha/springboot3-mybatis-plus/tree/master

这篇关于springboot3.2.4+Mybatis-plus在graalvm21环境下打包exe的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/865573

相关文章

MyBatis-Plus 中 nested() 与 and() 方法详解(最佳实践场景)

《MyBatis-Plus中nested()与and()方法详解(最佳实践场景)》在MyBatis-Plus的条件构造器中,nested()和and()都是用于构建复杂查询条件的关键方法,但... 目录MyBATis-Plus 中nested()与and()方法详解一、核心区别对比二、方法详解1.and()

SQLite3 在嵌入式C环境中存储音频/视频文件的最优方案

《SQLite3在嵌入式C环境中存储音频/视频文件的最优方案》本文探讨了SQLite3在嵌入式C环境中存储音视频文件的优化方案,推荐采用文件路径存储结合元数据管理,兼顾效率与资源限制,小文件可使用B... 目录SQLite3 在嵌入式C环境中存储音频/视频文件的专业方案一、存储策略选择1. 直接存储 vs

python常见环境管理工具超全解析

《python常见环境管理工具超全解析》在Python开发中,管理多个项目及其依赖项通常是一个挑战,下面:本文主要介绍python常见环境管理工具的相关资料,文中通过代码介绍的非常详细,需要的朋友... 目录1. conda2. pip3. uvuv 工具自动创建和管理环境的特点4. setup.py5.

Python中使用uv创建环境及原理举例详解

《Python中使用uv创建环境及原理举例详解》uv是Astral团队开发的高性能Python工具,整合包管理、虚拟环境、Python版本控制等功能,:本文主要介绍Python中使用uv创建环境及... 目录一、uv工具简介核心特点:二、安装uv1. 通过pip安装2. 通过脚本安装验证安装:配置镜像源(可

MyBatis ResultMap 的基本用法示例详解

《MyBatisResultMap的基本用法示例详解》在MyBatis中,resultMap用于定义数据库查询结果到Java对象属性的映射关系,本文给大家介绍MyBatisResultMap的基本... 目录MyBATis 中的 resultMap1. resultMap 的基本语法2. 简单的 resul

Mybatis的分页实现方式

《Mybatis的分页实现方式》MyBatis的分页实现方式主要有以下几种,每种方式适用于不同的场景,且在性能、灵活性和代码侵入性上有所差异,对Mybatis的分页实现方式感兴趣的朋友一起看看吧... 目录​1. 原生 SQL 分页(物理分页)​​2. RowBounds 分页(逻辑分页)​​3. Page

MyBatis Plus 中 update_time 字段自动填充失效的原因分析及解决方案(最新整理)

《MyBatisPlus中update_time字段自动填充失效的原因分析及解决方案(最新整理)》在使用MyBatisPlus时,通常我们会在数据库表中设置create_time和update... 目录前言一、问题现象二、原因分析三、总结:常见原因与解决方法对照表四、推荐写法前言在使用 MyBATis

Mybatis Plus Join使用方法示例详解

《MybatisPlusJoin使用方法示例详解》:本文主要介绍MybatisPlusJoin使用方法示例详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,... 目录1、pom文件2、yaml配置文件3、分页插件4、示例代码:5、测试代码6、和PageHelper结合6

MyBatis设计SQL返回布尔值(Boolean)的常见方法

《MyBatis设计SQL返回布尔值(Boolean)的常见方法》这篇文章主要为大家详细介绍了MyBatis设计SQL返回布尔值(Boolean)的几种常见方法,文中的示例代码讲解详细,感兴趣的小伙伴... 目录方案一:使用COUNT查询存在性(推荐)方案二:条件表达式直接返回布尔方案三:存在性检查(EXI

python获取cmd环境变量值的实现代码

《python获取cmd环境变量值的实现代码》:本文主要介绍在Python中获取命令行(cmd)环境变量的值,可以使用标准库中的os模块,需要的朋友可以参考下... 前言全局说明在执行py过程中,总要使用到系统环境变量一、说明1.1 环境:Windows 11 家庭版 24H2 26100.4061