├── .gitignore ├── LICENSE ├── README.md ├── README.zh-CN.md ├── bach-update.md ├── common-util ├── pom.xml └── src │ ├── main │ └── java │ │ └── com │ │ └── vonchange │ │ └── common │ │ └── util │ │ ├── Assert.java │ │ ├── ClazzUtils.java │ │ ├── ConvertUtil.java │ │ ├── JsonUtil.java │ │ ├── MD5Util.java │ │ ├── MarkdownUtil.java │ │ ├── StringPool.java │ │ ├── Three.java │ │ ├── TimeUtil.java │ │ ├── Two.java │ │ ├── UtilAll.java │ │ ├── bean │ │ ├── BeanUtil.java │ │ ├── MethodAccessData.java │ │ └── convert │ │ │ ├── Converter.java │ │ │ ├── TypeConversionException.java │ │ │ ├── TypeConvertCommon.java │ │ │ ├── TypeConverter.java │ │ │ └── impl │ │ │ ├── BigDecimalConverter.java │ │ │ ├── BigIntegerConverter.java │ │ │ ├── BooleanConverter.java │ │ │ ├── ByteArrayConverter.java │ │ │ ├── ByteConverter.java │ │ │ ├── CharacterConverter.java │ │ │ ├── DateConverter.java │ │ │ ├── DoubleConverter.java │ │ │ ├── FloatConverter.java │ │ │ ├── IntegerConverter.java │ │ │ ├── LocalDateConverter.java │ │ │ ├── LocalDateTimeConverter.java │ │ │ ├── LocalTimeConverter.java │ │ │ ├── LongConverter.java │ │ │ ├── NumberConverter.java │ │ │ ├── ShortConverter.java │ │ │ └── StringConverter.java │ │ ├── exception │ │ ├── CommonRuntimeException.java │ │ ├── EnumUtilErrorCode.java │ │ ├── ErrorMsg.java │ │ ├── ParseException.java │ │ └── UtilException.java │ │ ├── io │ │ ├── CharArraySequence.java │ │ ├── FastCharArrayWriter.java │ │ ├── FastCharBuffer.java │ │ └── UnicodeInputStream.java │ │ ├── map │ │ ├── HashMapFluent.java │ │ ├── VMap.java │ │ └── VarMap.java │ │ └── model │ │ └── BaseField.java │ └── test │ ├── java │ ├── AsmTest.java │ ├── BaseModel.java │ ├── MarkdownUtilTest.java │ ├── RootModel.java │ ├── Test1.java │ ├── Test2.java │ └── UserModel.java │ └── resources │ └── config │ └── test.md ├── curd-repository.md ├── easy-dynamic-sql.md ├── jdbc-mybatis ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── vonchange │ └── jdbc │ ├── annotation │ ├── ColumnNot.java │ ├── InsertOnlyProperty.java │ └── InsertReturn.java │ ├── client │ ├── CrudClient.java │ ├── DefaultJdbcClient.java │ └── JdbcClient.java │ ├── config │ ├── ConstantJdbc.java │ ├── EnumMappedClass.java │ ├── EnumNameQueryType.java │ ├── EnumRWType.java │ └── EnumSqlRead.java │ ├── core │ ├── CrudUtil.java │ ├── DefaultCrudClient.java │ ├── JdbcLogUtil.java │ └── MyJdbcTemplate.java │ ├── count │ └── CountSqlParser.java │ ├── mapper │ ├── AbstractPageWork.java │ ├── BeanInsertMapper.java │ ├── BeanMapper.java │ ├── BigDataBeanMapper.java │ └── ScalarMapper.java │ ├── model │ ├── BaseEntityField.java │ ├── BaseSqlParam.java │ ├── DataSourceWrapper.java │ ├── EntityField.java │ ├── EntityInfo.java │ ├── EnumCondition.java │ ├── EnumStep.java │ ├── QueryColumn.java │ ├── SqlMatch.java │ └── SqlParam.java │ ├── mybatis │ └── MybatisJdbcTemplate.java │ └── util │ ├── ConvertMap.java │ ├── EntityUtil.java │ ├── JdbcUtil.java │ ├── MybatisTpl.java │ ├── NameQueryUtil.java │ ├── OrmUtil.java │ └── SqlFill.java ├── method-name-query.md ├── multi-datasource.md ├── mybatis-sql-extend-test ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── vonchange │ │ │ └── mybatis │ │ │ ├── MybatisSqlExtendTestApplication.java │ │ │ └── test │ │ │ └── config │ │ │ ├── BaseCrudMapper.java │ │ │ ├── SimpleLanguageDriver.java │ │ │ ├── UserBaseDO.java │ │ │ └── UserMapper.java │ └── resources │ │ ├── application-h2.yml │ │ ├── application.yml │ │ ├── db-init.sql │ │ └── mapper │ │ └── UserMapper.md │ └── test │ └── java │ └── com │ └── vonchange │ └── mybatis │ └── test │ └── MybatisSqlExtendTest.java ├── mybatis-sql-extend.md ├── mybatis-sql-extend ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── vonchange │ └── mybatis │ ├── dialect │ ├── Dialect.java │ ├── H2MySqlDialect.java │ ├── LikeTemplate.java │ ├── MariaDialect.java │ ├── MySQLDialect.java │ ├── OracleDialect.java │ ├── OracleLowDialect.java │ └── PostgresDialect.java │ ├── exception │ ├── EnumJdbcErrorCode.java │ └── JdbcMybatisRuntimeException.java │ ├── language │ └── MybatisSqlLanguageUtil.java │ ├── sql │ ├── AnalyeNamed.java │ ├── DynamicSql.java │ └── SqlParamResult.java │ └── tpl │ └── MyOgnl.java ├── pom.xml ├── recommend.md ├── spring-data-jdbc-demo ├── .gitignore ├── README.md ├── pom.xml └── src │ ├── main │ ├── java │ │ ├── com │ │ │ └── vonchange │ │ │ │ └── common │ │ │ │ ├── App.java │ │ │ │ ├── config │ │ │ │ ├── MyDialectResolver.java │ │ │ │ └── MybatisQuerySupportConfig.java │ │ │ │ ├── dao │ │ │ │ └── UserRepository.java │ │ │ │ └── domain │ │ │ │ ├── ReqUser.java │ │ │ │ ├── UserDTO.java │ │ │ │ └── UserInfoDO.java │ │ └── org │ │ │ └── springframework │ │ │ └── data │ │ │ └── jdbc │ │ │ └── core │ │ │ └── convert │ │ │ └── BasicJdbcConverter.java │ └── resources │ │ ├── META-INF │ │ └── spring.factories │ │ ├── application-h2.yml │ │ ├── application-mysql.yml │ │ ├── application.properties │ │ ├── application.yml │ │ ├── log4j2.xml │ │ └── sql │ │ └── user.md │ └── test │ ├── java │ └── com │ │ └── vonchange │ │ └── common │ │ └── AppTest.java │ └── resources │ └── db-init.sql ├── spring-data-jdbc-mybatis-demo ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── vonchange │ │ │ └── nine │ │ │ └── demo │ │ │ ├── JdbcMybatisTestApplication.java │ │ │ ├── config │ │ │ └── DBConfig.java │ │ │ ├── dao │ │ │ ├── IUserInfoCrudClientDao.java │ │ │ ├── UserInfoCrudClientDao.java │ │ │ ├── UserInfoMethodDao.java │ │ │ ├── UserInfoQueryDao.java │ │ │ └── UserInfoRepository.java │ │ │ ├── domain │ │ │ ├── BaseDO.java │ │ │ ├── SearchParam.java │ │ │ └── UserInfoDO.java │ │ │ └── util │ │ │ └── H2DBFunctionExt.java │ └── resources │ │ └── sql │ │ ├── UserInfoCrudClientDao.md │ │ ├── UserInfoQueryDao.md │ │ └── UserInfoRepository.md │ └── test │ ├── java │ └── com │ │ └── vonchange │ │ └── nine │ │ └── demo │ │ └── dao │ │ ├── CrudClientTest.java │ │ ├── UserExample.java │ │ ├── UserInfoMethodDaoTest.java │ │ ├── UserInfoQueryDaoTest.java │ │ └── UserInfoRepositoryTest.java │ └── resources │ ├── application-h2.yml │ ├── application-mysql.yml │ ├── application.properties │ ├── application.yml │ ├── db-init.sql │ ├── log4j2.xml │ └── sql │ └── CrudClientTest.md └── spring-data-jdbc-mybatis ├── pom.xml └── src └── main ├── java └── com │ └── vonchange │ └── jdbc │ └── mybatis │ └── core │ ├── config │ ├── BindParameterWrapper.java │ ├── ConfigInfo.java │ ├── EnableJdbcRepositories.java │ ├── JdbcConfiguration.java │ ├── JdbcRepositoriesRegistrar.java │ └── JdbcRepositoryConfigExtension.java │ ├── query │ ├── BatchUpdate.java │ ├── DataSourceKey.java │ └── Modifying.java │ └── support │ ├── CrudExtendRepository.java │ ├── JdbcQueryLookupStrategy.java │ ├── JdbcQueryMethod.java │ ├── JdbcRepositoryFactory.java │ ├── JdbcRepositoryFactoryBean.java │ ├── JdbcRepositoryQuery.java │ ├── QueryModel.java │ ├── QueryRepository.java │ └── SimpleJdbcRepository.java └── resources └── META-INF └── spring.factories /.gitignore: -------------------------------------------------------------------------------- 1 | /*/logs/ 2 | /target/ 3 | /*/target/ 4 | !.mvn/wrapper/maven-wrapper.jar 5 | 6 | ### STS ### 7 | .apt_generated 8 | .classpath 9 | .factorypath 10 | .project 11 | .settings 12 | .springBeans 13 | .sts4-cache 14 | 15 | ### IntelliJ IDEA ### 16 | .idea 17 | *.iws 18 | *.iml 19 | *.ipr 20 | 21 | ### NetBeans ### 22 | /nbproject/private/ 23 | /build/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | -------------------------------------------------------------------------------- /bach-update.md: -------------------------------------------------------------------------------- 1 | 2 | > > need rewriteBatchedStatements=true&allowMultiQueries=true 3 | ```java 4 | public interface UserInfoRepository extends CrudJdbcRepository { 5 | @BatchUpdate 6 | int batchUpdate(List list); 7 | } 8 | ``` -------------------------------------------------------------------------------- /common-util/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-data-jdbc-mybatis-parent 7 | com.vonchange.common 8 | 2.5.0 9 | 10 | 4.0.0 11 | common-util 12 | 2.5.1 13 | 14 | 15 | com.esotericsoftware 16 | reflectasm 17 | 1.11.9 18 | 19 | 20 | org.slf4j 21 | slf4j-api 22 | 2.0.11 23 | provided 24 | 25 | 26 | com.fasterxml.jackson.core 27 | jackson-databind 28 | 2.9.8 29 | provided 30 | 31 | 32 | junit 33 | junit 34 | 4.12 35 | test 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /common-util/src/main/java/com/vonchange/common/util/ClazzUtils.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.common.util; 2 | 3 | import com.vonchange.common.util.bean.convert.Converter; 4 | 5 | import java.net.URI; 6 | import java.net.URL; 7 | import java.util.Collection; 8 | import java.util.Locale; 9 | 10 | public class ClazzUtils { 11 | private ClazzUtils() { 12 | throw new IllegalStateException("Utility class"); 13 | } 14 | 15 | /** 16 | * isBaseType 17 | */ 18 | public static boolean isBaseType(Class clazz) { 19 | // ||clazz== Time.class||clazz == Timestamp.class 20 | return Converter.hasConvertKey(clazz) || clazz.isPrimitive() || 21 | Enum.class.isAssignableFrom(clazz) || 22 | URI.class == clazz || URL.class == clazz || 23 | Locale.class == clazz || Class.class == clazz; 24 | } 25 | public static boolean isBaseTypeWithArray(Class clazz) { 26 | return isBaseType(clazz)||(clazz.isArray()&& isBaseType(clazz.getComponentType()))|| Collection.class.isAssignableFrom(clazz) ; 27 | } 28 | public static boolean isVersionType(Class clazz) { 29 | return Integer.class==clazz||Long.class==clazz; 30 | } 31 | 32 | @SuppressWarnings("unchecked") 33 | public static T cast(Class clazz, Object obj) { 34 | if (obj != null && !clazz.isInstance(obj)) 35 | throw new ClassCastException(cannotCastMsg(clazz, obj)); 36 | return (T) obj; 37 | } 38 | public static boolean isClassExists(String className) { 39 | try { 40 | Class.forName(className); 41 | return true; 42 | } catch (ClassNotFoundException e) { 43 | return false; 44 | } 45 | } 46 | 47 | 48 | @SuppressWarnings("unchecked") 49 | public static T cast(Object obj) { 50 | return (T) obj; 51 | } 52 | 53 | private static String cannotCastMsg(Class clazz, Object obj) { 54 | return "Cannot cast " + obj.getClass().getName() + " to " + clazz.getName(); 55 | } 56 | 57 | } -------------------------------------------------------------------------------- /common-util/src/main/java/com/vonchange/common/util/JsonUtil.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.common.util; 2 | 3 | import com.fasterxml.jackson.core.JsonParser; 4 | import com.fasterxml.jackson.core.JsonProcessingException; 5 | import com.fasterxml.jackson.core.type.TypeReference; 6 | import com.fasterxml.jackson.databind.DeserializationFeature; 7 | import com.fasterxml.jackson.databind.Module; 8 | import com.fasterxml.jackson.databind.ObjectMapper; 9 | import org.slf4j.Logger; 10 | import org.slf4j.LoggerFactory; 11 | 12 | import java.io.IOException; 13 | import java.util.ArrayList; 14 | import java.util.List; 15 | 16 | public class JsonUtil { 17 | private static Logger log = LoggerFactory.getLogger(JsonUtil.class); 18 | private JsonUtil() { 19 | throw new IllegalStateException("Utility class"); 20 | } 21 | static ObjectMapper objectMapper; 22 | static List moduleList=new ArrayList<>(); 23 | static { 24 | objectMapper=new ObjectMapper(); 25 | moduleList.add("com.fasterxml.jackson.datatype.jsr310.JavaTimeModule"); 26 | moduleList.add("com.fasterxml.jackson.module.paramnames.ParameterNamesModule"); 27 | moduleList.add("com.fasterxml.jackson.datatype.jdk8.Jdk8Module"); 28 | for (String module : moduleList) { 29 | if(ClazzUtils.isClassExists(module)){ 30 | try { 31 | objectMapper.registerModule((Module) Class.forName(module).newInstance()); 32 | } catch (Exception e) { 33 | log.info("registerModule {} {}",module,e.getMessage()); 34 | } 35 | } 36 | } 37 | objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES,true); 38 | objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false); 39 | } 40 | public static String toJson(Object object) { 41 | try { 42 | return objectMapper.writeValueAsString(object); 43 | } catch (JsonProcessingException e) { 44 | log.error("toJson",e); 45 | } 46 | return null; 47 | } 48 | 49 | public static T fromJson(String json, TypeReference type) { 50 | return fromJson(json,null,type); 51 | } 52 | public static T evalJson(String json, TypeReference type) throws IOException { 53 | return evalJson(json,null,type); 54 | } 55 | public static T evalJson(String json, Class clazz) throws IOException { 56 | return evalJson(json,clazz,null); 57 | } 58 | public static T evalJson(String json, Class clazz,TypeReference type) throws IOException { 59 | T t =null; 60 | if(null!=clazz){ 61 | t = objectMapper.readValue(json, clazz); 62 | } 63 | if(null!=type){ 64 | t = objectMapper.readValue(json, type); 65 | } 66 | return t; 67 | } 68 | 69 | private static T fromJson(String json, Class clazz,TypeReference type) { 70 | T t =null; 71 | try { 72 | t=evalJson(json,clazz,type); 73 | } catch (IOException e) { 74 | log.error("fromJson",e); 75 | } 76 | return t; 77 | } 78 | public static T fromJson(String json, Class clazz) { 79 | return fromJson(json,clazz,null); 80 | } 81 | 82 | } 83 | -------------------------------------------------------------------------------- /common-util/src/main/java/com/vonchange/common/util/MD5Util.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.common.util; 2 | import java.security.MessageDigest; 3 | import java.security.NoSuchAlgorithmException; 4 | 5 | public class MD5Util { 6 | public static String getMD5(String str){ 7 | return getMD5(str.getBytes()); 8 | } 9 | public static String getMD5(byte[] source){ 10 | String s=null; 11 | //用来将字节转换成16进制表示的字符 12 | char[] hexDigits={'0','1','2','3','4','5','6','7','8','9', 13 | 'a','b','c','d','e','f'}; 14 | try { 15 | MessageDigest md=MessageDigest.getInstance("MD5"); 16 | md.update(source); 17 | //MD5的计算结果是一个128位的长整数,用字节表示为16个字节 18 | byte[] tmp=md.digest(); 19 | //每个字节用16进制表示的话,使用2个字符(高4位一个,低4位一个),所以表示成16进制需要32个字符 20 | char[] str=new char[16*2]; 21 | int k=0;//转换结果中对应的字符位置 22 | for(int i=0;i<16;i++){//对MD5的每一个字节转换成16进制字符 23 | byte byte0=tmp[i]; 24 | str[k++]=hexDigits[byte0>>>4 & 0xf];//对字节高4位进行16进制转换 25 | str[k++]=hexDigits[byte0 & 0xf]; //对字节低4位进行16进制转换 26 | } 27 | s=new String(str); 28 | } catch (NoSuchAlgorithmException e) { 29 | e.printStackTrace(); 30 | } 31 | return s; 32 | } 33 | 34 | 35 | 36 | } 37 | -------------------------------------------------------------------------------- /common-util/src/main/java/com/vonchange/common/util/StringPool.java: -------------------------------------------------------------------------------- 1 | // 2 | // Source code recreated from a .class file by IntelliJ IDEA 3 | // (powered by Fernflower decompiler) 4 | // 5 | 6 | package com.vonchange.common.util; 7 | 8 | public interface StringPool { 9 | String markdown_suffix=".md"; 10 | String AMPERSAND = "&"; 11 | String AND = "and"; 12 | String AT = "@"; 13 | String ASTERISK = "*"; 14 | String STAR = "*"; 15 | String BACK_SLASH = "\\"; 16 | String COLON = ":"; 17 | String COMMA = ","; 18 | String DASH = "-"; 19 | String DOLLAR = "$"; 20 | String DOT = "."; 21 | String DOTDOT = ".."; 22 | String DOT_CLASS = ".class"; 23 | String DOT_JAVA = ".java"; 24 | String EMPTY = ""; 25 | String EQUALS = "="; 26 | String FALSE = "false"; 27 | String SLASH = "/"; 28 | String HASH = "#"; 29 | String HAT = "^"; 30 | String LEFT_BRACE = "{"; 31 | String LEFT_BRACKET = "("; 32 | String LEFT_CHEV = "<"; 33 | String NEWLINE = "\n"; 34 | String N = "n"; 35 | String NO = "no"; 36 | String NULL = "null"; 37 | String OFF = "off"; 38 | String ON = "on"; 39 | String PERCENT = "%"; 40 | String PIPE = "|"; 41 | String PLUS = "+"; 42 | String QUESTION_MARK = "?"; 43 | String EXCLAMATION_MARK = "!"; 44 | String QUOTE = "\""; 45 | String RETURN = "\r"; 46 | String TAB = "\t"; 47 | String RIGHT_BRACE = "}"; 48 | String RIGHT_BRACKET = ")"; 49 | String RIGHT_CHEV = ">"; 50 | String SEMICOLON = ";"; 51 | String SINGLE_QUOTE = "'"; 52 | String BACKTICK = "`"; 53 | String SPACE = " "; 54 | String TILDA = "~"; 55 | String LEFT_SQ_BRACKET = "["; 56 | String RIGHT_SQ_BRACKET = "]"; 57 | String TRUE = "true"; 58 | String UNDERSCORE = "_"; 59 | String UTF_8 = "UTF-8"; 60 | String US_ASCII = "US-ASCII"; 61 | String ISO_8859_1 = "ISO-8859-1"; 62 | String Y = "y"; 63 | String YES = "yes"; 64 | String ONE = "1"; 65 | String ZERO = "0"; 66 | String DOLLAR_LEFT_BRACE = "${"; 67 | String CRLF = "\r\n"; 68 | String HTML_NBSP = " "; 69 | String HTML_AMP = "&"; 70 | String HTML_QUOTE = """; 71 | String HTML_LT = "<"; 72 | String HTML_GT = ">"; 73 | String[] EMPTY_ARRAY = new String[0]; 74 | byte[] BYTES_NEW_LINE = "\n".getBytes(); 75 | } 76 | -------------------------------------------------------------------------------- /common-util/src/main/java/com/vonchange/common/util/Three.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.common.util; 2 | 3 | public class Three{ 4 | private final A first; 5 | private final B second; 6 | 7 | private final C third; 8 | 9 | private Three(A first, B second, C third) { 10 | this.first = first; 11 | this.second = second; 12 | this.third=third; 13 | } 14 | 15 | public static Three of(A first, B second, C third) { 16 | return new Three<>(first, second,third); 17 | } 18 | 19 | 20 | public A getFirst() { 21 | return first; 22 | } 23 | 24 | public B getSecond() { 25 | return second; 26 | } 27 | public C getThird() { 28 | return third; 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /common-util/src/main/java/com/vonchange/common/util/Two.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.common.util; 2 | 3 | public final class Two { 4 | 5 | private A first; 6 | private B second; 7 | 8 | public Two(){ 9 | 10 | } 11 | private Two(A first, B second) { 12 | this.first = first; 13 | this.second = second; 14 | } 15 | 16 | /** 17 | * Creates a new {@link Two} for the given elements. 18 | * 19 | * @param first must not be {@literal null}. 20 | * @param second must not be {@literal null}. 21 | * @return 22 | */ 23 | public static Two of(A first, B second) { 24 | return new Two<>(first, second); 25 | } 26 | 27 | /** 28 | * Returns the first element of the {@link Two}. 29 | * 30 | * @return 31 | */ 32 | public A getFirst() { 33 | return first; 34 | } 35 | 36 | /** 37 | * Returns the second element of the {@link Two}. 38 | * 39 | * @return 40 | */ 41 | public B getSecond() { 42 | return second; 43 | } 44 | 45 | public void setFirst(A first) { 46 | this.first = first; 47 | } 48 | 49 | public void setSecond(B second) { 50 | this.second = second; 51 | } 52 | } -------------------------------------------------------------------------------- /common-util/src/main/java/com/vonchange/common/util/bean/MethodAccessData.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.common.util.bean; 2 | 3 | import com.esotericsoftware.reflectasm.MethodAccess; 4 | 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | 8 | public class MethodAccessData { 9 | private MethodAccess methodAccess; 10 | private Map methodIndexMap; 11 | Map paramTypeMap=new HashMap<>(); 12 | public MethodAccessData(){ 13 | 14 | } 15 | 16 | public MethodAccessData(MethodAccess methodAccess, Map methodIndexMap, Map paramTypeMap) { 17 | this.methodAccess = methodAccess; 18 | this.methodIndexMap = methodIndexMap; 19 | this.paramTypeMap = paramTypeMap; 20 | } 21 | 22 | public MethodAccess getMethodAccess() { 23 | return methodAccess; 24 | } 25 | 26 | public Map getParamTypeMap() { 27 | return paramTypeMap; 28 | } 29 | 30 | public void setParamTypeMap(Map paramTypeMap) { 31 | this.paramTypeMap = paramTypeMap; 32 | } 33 | 34 | public void setMethodAccess(MethodAccess methodAccess) { 35 | this.methodAccess = methodAccess; 36 | } 37 | 38 | public Map getMethodIndexMap() { 39 | return methodIndexMap; 40 | } 41 | 42 | public void setMethodIndexMap(Map methodIndexMap) { 43 | this.methodIndexMap = methodIndexMap; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /common-util/src/main/java/com/vonchange/common/util/bean/convert/TypeConversionException.java: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2003-present, Jodd Team (http://jodd.org) 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are met: 6 | // 7 | // 1. Redistributions of source code must retain the above copyright notice, 8 | // this list of conditions and the following disclaimer. 9 | // 10 | // 2. Redistributions in binary form must reproduce the above copyright 11 | // notice, this list of conditions and the following disclaimer in the 12 | // documentation and/or other materials provided with the distribution. 13 | // 14 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 15 | // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 16 | // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 17 | // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 18 | // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 19 | // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 20 | // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 21 | // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 22 | // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 23 | // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 24 | // POSSIBILITY OF SUCH DAMAGE. 25 | 26 | package com.vonchange.common.util.bean.convert; 27 | 28 | 29 | /** 30 | * Type conversion exception. 31 | */ 32 | public class TypeConversionException extends RuntimeException { 33 | 34 | public TypeConversionException(final Throwable t) { 35 | super(t); 36 | } 37 | 38 | public TypeConversionException(final String message) { 39 | super(message); 40 | } 41 | 42 | public TypeConversionException(final String message, final Throwable t) { 43 | super(message, t); 44 | } 45 | 46 | public TypeConversionException(final Object value) { 47 | this("Conversion failed: " + value); 48 | } 49 | 50 | public TypeConversionException(final Object value, final Throwable t) { 51 | this("Conversion failed: " + value, t); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /common-util/src/main/java/com/vonchange/common/util/bean/convert/TypeConvertCommon.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.common.util.bean.convert; 2 | 3 | public abstract class TypeConvertCommon implements TypeConverter{ 4 | 5 | public abstract T convert(Object value); 6 | 7 | public T convert(final Object value, final T defaultValue){ 8 | if (value == null) { 9 | return defaultValue; 10 | } 11 | try { 12 | return convert(value); 13 | } 14 | catch (Exception e) { 15 | return defaultValue; 16 | } 17 | } 18 | } 19 | 20 | -------------------------------------------------------------------------------- /common-util/src/main/java/com/vonchange/common/util/bean/convert/TypeConverter.java: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2003-present, Jodd Team (http://jodd.org) 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are met: 6 | // 7 | // 1. Redistributions of source code must retain the above copyright notice, 8 | // this list of conditions and the following disclaimer. 9 | // 10 | // 2. Redistributions in binary form must reproduce the above copyright 11 | // notice, this list of conditions and the following disclaimer in the 12 | // documentation and/or other materials provided with the distribution. 13 | // 14 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 15 | // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 16 | // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 17 | // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 18 | // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 19 | // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 20 | // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 21 | // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 22 | // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 23 | // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 24 | // POSSIBILITY OF SUCH DAMAGE. 25 | 26 | package com.vonchange.common.util.bean.convert; 27 | 28 | 29 | 30 | /** 31 | * Object converter interface. 32 | * 33 | */ 34 | public interface TypeConverter { 35 | 36 | /** 37 | * Converts object received as parameter into object of another class. 38 | * For example, an Integer converter tries to convert given objects 39 | * into target Integer object. Converters should try all reasonable 40 | * ways of conversion into target object, depending on target type. 41 | * 42 | * @param value object to convert from 43 | * 44 | * @return resulting object converted to target type 45 | * @throws TypeConversionException if conversion fails 46 | */ 47 | T convert(Object value); 48 | 49 | /** 50 | * Converts object and returns default value if conversion fails. 51 | */ 52 | T convert(final Object value, final T defaultValue); 53 | 54 | } 55 | -------------------------------------------------------------------------------- /common-util/src/main/java/com/vonchange/common/util/bean/convert/impl/BigDecimalConverter.java: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2003-present, Jodd Team (http://jodd.org) 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are met: 6 | // 7 | // 1. Redistributions of source code must retain the above copyright notice, 8 | // this list of conditions and the following disclaimer. 9 | // 10 | // 2. Redistributions in binary form must reproduce the above copyright 11 | // notice, this list of conditions and the following disclaimer in the 12 | // documentation and/or other materials provided with the distribution. 13 | // 14 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 15 | // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 16 | // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 17 | // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 18 | // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 19 | // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 20 | // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 21 | // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 22 | // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 23 | // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 24 | // POSSIBILITY OF SUCH DAMAGE. 25 | 26 | package com.vonchange.common.util.bean.convert.impl; 27 | 28 | import com.vonchange.common.util.bean.convert.TypeConversionException; 29 | import com.vonchange.common.util.bean.convert.TypeConvertCommon; 30 | 31 | import java.math.BigDecimal; 32 | 33 | /** 34 | * Converts given object to BigDecimal. 35 | * Conversion rules: 36 | *
    37 | *
  • null value is returned as null
  • 38 | *
  • object of destination type is simply casted
  • 39 | *
  • object is converted to string, trimmed, and then converted if 40 | * possible
  • 41 | *
42 | */ 43 | public class BigDecimalConverter extends TypeConvertCommon { 44 | 45 | @Override 46 | public BigDecimal convert(final Object value) { 47 | if (value == null) { 48 | return null; 49 | } 50 | 51 | if (value instanceof BigDecimal) { 52 | return (BigDecimal) value; 53 | } 54 | try { 55 | return new BigDecimal(value.toString().trim()); 56 | } catch (NumberFormatException nfex) { 57 | throw new TypeConversionException(value, nfex); 58 | } 59 | } 60 | 61 | } -------------------------------------------------------------------------------- /common-util/src/main/java/com/vonchange/common/util/bean/convert/impl/BigIntegerConverter.java: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2003-present, Jodd Team (http://jodd.org) 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are met: 6 | // 7 | // 1. Redistributions of source code must retain the above copyright notice, 8 | // this list of conditions and the following disclaimer. 9 | // 10 | // 2. Redistributions in binary form must reproduce the above copyright 11 | // notice, this list of conditions and the following disclaimer in the 12 | // documentation and/or other materials provided with the distribution. 13 | // 14 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 15 | // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 16 | // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 17 | // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 18 | // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 19 | // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 20 | // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 21 | // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 22 | // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 23 | // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 24 | // POSSIBILITY OF SUCH DAMAGE. 25 | 26 | package com.vonchange.common.util.bean.convert.impl; 27 | 28 | import java.math.BigInteger; 29 | 30 | import com.vonchange.common.util.bean.convert.TypeConversionException; 31 | import com.vonchange.common.util.bean.convert.TypeConvertCommon; 32 | 33 | /** 34 | * Converts given object to BigInteger. 35 | * Conversion rules: 36 | *
    37 | *
  • null value is returned as null
  • 38 | *
  • object of destination type is simply casted
  • 39 | *
  • object is converted to string, trimmed, and then converted if 40 | * possible
  • 41 | *
42 | */ 43 | public class BigIntegerConverter extends TypeConvertCommon { 44 | 45 | public BigInteger convert(final Object value) { 46 | if (value == null) { 47 | return null; 48 | } 49 | 50 | if (value instanceof BigInteger) { 51 | return (BigInteger) value; 52 | } 53 | if (value instanceof Number) { 54 | return new BigInteger(String.valueOf(((Number) value).longValue())); 55 | } 56 | try { 57 | return new BigInteger(value.toString().trim()); 58 | } catch (NumberFormatException nfex) { 59 | throw new TypeConversionException(value, nfex); 60 | } 61 | } 62 | 63 | } -------------------------------------------------------------------------------- /common-util/src/main/java/com/vonchange/common/util/bean/convert/impl/ByteConverter.java: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2003-present, Jodd Team (http://jodd.org) 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are met: 6 | // 7 | // 1. Redistributions of source code must retain the above copyright notice, 8 | // this list of conditions and the following disclaimer. 9 | // 10 | // 2. Redistributions in binary form must reproduce the above copyright 11 | // notice, this list of conditions and the following disclaimer in the 12 | // documentation and/or other materials provided with the distribution. 13 | // 14 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 15 | // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 16 | // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 17 | // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 18 | // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 19 | // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 20 | // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 21 | // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 22 | // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 23 | // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 24 | // POSSIBILITY OF SUCH DAMAGE. 25 | 26 | package com.vonchange.common.util.bean.convert.impl; 27 | 28 | import com.vonchange.common.util.UtilAll; 29 | import com.vonchange.common.util.bean.convert.TypeConversionException; 30 | import com.vonchange.common.util.bean.convert.TypeConvertCommon; 31 | 32 | /** 33 | * Converts given object to Byte. 34 | * Conversion rules: 35 | *
    36 | *
  • null value is returned as null
  • 37 | *
  • object of destination type is simply casted
  • 38 | *
  • object is converted to string, trimmed, and then converted if 39 | * possible.
  • 40 | *
41 | * Number string may start with plus and minus sign. 42 | */ 43 | public class ByteConverter extends TypeConvertCommon { 44 | 45 | @Override 46 | public Byte convert(final Object value) { 47 | if (value == null) { 48 | return null; 49 | } 50 | if (value.getClass() == Byte.class) { 51 | return (Byte) value; 52 | } 53 | if (value instanceof Number) { 54 | return Byte.valueOf(((Number) value).byteValue()); 55 | } 56 | if (value instanceof Boolean) { 57 | return ((Boolean) value).booleanValue() ? Byte.valueOf((byte) 1) : Byte.valueOf((byte) 0); 58 | } 59 | 60 | try { 61 | String stringValue = value.toString().trim(); 62 | if (UtilAll.UString.startsWithChar(stringValue, '+')) { 63 | stringValue = stringValue.substring(1); 64 | } 65 | return Byte.valueOf(stringValue); 66 | } catch (NumberFormatException nfex) { 67 | throw new TypeConversionException(value, nfex); 68 | } 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /common-util/src/main/java/com/vonchange/common/util/bean/convert/impl/CharacterConverter.java: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2003-present, Jodd Team (http://jodd.org) 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are met: 6 | // 7 | // 1. Redistributions of source code must retain the above copyright notice, 8 | // this list of conditions and the following disclaimer. 9 | // 10 | // 2. Redistributions in binary form must reproduce the above copyright 11 | // notice, this list of conditions and the following disclaimer in the 12 | // documentation and/or other materials provided with the distribution. 13 | // 14 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 15 | // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 16 | // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 17 | // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 18 | // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 19 | // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 20 | // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 21 | // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 22 | // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 23 | // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 24 | // POSSIBILITY OF SUCH DAMAGE. 25 | 26 | package com.vonchange.common.util.bean.convert.impl; 27 | 28 | import com.vonchange.common.util.UtilAll; 29 | import com.vonchange.common.util.bean.convert.TypeConversionException; 30 | import com.vonchange.common.util.bean.convert.TypeConvertCommon; 31 | 32 | /** 33 | * Converts given object to Character. 34 | * Conversion rules: 35 | *
    36 | *
  • null value is returned as null
  • 37 | *
  • object of destination type is simply casted
  • 38 | *
  • Number is converted to char value
  • 39 | *
  • finally, toString() value of length 1 is converted to 40 | * char
  • 41 | *
  • if string is longer, and made of digits, try to convert it to int 42 | * first
  • 43 | *
44 | */ 45 | public class CharacterConverter extends TypeConvertCommon { 46 | 47 | public Character convert(final Object value) { 48 | if (value == null) { 49 | return null; 50 | } 51 | if (value.getClass() == Character.class) { 52 | return (Character) value; 53 | } 54 | if (value instanceof Number) { 55 | char c = (char) ((Number) value).intValue(); 56 | return Character.valueOf(c); 57 | } 58 | try { 59 | String s = value.toString(); 60 | if (s.length() != 1) { 61 | s = s.trim(); 62 | if (!UtilAll.UString.containsOnlyDigitsAndSigns(s)) { 63 | throw new TypeConversionException(value); 64 | } 65 | 66 | try { 67 | char c = (char) Integer.parseInt(s); 68 | return Character.valueOf(c); 69 | } catch (NumberFormatException nfex) { 70 | throw new TypeConversionException(value, nfex); 71 | } 72 | } 73 | return Character.valueOf(s.charAt(0)); 74 | } catch (IndexOutOfBoundsException ioobex) { 75 | throw new TypeConversionException(value, ioobex); 76 | } 77 | } 78 | 79 | } -------------------------------------------------------------------------------- /common-util/src/main/java/com/vonchange/common/util/bean/convert/impl/DateConverter.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.common.util.bean.convert.impl; 2 | 3 | import com.vonchange.common.util.UtilAll; 4 | import com.vonchange.common.util.bean.convert.TypeConversionException; 5 | import com.vonchange.common.util.bean.convert.TypeConvertCommon; 6 | import com.vonchange.common.util.exception.ParseException; 7 | import com.vonchange.common.util.TimeUtil; 8 | 9 | import java.time.LocalDate; 10 | import java.time.LocalDateTime; 11 | import java.util.Calendar; 12 | import java.util.Date; 13 | 14 | public class DateConverter extends TypeConvertCommon { 15 | 16 | @Override 17 | public Date convert(final Object value) { 18 | if (value == null) { 19 | return null; 20 | } 21 | 22 | if (value instanceof Date) { 23 | return (Date) value; 24 | } 25 | if (value instanceof Calendar) { 26 | return new Date(((Calendar) value).getTimeInMillis()); 27 | } 28 | if (value instanceof LocalDateTime) { 29 | return TimeUtil.toDate((LocalDateTime) value); 30 | } 31 | if (value instanceof LocalDate) { 32 | return TimeUtil.toDate((LocalDate) value); 33 | } 34 | if (value instanceof Number) { 35 | return new Date(((Number) value).longValue()); 36 | } 37 | final String stringValue = value.toString().trim(); 38 | if(UtilAll.UString.containsOnlyDigits(stringValue)){ 39 | try { 40 | long milliseconds = Long.parseLong(stringValue); 41 | return new Date(milliseconds); 42 | } catch (NumberFormatException nfex) { 43 | throw new TypeConversionException(value, nfex); 44 | } 45 | } 46 | Date result; 47 | try { 48 | result= UtilAll.UDate.parseDate(stringValue, 49 | "yyyy-MM-dd HH:mm:ss","yyyy-MM-dd","yyyy-MM-ddTHH:mm:ssZ"); 50 | } catch (ParseException e) { 51 | throw new TypeConversionException(value, e); 52 | } 53 | return result; 54 | } 55 | 56 | } -------------------------------------------------------------------------------- /common-util/src/main/java/com/vonchange/common/util/bean/convert/impl/DoubleConverter.java: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2003-present, Jodd Team (http://jodd.org) 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are met: 6 | // 7 | // 1. Redistributions of source code must retain the above copyright notice, 8 | // this list of conditions and the following disclaimer. 9 | // 10 | // 2. Redistributions in binary form must reproduce the above copyright 11 | // notice, this list of conditions and the following disclaimer in the 12 | // documentation and/or other materials provided with the distribution. 13 | // 14 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 15 | // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 16 | // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 17 | // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 18 | // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 19 | // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 20 | // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 21 | // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 22 | // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 23 | // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 24 | // POSSIBILITY OF SUCH DAMAGE. 25 | 26 | package com.vonchange.common.util.bean.convert.impl; 27 | 28 | import com.vonchange.common.util.UtilAll; 29 | import com.vonchange.common.util.bean.convert.TypeConversionException; 30 | import com.vonchange.common.util.bean.convert.TypeConvertCommon; 31 | 32 | /** 33 | * Converts given object to Double. 34 | * Conversion rules: 35 | *
    36 | *
  • null value is returned as null
  • 37 | *
  • object of destination type is simply casted
  • 38 | *
  • object is converted to string, trimmed, and then converted if 39 | * possible.
  • 40 | *
41 | * Number string may start with plus and minus sign. 42 | */ 43 | public class DoubleConverter extends TypeConvertCommon { 44 | 45 | public Double convert(final Object value) { 46 | if (value == null) { 47 | return null; 48 | } 49 | 50 | if (value.getClass() == Double.class) { 51 | return (Double) value; 52 | } 53 | if (value instanceof Number) { 54 | return Double.valueOf(((Number) value).doubleValue()); 55 | } 56 | if (value instanceof Boolean) { 57 | return ((Boolean) value).booleanValue() ? Double.valueOf(1) : Double.valueOf(0); 58 | } 59 | 60 | try { 61 | String stringValue = value.toString().trim(); 62 | if (UtilAll.UString.startsWithChar(stringValue, '+')) { 63 | stringValue = stringValue.substring(1); 64 | } 65 | return Double.valueOf(stringValue); 66 | } catch (NumberFormatException nfex) { 67 | throw new TypeConversionException(value, nfex); 68 | } 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /common-util/src/main/java/com/vonchange/common/util/bean/convert/impl/FloatConverter.java: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2003-present, Jodd Team (http://jodd.org) 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are met: 6 | // 7 | // 1. Redistributions of source code must retain the above copyright notice, 8 | // this list of conditions and the following disclaimer. 9 | // 10 | // 2. Redistributions in binary form must reproduce the above copyright 11 | // notice, this list of conditions and the following disclaimer in the 12 | // documentation and/or other materials provided with the distribution. 13 | // 14 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 15 | // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 16 | // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 17 | // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 18 | // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 19 | // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 20 | // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 21 | // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 22 | // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 23 | // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 24 | // POSSIBILITY OF SUCH DAMAGE. 25 | 26 | package com.vonchange.common.util.bean.convert.impl; 27 | 28 | import com.vonchange.common.util.UtilAll; 29 | import com.vonchange.common.util.bean.convert.TypeConversionException; 30 | import com.vonchange.common.util.bean.convert.TypeConvertCommon; 31 | 32 | /** 33 | * Converts given object to Float. 34 | * Conversion rules: 35 | *
    36 | *
  • null value is returned as null
  • 37 | *
  • object of destination type is simply casted
  • 38 | *
  • object is converted to string, trimmed, and then converted if 39 | * possible.
  • 40 | *
41 | * Number string may start with plus and minus sign. 42 | */ 43 | public class FloatConverter extends TypeConvertCommon { 44 | 45 | public Float convert(final Object value) { 46 | if (value == null) { 47 | return null; 48 | } 49 | 50 | if (value.getClass() == Float.class) { 51 | return (Float) value; 52 | } 53 | if (value instanceof Number) { 54 | return Float.valueOf(((Number) value).floatValue()); 55 | } 56 | if (value instanceof Boolean) { 57 | return ((Boolean) value).booleanValue() ? Float.valueOf(1) : Float.valueOf(0); 58 | } 59 | 60 | try { 61 | String stringValue = value.toString().trim(); 62 | if (UtilAll.UString.startsWithChar(stringValue, '+')) { 63 | stringValue = stringValue.substring(1); 64 | } 65 | return Float.valueOf(stringValue); 66 | } catch (NumberFormatException nfex) { 67 | throw new TypeConversionException(value, nfex); 68 | } 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /common-util/src/main/java/com/vonchange/common/util/bean/convert/impl/IntegerConverter.java: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2003-present, Jodd Team (http://jodd.org) 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are met: 6 | // 7 | // 1. Redistributions of source code must retain the above copyright notice, 8 | // this list of conditions and the following disclaimer. 9 | // 10 | // 2. Redistributions in binary form must reproduce the above copyright 11 | // notice, this list of conditions and the following disclaimer in the 12 | // documentation and/or other materials provided with the distribution. 13 | // 14 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 15 | // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 16 | // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 17 | // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 18 | // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 19 | // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 20 | // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 21 | // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 22 | // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 23 | // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 24 | // POSSIBILITY OF SUCH DAMAGE. 25 | 26 | package com.vonchange.common.util.bean.convert.impl; 27 | 28 | import com.vonchange.common.util.UtilAll; 29 | import com.vonchange.common.util.bean.convert.TypeConversionException; 30 | import com.vonchange.common.util.bean.convert.TypeConvertCommon; 31 | 32 | /** 33 | * Converts given object to an Integer. 34 | * Conversion rules: 35 | *
    36 | *
  • null value is returned as null
  • 37 | *
  • object of destination type is simply casted
  • 38 | *
  • object is converted to string, trimmed, and then converted if 39 | * possible.
  • 40 | *
41 | * Number string may start with plus and minus sign. 42 | */ 43 | public class IntegerConverter extends TypeConvertCommon { 44 | 45 | public Integer convert(final Object value) { 46 | if (value == null) { 47 | return null; 48 | } 49 | 50 | if (value.getClass() == Integer.class) { 51 | return (Integer) value; 52 | } 53 | if (value instanceof Number) { 54 | return Integer.valueOf(((Number) value).intValue()); 55 | } 56 | if (value instanceof Boolean) { 57 | return ((Boolean) value).booleanValue() ? Integer.valueOf(1) : Integer.valueOf(0); 58 | } 59 | 60 | try { 61 | String stringValue = value.toString().trim(); 62 | if (UtilAll.UString.startsWithChar(stringValue, '+')) { 63 | stringValue = stringValue.substring(1); 64 | } 65 | return Integer.valueOf(stringValue); 66 | } catch (NumberFormatException nfex) { 67 | throw new TypeConversionException(value, nfex); 68 | } 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /common-util/src/main/java/com/vonchange/common/util/bean/convert/impl/LocalDateConverter.java: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2003-present, Jodd Team (http://jodd.org) 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are met: 6 | // 7 | // 1. Redistributions of source code must retain the above copyright notice, 8 | // this list of conditions and the following disclaimer. 9 | // 10 | // 2. Redistributions in binary form must reproduce the above copyright 11 | // notice, this list of conditions and the following disclaimer in the 12 | // documentation and/or other materials provided with the distribution. 13 | // 14 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 15 | // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 16 | // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 17 | // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 18 | // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 19 | // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 20 | // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 21 | // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 22 | // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 23 | // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 24 | // POSSIBILITY OF SUCH DAMAGE. 25 | 26 | package com.vonchange.common.util.bean.convert.impl; 27 | 28 | import com.vonchange.common.util.UtilAll; 29 | import com.vonchange.common.util.bean.convert.TypeConversionException; 30 | import com.vonchange.common.util.bean.convert.TypeConvertCommon; 31 | import com.vonchange.common.util.TimeUtil; 32 | 33 | import java.sql.Timestamp; 34 | import java.time.LocalDate; 35 | import java.time.LocalDateTime; 36 | import java.time.LocalTime; 37 | import java.util.Calendar; 38 | import java.util.Date; 39 | 40 | public class LocalDateConverter extends TypeConvertCommon { 41 | @Override 42 | public LocalDate convert(Object value) { 43 | if (value == null) { 44 | return null; 45 | } 46 | 47 | if (value instanceof LocalDateTime) { 48 | return ((LocalDateTime) value).toLocalDate(); 49 | } 50 | if (value instanceof Calendar) { 51 | return TimeUtil.fromCalendar((Calendar) value).toLocalDate(); 52 | } 53 | if (value instanceof Timestamp) { 54 | return TimeUtil.fromMilliseconds(((Timestamp) value).getTime()).toLocalDate(); 55 | } 56 | if (value instanceof Date) { 57 | if (value instanceof java.sql.Date) { 58 | return ((java.sql.Date) value).toLocalDate(); 59 | } 60 | return TimeUtil.fromDate((Date) value).toLocalDate(); 61 | } 62 | if (value instanceof Number) { 63 | return TimeUtil.fromMilliseconds(((Number) value).longValue()).toLocalDate(); 64 | } 65 | if (value instanceof LocalTime) { 66 | throw new TypeConversionException("Can't convert to date just from time: " + value); 67 | } 68 | 69 | String stringValue = value.toString().trim(); 70 | 71 | if (!UtilAll.UString.containsOnlyDigits(stringValue)) { 72 | // try to parse default string format 73 | return LocalDate.parse(stringValue); 74 | } 75 | 76 | try { 77 | return TimeUtil.fromMilliseconds(Long.parseLong(stringValue)).toLocalDate(); 78 | } catch (NumberFormatException nfex) { 79 | throw new TypeConversionException(value, nfex); 80 | } 81 | 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /common-util/src/main/java/com/vonchange/common/util/bean/convert/impl/LocalDateTimeConverter.java: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2003-present, Jodd Team (http://jodd.org) 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are met: 6 | // 7 | // 1. Redistributions of source code must retain the above copyright notice, 8 | // this list of conditions and the following disclaimer. 9 | // 10 | // 2. Redistributions in binary form must reproduce the above copyright 11 | // notice, this list of conditions and the following disclaimer in the 12 | // documentation and/or other materials provided with the distribution. 13 | // 14 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 15 | // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 16 | // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 17 | // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 18 | // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 19 | // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 20 | // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 21 | // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 22 | // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 23 | // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 24 | // POSSIBILITY OF SUCH DAMAGE. 25 | 26 | package com.vonchange.common.util.bean.convert.impl; 27 | 28 | import com.vonchange.common.util.UtilAll; 29 | import com.vonchange.common.util.bean.convert.TypeConversionException; 30 | import com.vonchange.common.util.bean.convert.TypeConvertCommon; 31 | import com.vonchange.common.util.TimeUtil; 32 | 33 | import java.sql.Timestamp; 34 | import java.time.LocalDate; 35 | import java.time.LocalDateTime; 36 | import java.time.LocalTime; 37 | import java.util.Calendar; 38 | import java.util.Date; 39 | 40 | public class LocalDateTimeConverter extends TypeConvertCommon { 41 | @Override 42 | public LocalDateTime convert(Object value) { 43 | if (value == null) { 44 | return null; 45 | } 46 | 47 | if (value instanceof LocalDate) { 48 | return LocalDateTime.of(((LocalDate) value), LocalTime.MIDNIGHT); 49 | } 50 | if (value instanceof Calendar) { 51 | return TimeUtil.fromCalendar((Calendar) value); 52 | } 53 | if (value instanceof Timestamp) { 54 | return TimeUtil.fromMilliseconds(((Timestamp) value).getTime()); 55 | } 56 | if (value instanceof Date) { 57 | return TimeUtil.fromDate((Date) value); 58 | } 59 | if (value instanceof Number) { 60 | return TimeUtil.fromMilliseconds(((Number) value).longValue()); 61 | } 62 | if (value instanceof LocalTime) { 63 | throw new TypeConversionException("Can't convert to date just from time: " + value); 64 | } 65 | 66 | String stringValue = value.toString().trim(); 67 | 68 | if (!UtilAll.UString.containsOnlyDigits(stringValue)) { 69 | // try to parse default string format 70 | return LocalDateTime.parse(stringValue); 71 | } 72 | 73 | try { 74 | return TimeUtil.fromMilliseconds(Long.parseLong(stringValue)); 75 | } catch (NumberFormatException nfex) { 76 | throw new TypeConversionException(value, nfex); 77 | } 78 | 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /common-util/src/main/java/com/vonchange/common/util/bean/convert/impl/LocalTimeConverter.java: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2003-present, Jodd Team (http://jodd.org) 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are met: 6 | // 7 | // 1. Redistributions of source code must retain the above copyright notice, 8 | // this list of conditions and the following disclaimer. 9 | // 10 | // 2. Redistributions in binary form must reproduce the above copyright 11 | // notice, this list of conditions and the following disclaimer in the 12 | // documentation and/or other materials provided with the distribution. 13 | // 14 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 15 | // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 16 | // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 17 | // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 18 | // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 19 | // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 20 | // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 21 | // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 22 | // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 23 | // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 24 | // POSSIBILITY OF SUCH DAMAGE. 25 | 26 | package com.vonchange.common.util.bean.convert.impl; 27 | 28 | import com.vonchange.common.util.UtilAll; 29 | import com.vonchange.common.util.bean.convert.TypeConversionException; 30 | import com.vonchange.common.util.bean.convert.TypeConvertCommon; 31 | import com.vonchange.common.util.TimeUtil; 32 | 33 | import java.sql.Timestamp; 34 | import java.time.LocalDate; 35 | import java.time.LocalDateTime; 36 | import java.time.LocalTime; 37 | import java.util.Calendar; 38 | import java.util.Date; 39 | 40 | public class LocalTimeConverter extends TypeConvertCommon { 41 | @Override 42 | public LocalTime convert(Object value) { 43 | if (value == null) { 44 | return null; 45 | } 46 | 47 | if (value instanceof LocalDateTime) { 48 | return ((LocalDateTime) value).toLocalTime(); 49 | } 50 | if (value instanceof Calendar) { 51 | return TimeUtil.fromCalendar((Calendar) value).toLocalTime(); 52 | } 53 | if (value instanceof Timestamp) { 54 | return TimeUtil.fromMilliseconds(((Timestamp) value).getTime()).toLocalTime(); 55 | } 56 | if (value instanceof Date) { 57 | return TimeUtil.fromDate((Date) value).toLocalTime(); 58 | } 59 | if (value instanceof Number) { 60 | return TimeUtil.fromMilliseconds(((Number) value).longValue()).toLocalTime(); 61 | } 62 | if (value instanceof LocalDate) { 63 | throw new TypeConversionException("Can't convert to time just from date: " + value); 64 | } 65 | 66 | String stringValue = value.toString().trim(); 67 | 68 | if (!UtilAll.UString.containsOnlyDigits(stringValue)) { 69 | // try to parse default string format 70 | return LocalTime.parse(stringValue); 71 | } 72 | 73 | try { 74 | return TimeUtil.fromMilliseconds(Long.parseLong(stringValue)).toLocalTime(); 75 | } catch (NumberFormatException nfex) { 76 | throw new TypeConversionException(value, nfex); 77 | } 78 | 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /common-util/src/main/java/com/vonchange/common/util/bean/convert/impl/LongConverter.java: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2003-present, Jodd Team (http://jodd.org) 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are met: 6 | // 7 | // 1. Redistributions of source code must retain the above copyright notice, 8 | // this list of conditions and the following disclaimer. 9 | // 10 | // 2. Redistributions in binary form must reproduce the above copyright 11 | // notice, this list of conditions and the following disclaimer in the 12 | // documentation and/or other materials provided with the distribution. 13 | // 14 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 15 | // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 16 | // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 17 | // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 18 | // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 19 | // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 20 | // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 21 | // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 22 | // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 23 | // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 24 | // POSSIBILITY OF SUCH DAMAGE. 25 | 26 | package com.vonchange.common.util.bean.convert.impl; 27 | 28 | import com.vonchange.common.util.UtilAll; 29 | import com.vonchange.common.util.bean.convert.TypeConversionException; 30 | import com.vonchange.common.util.bean.convert.TypeConvertCommon; 31 | 32 | /** 33 | * Converts given object to a Long. 34 | * Conversion rules: 35 | *
    36 | *
  • null value is returned as null
  • 37 | *
  • object of destination type is simply casted
  • 38 | *
  • object is converted to string, trimmed, and then converted if 39 | * possible.
  • 40 | *
41 | * Number string may start with plus and minus sign. 42 | */ 43 | public class LongConverter extends TypeConvertCommon { 44 | 45 | public Long convert(final Object value) { 46 | if (value == null) { 47 | return null; 48 | } 49 | 50 | if (value.getClass() == Long.class) { 51 | return (Long) value; 52 | } 53 | if (value instanceof Number) { 54 | return Long.valueOf(((Number) value).longValue()); 55 | } 56 | if (value instanceof Boolean) { 57 | return ((Boolean) value).booleanValue() ? Long.valueOf(1L) : Long.valueOf(0L); 58 | } 59 | 60 | try { 61 | String stringValue = value.toString().trim(); 62 | if (UtilAll.UString.startsWithChar(stringValue, '+')) { 63 | stringValue = stringValue.substring(1); 64 | } 65 | return Long.valueOf(stringValue); 66 | } catch (NumberFormatException nfex) { 67 | throw new TypeConversionException(value, nfex); 68 | } 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /common-util/src/main/java/com/vonchange/common/util/bean/convert/impl/NumberConverter.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.common.util.bean.convert.impl; 2 | 3 | import com.vonchange.common.util.UtilAll; 4 | import com.vonchange.common.util.bean.convert.TypeConversionException; 5 | import com.vonchange.common.util.bean.convert.TypeConvertCommon; 6 | import com.vonchange.common.util.bean.convert.TypeConverter; 7 | 8 | public class NumberConverter extends TypeConvertCommon implements TypeConverter { 9 | @Override 10 | public Number convert(Object value) { 11 | if (value == null) { 12 | return null; 13 | } 14 | 15 | if (value instanceof Number) { 16 | return (Number) value; 17 | } 18 | 19 | if (value instanceof Boolean) { 20 | return ((Boolean) value).booleanValue() ? 1 :0; 21 | } 22 | 23 | try { 24 | String stringValue = value.toString().trim(); 25 | if (UtilAll.UString.startsWithChar(stringValue, '+')) { 26 | stringValue = stringValue.substring(1); 27 | } 28 | if(stringValue.contains(".")){ 29 | return Double.valueOf(stringValue); 30 | } 31 | return Long.valueOf(stringValue); 32 | } catch (NumberFormatException nfex) { 33 | throw new TypeConversionException(value, nfex); 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /common-util/src/main/java/com/vonchange/common/util/bean/convert/impl/ShortConverter.java: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2003-present, Jodd Team (http://jodd.org) 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are met: 6 | // 7 | // 1. Redistributions of source code must retain the above copyright notice, 8 | // this list of conditions and the following disclaimer. 9 | // 10 | // 2. Redistributions in binary form must reproduce the above copyright 11 | // notice, this list of conditions and the following disclaimer in the 12 | // documentation and/or other materials provided with the distribution. 13 | // 14 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 15 | // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 16 | // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 17 | // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 18 | // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 19 | // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 20 | // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 21 | // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 22 | // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 23 | // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 24 | // POSSIBILITY OF SUCH DAMAGE. 25 | 26 | package com.vonchange.common.util.bean.convert.impl; 27 | 28 | import com.vonchange.common.util.UtilAll; 29 | import com.vonchange.common.util.bean.convert.TypeConversionException; 30 | import com.vonchange.common.util.bean.convert.TypeConvertCommon; 31 | 32 | /** 33 | * Converts given object to Short. 34 | * Conversion rules: 35 | *
    36 | *
  • null value is returned as null
  • 37 | *
  • object of destination type is simply casted
  • 38 | *
  • object is converted to string, trimmed, and then converted if 39 | * possible.
  • 40 | *
41 | * Number string may start with plus and minus sign. 42 | */ 43 | public class ShortConverter extends TypeConvertCommon { 44 | 45 | @Override 46 | public Short convert(final Object value) { 47 | if (value == null) { 48 | return null; 49 | } 50 | 51 | if (value.getClass() == Short.class) { 52 | return (Short) value; 53 | } 54 | if (value instanceof Number) { 55 | return Short.valueOf(((Number) value).shortValue()); 56 | } 57 | if (value instanceof Boolean) { 58 | return ((Boolean) value).booleanValue() ? Short.valueOf((short) 1) : Short.valueOf((short) 0); 59 | } 60 | 61 | try { 62 | String stringValue = value.toString().trim(); 63 | if (UtilAll.UString.startsWithChar(stringValue, '+')) { 64 | stringValue = stringValue.substring(1); 65 | } 66 | return Short.valueOf(stringValue); 67 | } catch (NumberFormatException nfex) { 68 | throw new TypeConversionException(value, nfex); 69 | } 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /common-util/src/main/java/com/vonchange/common/util/bean/convert/impl/StringConverter.java: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2003-present, Jodd Team (http://jodd.org) 2 | // All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are met: 6 | // 7 | // 1. Redistributions of source code must retain the above copyright notice, 8 | // this list of conditions and the following disclaimer. 9 | // 10 | // 2. Redistributions in binary form must reproduce the above copyright 11 | // notice, this list of conditions and the following disclaimer in the 12 | // documentation and/or other materials provided with the distribution. 13 | // 14 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 15 | // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 16 | // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 17 | // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 18 | // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 19 | // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 20 | // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 21 | // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 22 | // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 23 | // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 24 | // POSSIBILITY OF SUCH DAMAGE. 25 | 26 | package com.vonchange.common.util.bean.convert.impl; 27 | 28 | import java.sql.Clob; 29 | import java.sql.SQLException; 30 | 31 | import com.vonchange.common.util.bean.convert.TypeConversionException; 32 | import com.vonchange.common.util.bean.convert.TypeConvertCommon; 33 | 34 | /** 35 | * Converts given object to String. 36 | * Conversion rules: 37 | *
    38 | *
  • null value is returned as null
  • 39 | *
  • for CharSequence type returns toString value
  • 40 | *
  • Class returns cass name
  • 41 | *
  • char[] is used for creating string
  • 42 | *
  • arrays are converted to comma-separated list of toString 43 | * values
  • 44 | *
  • Clob is converted
  • 45 | *
  • finally, toString() value is returned.
  • 46 | *
47 | */ 48 | public class StringConverter extends TypeConvertCommon { 49 | 50 | @Override 51 | public String convert(final Object value) { 52 | if (value == null) { 53 | return null; 54 | } 55 | 56 | if (value instanceof CharSequence) { // for speed 57 | return value.toString(); 58 | } 59 | Class type = value.getClass(); 60 | if (type == Class.class) { 61 | return ((Class) value).getName(); 62 | } 63 | 64 | if (value instanceof Clob) { 65 | Clob clob = (Clob) value; 66 | try { 67 | long length = clob.length(); 68 | if (length > Integer.MAX_VALUE) { 69 | throw new TypeConversionException("Clob is too big."); 70 | } 71 | return clob.getSubString(1, (int) length); 72 | } catch (SQLException sex) { 73 | throw new TypeConversionException(value, sex); 74 | } 75 | } 76 | return value.toString(); 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /common-util/src/main/java/com/vonchange/common/util/exception/CommonRuntimeException.java: -------------------------------------------------------------------------------- 1 | 2 | package com.vonchange.common.util.exception; 3 | 4 | 5 | public class CommonRuntimeException extends RuntimeException { 6 | 7 | 8 | private static final long serialVersionUID = 1050921059666314224L; 9 | private final Object errorCode; 10 | 11 | public CommonRuntimeException(Object errorCode) { 12 | super(errorCode.toString()); 13 | this.errorCode = errorCode; 14 | } 15 | 16 | public CommonRuntimeException(Object errorCode, ErrorMsg errorMsg) { 17 | super(errorCode.toString() + " " + errorMsg.getMessage(), errorMsg.getThrowable()); 18 | this.errorCode = errorCode; 19 | } 20 | 21 | 22 | public Object getErrorCode() { 23 | return errorCode; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /common-util/src/main/java/com/vonchange/common/util/exception/EnumUtilErrorCode.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.common.util.exception; 2 | 3 | public enum EnumUtilErrorCode { 4 | Error,NullValue,MarkdownIdNotFound,MarkdownPathNotFound 5 | } 6 | -------------------------------------------------------------------------------- /common-util/src/main/java/com/vonchange/common/util/exception/ErrorMsg.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.common.util.exception; 2 | 3 | import com.vonchange.common.util.UtilAll; 4 | 5 | public class ErrorMsg{ 6 | private String message; 7 | private Throwable throwable; 8 | 9 | 10 | public static ErrorMsg builder(){ 11 | return new ErrorMsg(); 12 | } 13 | public ErrorMsg message(String message) { 14 | this.message =message; 15 | return this; 16 | } 17 | public ErrorMsg message(String message, Object... parameters) { 18 | this.message = UtilAll.UString.format(message,parameters); 19 | return this; 20 | } 21 | public ErrorMsg throwable( Throwable throwable) { 22 | this.throwable =throwable; 23 | return this; 24 | } 25 | 26 | 27 | public String getMessage() { 28 | return message; 29 | } 30 | 31 | 32 | public Throwable getThrowable() { 33 | return throwable; 34 | } 35 | } -------------------------------------------------------------------------------- /common-util/src/main/java/com/vonchange/common/util/exception/ParseException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved. 3 | * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. 4 | * 5 | * 6 | * 7 | * 8 | * 9 | * 10 | * 11 | * 12 | * 13 | * 14 | * 15 | * 16 | * 17 | * 18 | * 19 | * 20 | * 21 | * 22 | * 23 | * 24 | */ 25 | 26 | /* 27 | * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved 28 | * (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved 29 | * 30 | * The original version of this source code and documentation is copyrighted 31 | * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These 32 | * materials are provided under terms of a License Agreement between Taligent 33 | * and Sun. This technology is protected by multiple US and International 34 | * patents. This notice and attribution to Taligent may not be removed. 35 | * Taligent is a registered trademark of Taligent, Inc. 36 | * 37 | */ 38 | 39 | package com.vonchange.common.util.exception; 40 | 41 | /** 42 | * Signals that an error has been reached unexpectedly 43 | * while parsing. 44 | * @see java.lang.Exception 45 | * @see java.text.Format 46 | * @see java.text.FieldPosition 47 | * @author Mark Davis 48 | */ 49 | public 50 | class ParseException extends Exception { 51 | 52 | private static final long serialVersionUID = 2703218443322787634L; 53 | 54 | /** 55 | * Constructs a ParseException with the specified detail message and 56 | * offset. 57 | * A detail message is a String that describes this particular exception. 58 | * 59 | * @param s the detail message 60 | * @param errorOffset the position where the error is found while parsing. 61 | */ 62 | public ParseException(String s, int errorOffset) { 63 | super(s); 64 | this.errorOffset = errorOffset; 65 | } 66 | 67 | /** 68 | * Returns the position where the error was found. 69 | * 70 | * @return the position where the error was found 71 | */ 72 | public int getErrorOffset () { 73 | return errorOffset; 74 | } 75 | 76 | //============ privates ============ 77 | /** 78 | * The zero-based character offset into the string being parsed at which 79 | * the error was found during parsing. 80 | * @serial 81 | */ 82 | private int errorOffset; 83 | } 84 | -------------------------------------------------------------------------------- /common-util/src/main/java/com/vonchange/common/util/exception/UtilException.java: -------------------------------------------------------------------------------- 1 | 2 | package com.vonchange.common.util.exception; 3 | 4 | 5 | public class UtilException extends CommonRuntimeException { 6 | private static final long serialVersionUID = -8919479339352899374L; 7 | 8 | public UtilException(EnumUtilErrorCode code) { 9 | super(code); 10 | } 11 | public UtilException(EnumUtilErrorCode code,ErrorMsg message) { 12 | super(code,message); 13 | } 14 | public EnumUtilErrorCode getErrorCode() { 15 | return (EnumUtilErrorCode) super.getErrorCode(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /common-util/src/main/java/com/vonchange/common/util/map/HashMapFluent.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.common.util.map; 2 | 3 | import com.vonchange.common.util.ConvertUtil; 4 | 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | 8 | /** 9 | * 支持链式调用的HashMap 10 | * 11 | * @author von_change@163.com 12 | * 2015-6-14 下午10:37:59 13 | * @param 14 | * @param 15 | */ 16 | public class HashMapFluent extends HashMap implements VMap{ 17 | 18 | public HashMapFluent() { 19 | super(); 20 | } 21 | 22 | public HashMapFluent(Map map) { 23 | super(map); 24 | } 25 | 26 | public HashMapFluent set(K key, V value) { 27 | super.put(key, value); 28 | return this; 29 | } 30 | 31 | @Override 32 | public HashMapFluent setAll(Map vMap) { 33 | super.putAll(vMap); 34 | return null; 35 | } 36 | 37 | @Override 38 | public T get(K key, Class type) { 39 | return ConvertUtil.toObject(super.get(key),type); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /common-util/src/main/java/com/vonchange/common/util/map/VMap.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.common.util.map; 2 | 3 | import java.util.Map; 4 | 5 | public interface VMap extends Map { 6 | public VMap set(K key, V value); 7 | VMap setAll(Map vMap); 8 | T get(K key, Class type); 9 | } 10 | -------------------------------------------------------------------------------- /common-util/src/main/java/com/vonchange/common/util/map/VarMap.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.common.util.map; 2 | 3 | public class VarMap extends HashMapFluent implements VMap{ 4 | 5 | } -------------------------------------------------------------------------------- /common-util/src/main/java/com/vonchange/common/util/model/BaseField.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.common.util.model; 2 | 3 | public class BaseField { 4 | private String fieldName; 5 | private Class type; 6 | 7 | public String getFieldName() { 8 | return fieldName; 9 | } 10 | 11 | public void setFieldName(String fieldName) { 12 | this.fieldName = fieldName; 13 | } 14 | 15 | public Class getType() { 16 | return type; 17 | } 18 | 19 | public void setType(Class type) { 20 | this.type = type; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /common-util/src/test/java/AsmTest.java: -------------------------------------------------------------------------------- 1 | import com.esotericsoftware.reflectasm.MethodAccess; 2 | import org.junit.Test; 3 | 4 | import java.time.LocalDateTime; 5 | 6 | public class AsmTest { 7 | @Test 8 | public void asmParentTest(){ 9 | UserModel userModel = new UserModel(); 10 | MethodAccess ma = MethodAccess.get(UserModel.class); 11 | int index = ma.getIndex("setUpdateTime"); 12 | for (String methodName : ma.getMethodNames()) { 13 | System.out.println(methodName); 14 | } 15 | System.out.println(ma.getClass()); 16 | 17 | ma.invoke(userModel, index, LocalDateTime.now()); 18 | System.out.println(userModel.getUpdateTime()); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /common-util/src/test/java/BaseModel.java: -------------------------------------------------------------------------------- 1 | public class BaseModel extends RootModel{ 2 | private String id; 3 | 4 | public String getId() { 5 | return id; 6 | } 7 | 8 | public void setId(String id) { 9 | this.id = id; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /common-util/src/test/java/MarkdownUtilTest.java: -------------------------------------------------------------------------------- 1 | import com.vonchange.common.util.MarkdownUtil; 2 | import org.junit.Test; 3 | 4 | public class MarkdownUtilTest { 5 | 6 | 7 | @Test 8 | public void markdownUtilTest(){ 9 | String content = MarkdownUtil.getContent("config.test.sql2"); 10 | System.out.println(content); 11 | 12 | } 13 | @Test 14 | public void markdownUtilTest2(){ 15 | String content = MarkdownUtil.getContent("config.test.sql1"); 16 | System.out.println(content); 17 | } 18 | 19 | 20 | } 21 | -------------------------------------------------------------------------------- /common-util/src/test/java/RootModel.java: -------------------------------------------------------------------------------- 1 | import java.time.LocalDateTime; 2 | import java.util.Date; 3 | 4 | public class RootModel { 5 | private Integer isDelete; 6 | private Date createTime; 7 | private LocalDateTime updateTime; 8 | 9 | public Integer getIsDelete() { 10 | return isDelete; 11 | } 12 | 13 | public void setIsDelete(Integer isDelete) { 14 | this.isDelete = isDelete; 15 | } 16 | 17 | public Date getCreateTime() { 18 | return createTime; 19 | } 20 | 21 | public void setCreateTime(Date createTime) { 22 | this.createTime = createTime; 23 | } 24 | 25 | public LocalDateTime getUpdateTime() { 26 | return updateTime; 27 | } 28 | 29 | public void setUpdateTime(LocalDateTime updateTime) { 30 | this.updateTime = updateTime; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /common-util/src/test/java/Test1.java: -------------------------------------------------------------------------------- 1 | public class Test1 { 2 | private Integer i ; 3 | private Integer num ; 4 | 5 | public Test1() { 6 | } 7 | 8 | public int getI() { 9 | return i; 10 | } 11 | 12 | public void setI(int i) { 13 | this.i = i; 14 | } 15 | 16 | public int getNum() { 17 | return num; 18 | } 19 | 20 | public void setNum(int num) { 21 | this.num = num; 22 | } 23 | } -------------------------------------------------------------------------------- /common-util/src/test/java/Test2.java: -------------------------------------------------------------------------------- 1 | import com.esotericsoftware.reflectasm.MethodAccess; 2 | 3 | import java.lang.reflect.InvocationTargetException; 4 | import java.lang.reflect.Method; 5 | 6 | public class Test2 { 7 | 8 | public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { 9 | long now; 10 | Test1 t = new Test1(); 11 | long sum=0; 12 | now = System.currentTimeMillis(); 13 | for(int i = 0; i<500000000; ++i){ 14 | t.setNum(i); 15 | } 16 | System.out.println("get-set耗时"+(System.currentTimeMillis() - now) + "ms秒,和是" +sum); 17 | 18 | now = System.currentTimeMillis(); 19 | 20 | for(int i = 0; i<5000000; ++i){ 21 | Class c = Class.forName("Test1"); 22 | Class[] argsType = new Class[1]; 23 | argsType[0] = int.class; 24 | Method m = c.getMethod("setNum", argsType); 25 | m.invoke(t, i); 26 | } 27 | System.out.println("标准反射耗时"+(System.currentTimeMillis() - now) + "ms,和是" +sum); 28 | now = System.currentTimeMillis(); 29 | Class c = Class.forName("Test1"); 30 | Class[] argsType = new Class[1]; 31 | argsType[0] = int.class; 32 | Method m = c.getMethod("setNum", argsType); 33 | System.out.println("缓存 初始化"+(System.currentTimeMillis() - now) + "ms,和是" ); 34 | now = System.currentTimeMillis(); 35 | 36 | for(int i = 0; i<500000000; ++i){ 37 | m.invoke(t, i); 38 | } 39 | System.out.println("缓存反射耗时"+(System.currentTimeMillis() - now) + "ms,和是" ); 40 | now = System.currentTimeMillis(); 41 | MethodAccess ma = MethodAccess.get(Test1.class); 42 | System.out.println("reflectasm初始化 "+(System.currentTimeMillis() - now) + "ms,和是" ); 43 | int index = ma.getIndex("setNum"); 44 | 45 | System.out.println("reflectasm初始化 "+(System.currentTimeMillis() - now) + "ms,和是" ); 46 | 47 | now = System.currentTimeMillis(); 48 | for(int i = 0; i<500000000; ++i){ 49 | ma.invoke(t, index, i); 50 | } 51 | System.out.println("reflectasm反射耗时"+(System.currentTimeMillis() - now) + "ms,和是" ); 52 | now = System.currentTimeMillis(); 53 | for(int i = 0; i<500000000; ++i){ 54 | ma.invoke(t, "setNum", i); 55 | } 56 | System.out.println("reflectasm反射耗时"+(System.currentTimeMillis() - now) + "ms,和是" ); 57 | //InputStream inputStream = .getClassLoader().getResourceAsStream("test.xml"); 58 | 59 | } 60 | } -------------------------------------------------------------------------------- /common-util/src/test/java/UserModel.java: -------------------------------------------------------------------------------- 1 | public class UserModel extends BaseModel{ 2 | private String userCode; 3 | private String userName; 4 | 5 | private Test1 test1; 6 | 7 | public String getUserCode() { 8 | return userCode; 9 | } 10 | 11 | public void setUserCode(String userCode) { 12 | this.userCode = userCode; 13 | } 14 | 15 | public String getUserName() { 16 | return userName; 17 | } 18 | 19 | public void setUserName(String userName) { 20 | this.userName = userName; 21 | } 22 | 23 | public Test1 getTest1() { 24 | return test1; 25 | } 26 | 27 | public void setTest1(Test1 test1) { 28 | this.test1 = test1; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /common-util/src/test/resources/config/test.md: -------------------------------------------------------------------------------- 1 | ```sql 2 | -- findById 3 | select [@id column] from user where id = #{id} 4 | ``` 5 | 6 | ```sql 7 | select [@id column] from user limit 100 8 | ``` 9 | 10 | 11 | ```sql 12 | -- column 13 | user_id,user_name 14 | ``` -------------------------------------------------------------------------------- /curd-repository.md: -------------------------------------------------------------------------------- 1 | ## first We don't need global updates, and this is a dangerous operation 2 | 3 | ``` 4 | long count(); 5 | void deleteAll(); 6 | Iterable findAll(); 7 | ``` 8 | 9 | ## deleteById is ok 10 | 11 | ``` 12 | void delete(T entity); 13 | void deleteAll(Iterable entities); 14 | ``` 15 | 16 | ## add methods return update num 17 | ``` 18 | int saveAll(Iterable entities,int batchSize); 19 | int update(S entity); 20 | int updateAllField(S entity); 21 | ``` -------------------------------------------------------------------------------- /easy-dynamic-sql.md: -------------------------------------------------------------------------------- 1 | 2 | > [@and id in idList] 3 | ``` xml 4 | and id in #{item} 7 | ``` 8 | 9 | > [@@and id in idList] 10 | 11 | ``` xml 12 | and id in #{item} 15 | ``` 16 | 17 | [@and user_name = userName] 18 | ```xml 19 | 20 | and user_name = #{userName} 21 | 22 | ``` 23 | [@and user_name like userName%] 24 | ```xml 25 | 26 | and user_name like CONCAT(?,'%') 27 | 28 | ``` 29 | 30 | > [@id column] 31 | 32 | ``` 33 | -- column 34 | id,code,user_name,mobile_phone,address,create_time 35 | ``` 36 | 37 | [@and id in #{idList:in} and user_name like #{userName:like}] 38 | ```xml 39 | 40 | and id in 41 | 42 | #{item} 43 | and user_name like CONCAT('%',#{userName},'%') 44 | 45 | ``` -------------------------------------------------------------------------------- /jdbc-mybatis/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-data-jdbc-mybatis-parent 7 | com.vonchange.common 8 | 2.5.0 9 | 10 | 4.0.0 11 | jdbc-mybatis 12 | 2.5.1 13 | 14 | 15 | com.vonchange.common 16 | mybatis-sql-extend 17 | 2.5.1 18 | 19 | 20 | com.vonchange.common 21 | jsqlparser 22 | 1.1 23 | 24 | 25 | com.vonchange.common 26 | mybati 27 | 3.5.2.3 28 | 29 | 30 | org.hibernate.javax.persistence 31 | hibernate-jpa-2.1-api 32 | 1.0.0.Final 33 | 34 | 35 | org.springframework.data 36 | spring-data-commons 37 | 2.1.5.RELEASE 38 | provided 39 | 40 | 41 | org.springframework 42 | spring-jdbc 43 | 5.1.5.RELEASE 44 | provided 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /jdbc-mybatis/src/main/java/com/vonchange/jdbc/annotation/ColumnNot.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.jdbc.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | *排除字段 10 | */ 11 | @Retention(RetentionPolicy.RUNTIME) 12 | @Target({ElementType.FIELD}) 13 | public @interface ColumnNot { 14 | 15 | } 16 | -------------------------------------------------------------------------------- /jdbc-mybatis/src/main/java/com/vonchange/jdbc/annotation/InsertOnlyProperty.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.jdbc.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Retention(RetentionPolicy.RUNTIME) 9 | @Target({ElementType.FIELD}) 10 | public @interface InsertOnlyProperty { 11 | 12 | } 13 | -------------------------------------------------------------------------------- /jdbc-mybatis/src/main/java/com/vonchange/jdbc/annotation/InsertReturn.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.jdbc.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | *排除字段 10 | */ 11 | @Retention(RetentionPolicy.RUNTIME) 12 | @Target({ElementType.FIELD}) 13 | public @interface InsertReturn { 14 | 15 | } 16 | -------------------------------------------------------------------------------- /jdbc-mybatis/src/main/java/com/vonchange/jdbc/client/CrudClient.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.jdbc.client;/* 2 | * Copyright 2002-2023 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | import com.vonchange.jdbc.config.ConstantJdbc; 19 | import com.vonchange.jdbc.core.DefaultCrudClient; 20 | import com.vonchange.jdbc.mapper.AbstractPageWork; 21 | import com.vonchange.jdbc.model.DataSourceWrapper; 22 | import com.vonchange.mybatis.dialect.MySQLDialect; 23 | import org.springframework.data.domain.Page; 24 | import org.springframework.data.domain.Pageable; 25 | import org.springframework.lang.Nullable; 26 | 27 | import java.util.List; 28 | import java.util.Map; 29 | import java.util.concurrent.ConcurrentHashMap; 30 | 31 | public interface CrudClient { 32 | static Map crudClientMap = new ConcurrentHashMap<>(); 33 | static CrudClient create(DataSourceWrapper dataSourceWrapper) { 34 | if(null==dataSourceWrapper.getKey()){ 35 | dataSourceWrapper.setKey(ConstantJdbc.DataSourceDefault); 36 | } 37 | String key = dataSourceWrapper.getKey(); 38 | if(crudClientMap.containsKey(key)){ 39 | return crudClientMap.get(key); 40 | } 41 | if(null==dataSourceWrapper.getDialect()){ 42 | dataSourceWrapper.setDialect(new MySQLDialect()); 43 | } 44 | CrudClient crudClient=new DefaultCrudClient(dataSourceWrapper); 45 | crudClientMap.put(dataSourceWrapper.getKey(),crudClient); 46 | return crudClient; 47 | } 48 | StatementSpec sqlId(String sqlId); 49 | 50 | JdbcClient jdbc(); 51 | 52 | int insert(T entity); 53 | int insertBatch(List entities,boolean ifNullInsertByFirstEntity); 54 | int update(T entity); 55 | int updateBatch(List entities,boolean ifNullUpdateByFirstEntity); 56 | interface StatementSpec { 57 | StatementSpec namespace(X service); 58 | StatementSpec param(String name, @Nullable Object value); 59 | StatementSpec params(Map paramMap); 60 | MappedQuerySpec query(Class mappedClass); 61 | int update(); 62 | int updateBatch(List entities); 63 | 64 | void queryBatch(Class mappedClass, AbstractPageWork pageWork); 65 | 66 | } 67 | 68 | 69 | interface MappedQuerySpec { 70 | List list(); 71 | 72 | Page page(Pageable pageable); 73 | 74 | Iterable iterable(); 75 | T single(); 76 | } 77 | 78 | } 79 | -------------------------------------------------------------------------------- /jdbc-mybatis/src/main/java/com/vonchange/jdbc/client/JdbcClient.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.jdbc.client;/* 2 | * Copyright 2002-2023 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | import com.vonchange.jdbc.config.ConstantJdbc; 19 | import com.vonchange.jdbc.model.DataSourceWrapper; 20 | import com.vonchange.mybatis.dialect.MySQLDialect; 21 | import org.springframework.data.domain.Page; 22 | import org.springframework.data.domain.Pageable; 23 | import org.springframework.lang.Nullable; 24 | 25 | import java.util.Collection; 26 | import java.util.List; 27 | import java.util.Map; 28 | import java.util.concurrent.ConcurrentHashMap; 29 | 30 | public interface JdbcClient { 31 | public static Map jdbcClientMap = new ConcurrentHashMap<>(); 32 | static JdbcClient create(DataSourceWrapper dataSourceWrapper) { 33 | if(null==dataSourceWrapper.getKey()){ 34 | dataSourceWrapper.setKey(ConstantJdbc.DataSourceDefault); 35 | } 36 | String key = dataSourceWrapper.getKey(); 37 | if(jdbcClientMap.containsKey(key)){ 38 | return jdbcClientMap.get(key); 39 | } 40 | if(null==dataSourceWrapper.getDialect()){ 41 | dataSourceWrapper.setDialect(new MySQLDialect()); 42 | } 43 | JdbcClient jdbcClient=new DefaultJdbcClient(dataSourceWrapper); 44 | jdbcClientMap.put(dataSourceWrapper.getKey(),jdbcClient); 45 | return jdbcClient; 46 | } 47 | StatementSpec sql(String sqlId); 48 | interface StatementSpec { 49 | StatementSpec param(Object value); 50 | 51 | //StatementSpec params(Object... values); 52 | 53 | StatementSpec params(Collection values); 54 | 55 | StatementSpec param(String name, @Nullable Object value); 56 | StatementSpec params(Map paramMap); 57 | MappedQuerySpec query(Class mappedClass); 58 | int update(); 59 | } 60 | 61 | 62 | interface MappedQuerySpec { 63 | List list(); 64 | 65 | Page page(Pageable pageable); 66 | 67 | Iterable iterable(); 68 | T single(); 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /jdbc-mybatis/src/main/java/com/vonchange/jdbc/config/ConstantJdbc.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.jdbc.config; 2 | 3 | /** 4 | * Created by 冯昌义 on 2018/3/20. 5 | */ 6 | public class ConstantJdbc { 7 | private ConstantJdbc() { throw new IllegalStateException("Utility class");} 8 | 9 | public static final String DataSourceDefault= "dataSource"; 10 | public static final String EntityType= "entityType"; 11 | public static final String SqlPackage= "sql."; 12 | public static final String SQL_START= "@sql"; 13 | public static final String COUNTFLAG = "Count"; 14 | public static final String MybatisIndexParam = "p"; 15 | public static final String OptimisticLockingFailureExceptionMessage="Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)"; 16 | } 17 | -------------------------------------------------------------------------------- /jdbc-mybatis/src/main/java/com/vonchange/jdbc/config/EnumMappedClass.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.jdbc.config; 2 | 3 | public enum EnumMappedClass { 4 | base,map,bean 5 | } 6 | -------------------------------------------------------------------------------- /jdbc-mybatis/src/main/java/com/vonchange/jdbc/config/EnumNameQueryType.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.jdbc.config; 2 | 3 | public enum EnumNameQueryType { 4 | Find,Count,Exists,Delete,Update 5 | } 6 | -------------------------------------------------------------------------------- /jdbc-mybatis/src/main/java/com/vonchange/jdbc/config/EnumRWType.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.jdbc.config; 2 | 3 | public enum EnumRWType { 4 | read,write; 5 | } -------------------------------------------------------------------------------- /jdbc-mybatis/src/main/java/com/vonchange/jdbc/config/EnumSqlRead.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.jdbc.config; 2 | 3 | public enum EnumSqlRead { 4 | markdown,sql,mybatis,name 5 | 6 | } 7 | -------------------------------------------------------------------------------- /jdbc-mybatis/src/main/java/com/vonchange/jdbc/core/JdbcLogUtil.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.jdbc.core; 2 | 3 | import com.vonchange.jdbc.config.EnumRWType; 4 | import com.vonchange.jdbc.util.SqlFill; 5 | import com.vonchange.jdbc.model.SqlParam; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | 9 | public class JdbcLogUtil { 10 | private static final Logger log = LoggerFactory.getLogger(JdbcLogUtil.class); 11 | public static void logSql(EnumRWType enumRWType, SqlParam sqlParam) { 12 | logSql(enumRWType, sqlParam.getSql(), sqlParam.getParams().toArray()); 13 | } 14 | public static void logSql(EnumRWType enumRWType, String sql, Object... params) { 15 | if (log.isDebugEnabled()) { 16 | try{ 17 | String sqlResult = SqlFill.fill(sql, params); 18 | log.debug("full sql: {}", sqlResult); 19 | }catch (Exception e){ 20 | log.warn("logFull {}",e.getMessage()); 21 | log.debug("org sql: {} params: {}", sql, params); 22 | } 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /jdbc-mybatis/src/main/java/com/vonchange/jdbc/mapper/AbstractPageWork.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.jdbc.mapper; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | /** 7 | * 8 | * Created by 冯昌义 on 2018/4/17. 9 | */ 10 | public abstract class AbstractPageWork { 11 | private long totalElements; 12 | private int totalPages; 13 | private int size; 14 | protected abstract void doPage(List pageContentList, int pageNum, Map extData); 15 | protected abstract int getPageSize(); 16 | 17 | public long getTotalElements() { 18 | return totalElements; 19 | } 20 | 21 | public void setTotalElements(long totalElements) { 22 | this.totalElements = totalElements; 23 | } 24 | 25 | public int getTotalPages() { 26 | return totalPages; 27 | } 28 | 29 | public void setTotalPages(int totalPages) { 30 | this.totalPages = totalPages; 31 | } 32 | 33 | public int getSize() { 34 | return size; 35 | } 36 | 37 | public void setSize(int size) { 38 | this.size = size; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /jdbc-mybatis/src/main/java/com/vonchange/jdbc/mapper/BeanInsertMapper.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.jdbc.mapper; 2 | 3 | import com.vonchange.common.util.UtilAll; 4 | import com.vonchange.common.util.exception.ErrorMsg; 5 | import com.vonchange.jdbc.core.CrudUtil; 6 | import com.vonchange.jdbc.model.EntityInfo; 7 | import com.vonchange.jdbc.util.ConvertMap; 8 | import com.vonchange.jdbc.util.EntityUtil; 9 | import com.vonchange.mybatis.exception.EnumJdbcErrorCode; 10 | import com.vonchange.mybatis.exception.JdbcMybatisRuntimeException; 11 | import org.springframework.jdbc.core.ResultSetExtractor; 12 | 13 | import java.sql.ResultSet; 14 | import java.sql.SQLException; 15 | import java.util.Collections; 16 | import java.util.List; 17 | 18 | public class BeanInsertMapper implements ResultSetExtractor { 19 | private final List entities; 20 | 21 | 22 | public BeanInsertMapper(List entities) { 23 | this.entities = entities; 24 | } 25 | public BeanInsertMapper(T entity) { 26 | this.entities = Collections.singletonList(entity); 27 | } 28 | 29 | 30 | @Override 31 | public Void extractData(ResultSet rs) throws SQLException { 32 | int i=0; 33 | while (rs.next()){ 34 | toBean(rs,entities.get(i)); 35 | i++; 36 | } 37 | return null; 38 | } 39 | 40 | private void toBean(ResultSet rs, T entity) throws SQLException { 41 | EntityInfo entityInfo = EntityUtil.getEntityInfo(entity.getClass()); 42 | String idFieldName = entityInfo.getIdFieldName(); 43 | if(UtilAll.UString.isBlank(idFieldName)){ 44 | throw new JdbcMybatisRuntimeException(EnumJdbcErrorCode.NeedIdAnnotation, 45 | ErrorMsg.builder().message("need @Id in your entity")); 46 | } 47 | ConvertMap.toBean(CrudUtil.rowToMap(entityInfo,rs,idFieldName),entity); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /jdbc-mybatis/src/main/java/com/vonchange/jdbc/mapper/BeanMapper.java: -------------------------------------------------------------------------------- 1 | 2 | package com.vonchange.jdbc.mapper; 3 | 4 | import com.vonchange.jdbc.config.EnumMappedClass; 5 | import com.vonchange.jdbc.util.ConvertMap; 6 | import com.vonchange.jdbc.util.EntityUtil; 7 | import com.vonchange.jdbc.model.EntityInfo; 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | import org.springframework.jdbc.core.ResultSetExtractor; 11 | 12 | import java.sql.ResultSet; 13 | import java.sql.SQLException; 14 | import java.util.ArrayList; 15 | import java.util.List; 16 | 17 | /** 18 | * ResultSetHandler implementation that converts a 19 | * ResultSet into a List of beans. This class is 20 | * thread safe. 21 | * 22 | * @param the target processor type 23 | */ 24 | public class BeanMapper implements ResultSetExtractor> { 25 | 26 | private static final Logger log = LoggerFactory.getLogger(BeanMapper.class); 27 | 28 | private final Class mappedClass; 29 | 30 | public BeanMapper(Class mappedClass) { 31 | this.mappedClass = mappedClass; 32 | } 33 | 34 | @Override 35 | public List extractData(ResultSet rs) throws SQLException { 36 | EnumMappedClass enumMappedClass = ConvertMap.enumMappedClass(mappedClass); 37 | EntityInfo entityInfo = null; 38 | if(enumMappedClass.equals(EnumMappedClass.bean)){ 39 | entityInfo = EntityUtil.getEntityInfo(mappedClass); 40 | } 41 | List results = new ArrayList<>(); 42 | while (rs.next()){ 43 | results.add(ConvertMap.toMappedClass(rs,mappedClass,enumMappedClass,entityInfo)); 44 | } 45 | return results; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /jdbc-mybatis/src/main/java/com/vonchange/jdbc/model/BaseEntityField.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.jdbc.model; 2 | 3 | public class BaseEntityField { 4 | private String fieldName; 5 | private String columnName; 6 | private Class type; 7 | private Boolean ifColumn = true; 8 | 9 | public String getFieldName() { 10 | return fieldName; 11 | } 12 | 13 | public void setFieldName(String fieldName) { 14 | this.fieldName = fieldName; 15 | } 16 | 17 | public String getColumnName() { 18 | return columnName; 19 | } 20 | 21 | public void setColumnName(String columnName) { 22 | this.columnName = columnName; 23 | } 24 | 25 | public Class getType() { 26 | return type; 27 | } 28 | 29 | public void setType(Class type) { 30 | this.type = type; 31 | } 32 | 33 | public Boolean getIfColumn() { 34 | return ifColumn; 35 | } 36 | 37 | public void setIfColumn(Boolean ifColumn) { 38 | this.ifColumn = ifColumn; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /jdbc-mybatis/src/main/java/com/vonchange/jdbc/model/BaseSqlParam.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.jdbc.model; 2 | 3 | import java.util.Collection; 4 | 5 | public class BaseSqlParam { 6 | private String sql; 7 | private Collection params; 8 | 9 | public BaseSqlParam(String sql, Collection params) { 10 | this.sql = sql; 11 | this.params = params; 12 | } 13 | 14 | public String getSql() { 15 | return sql; 16 | } 17 | 18 | public Collection getParams() { 19 | return params; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /jdbc-mybatis/src/main/java/com/vonchange/jdbc/model/DataSourceWrapper.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.jdbc.model; 2 | 3 | import com.vonchange.mybatis.dialect.Dialect; 4 | 5 | import javax.sql.DataSource; 6 | 7 | public class DataSourceWrapper { 8 | 9 | 10 | private DataSource dataSource; 11 | private String key; 12 | private Dialect dialect; 13 | public DataSourceWrapper(DataSource dataSource,String key,Dialect dialect){ 14 | this.dataSource=dataSource; 15 | this.key=key; 16 | this.dialect=dialect; 17 | } 18 | public void setKey(String key) { 19 | this.key = key; 20 | } 21 | public DataSource getDataSource() { 22 | return dataSource; 23 | } 24 | 25 | public Dialect getDialect() { 26 | return dialect; 27 | } 28 | 29 | public DataSourceWrapper setDialect(Dialect dialect) { 30 | this.dialect = dialect; 31 | return this; 32 | } 33 | 34 | public String getKey() { 35 | return key; 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /jdbc-mybatis/src/main/java/com/vonchange/jdbc/model/EntityField.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.jdbc.model; 2 | 3 | /** 4 | * 实体字段信息 5 | * 6 | * @author vonchange@163.com 7 | */ 8 | public class EntityField extends BaseEntityField{ 9 | 10 | private Boolean ifId = false; 11 | 12 | private Boolean updateNot=false; 13 | private Boolean insertNot=false; 14 | 15 | private Boolean version=false; 16 | 17 | 18 | public Boolean getIfId() { 19 | return ifId; 20 | } 21 | 22 | public void setIfId(Boolean ifId) { 23 | this.ifId = ifId; 24 | } 25 | 26 | public Boolean getVersion() { 27 | return version; 28 | } 29 | 30 | public void setVersion(Boolean version) { 31 | this.version = version; 32 | } 33 | 34 | public Boolean getUpdateNot() { 35 | return updateNot; 36 | } 37 | 38 | public void setUpdateNot(Boolean updateNot) { 39 | this.updateNot = updateNot; 40 | } 41 | 42 | public Boolean getInsertNot() { 43 | return insertNot; 44 | } 45 | 46 | public void setInsertNot(Boolean insertNot) { 47 | this.insertNot = insertNot; 48 | } 49 | 50 | 51 | } 52 | -------------------------------------------------------------------------------- /jdbc-mybatis/src/main/java/com/vonchange/jdbc/model/EntityInfo.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.jdbc.model; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | /** 7 | * 实体信息 8 | * @author vonchange@163.com 9 | */ 10 | public class EntityInfo { 11 | private String entityName; 12 | private String tableName; 13 | private String idFieldName; 14 | private String idColumnName; 15 | private String idType; 16 | 17 | private List columnReturns; 18 | private List entityFields; 19 | 20 | private Map fieldMap; 21 | private Map columnMap; 22 | 23 | public String getEntityName() { 24 | return entityName; 25 | } 26 | 27 | public void setEntityName(String entityName) { 28 | this.entityName = entityName; 29 | } 30 | 31 | public String getTableName() { 32 | return tableName; 33 | } 34 | 35 | public void setTableName(String tableName) { 36 | this.tableName = tableName; 37 | } 38 | 39 | public String getIdFieldName() { 40 | return idFieldName; 41 | } 42 | 43 | 44 | public Map getColumnMap() { 45 | return columnMap; 46 | } 47 | 48 | public void setColumnMap(Map columnMap) { 49 | this.columnMap = columnMap; 50 | } 51 | 52 | public void setIdFieldName(String idFieldName) { 53 | this.idFieldName = idFieldName; 54 | } 55 | 56 | public String getIdColumnName() { 57 | return idColumnName; 58 | } 59 | 60 | public void setIdColumnName(String idColumnName) { 61 | this.idColumnName = idColumnName; 62 | } 63 | 64 | public String getIdType() { 65 | return idType; 66 | } 67 | 68 | public void setIdType(String idType) { 69 | this.idType = idType; 70 | } 71 | 72 | public Map getFieldMap() { 73 | return fieldMap; 74 | } 75 | 76 | public void setFieldMap(Map fieldMap) { 77 | this.fieldMap = fieldMap; 78 | } 79 | 80 | public List getEntityFields() { 81 | return entityFields; 82 | } 83 | 84 | public void setEntityFields(List entityFields) { 85 | this.entityFields = entityFields; 86 | } 87 | 88 | public List getColumnReturns() { 89 | return columnReturns; 90 | } 91 | 92 | public void setColumnReturns(List columnReturns) { 93 | this.columnReturns = columnReturns; 94 | } 95 | 96 | 97 | } 98 | -------------------------------------------------------------------------------- /jdbc-mybatis/src/main/java/com/vonchange/jdbc/model/EnumCondition.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.jdbc.model; 2 | 3 | public enum EnumCondition { 4 | Eq("="),Order("order"); 5 | EnumCondition(String condition){ 6 | this.condition=condition; 7 | } 8 | private String condition; 9 | 10 | public String getCondition() { 11 | return condition; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /jdbc-mybatis/src/main/java/com/vonchange/jdbc/model/EnumStep.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.jdbc.model; 2 | 3 | public enum EnumStep { 4 | Column,Condition,Join,Value,End,ORDER; 5 | 6 | EnumStep() { 7 | } 8 | 9 | } 10 | -------------------------------------------------------------------------------- /jdbc-mybatis/src/main/java/com/vonchange/jdbc/model/QueryColumn.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.jdbc.model; 2 | 3 | public class QueryColumn { 4 | 5 | private String join; 6 | private String column; 7 | private String condition; 8 | private Object value; 9 | public QueryColumn(){ 10 | 11 | } 12 | public QueryColumn(String column, String condition, Object value) { 13 | this.column = column; 14 | this.condition = condition; 15 | this.value = value; 16 | } 17 | 18 | public String getColumn() { 19 | return column; 20 | } 21 | 22 | public String getJoin() { 23 | return join; 24 | } 25 | 26 | public void setJoin(String join) { 27 | this.join = join; 28 | } 29 | 30 | public void setColumn(String column) { 31 | this.column = column; 32 | } 33 | 34 | public String getCondition() { 35 | return condition; 36 | } 37 | 38 | public void setCondition(String condition) { 39 | this.condition = condition; 40 | } 41 | 42 | public Object getValue() { 43 | return value; 44 | } 45 | 46 | public void setValue(Object value) { 47 | this.value = value; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /jdbc-mybatis/src/main/java/com/vonchange/jdbc/model/SqlMatch.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.jdbc.model; 2 | 3 | public class SqlMatch { 4 | private String split; 5 | private EnumStep enumStep; 6 | public SqlMatch(){ 7 | 8 | } 9 | public SqlMatch(String split, EnumStep enumStep) { 10 | this.split = split; 11 | this.enumStep = enumStep; 12 | } 13 | 14 | public String getSplit() { 15 | return split; 16 | } 17 | 18 | public void setSplit(String split) { 19 | this.split = split; 20 | } 21 | 22 | public EnumStep getEnumStep() { 23 | return enumStep; 24 | } 25 | 26 | public void setEnumStep(EnumStep enumStep) { 27 | this.enumStep = enumStep; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /jdbc-mybatis/src/main/java/com/vonchange/jdbc/model/SqlParam.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.jdbc.model; 2 | 3 | import com.vonchange.jdbc.config.EnumSqlRead; 4 | 5 | import java.util.Collection; 6 | import java.util.List; 7 | 8 | /** 9 | * @author 冯昌义 10 | */ 11 | public class SqlParam{ 12 | private String sql; 13 | private Collection params; 14 | private List propertyNames; 15 | private List columnReturns; 16 | 17 | private Boolean version=false; 18 | private EnumSqlRead sqlRead; 19 | 20 | public SqlParam(String sql, Collection params) { 21 | this.sql = sql; 22 | this.params = params; 23 | } 24 | public String getSql() { 25 | return sql; 26 | } 27 | 28 | public Collection getParams() { 29 | return params; 30 | } 31 | public EnumSqlRead getSqlRead() { 32 | return sqlRead; 33 | } 34 | 35 | public void setSqlRead(EnumSqlRead sqlRead) { 36 | this.sqlRead = sqlRead; 37 | } 38 | 39 | public Boolean getVersion() { 40 | return version; 41 | } 42 | 43 | public void setVersion(Boolean version) { 44 | this.version = version; 45 | } 46 | 47 | public List getPropertyNames() { 48 | return propertyNames; 49 | } 50 | 51 | public void setPropertyNames(List propertyNames) { 52 | this.propertyNames = propertyNames; 53 | } 54 | 55 | 56 | public List getColumnReturns() { 57 | return columnReturns; 58 | } 59 | 60 | public void setColumnReturns(List columnReturns) { 61 | this.columnReturns = columnReturns; 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /jdbc-mybatis/src/main/java/com/vonchange/jdbc/util/ConvertMap.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.jdbc.util; 2 | 3 | import com.vonchange.common.util.Assert; 4 | import com.vonchange.common.util.ClazzUtils; 5 | import com.vonchange.common.util.ConvertUtil; 6 | import com.vonchange.common.util.bean.BeanUtil; 7 | import com.vonchange.common.util.exception.ErrorMsg; 8 | import com.vonchange.jdbc.config.EnumMappedClass; 9 | import com.vonchange.jdbc.core.CrudUtil; 10 | import com.vonchange.jdbc.model.EntityInfo; 11 | import com.vonchange.mybatis.exception.EnumJdbcErrorCode; 12 | import com.vonchange.mybatis.exception.JdbcMybatisRuntimeException; 13 | import org.springframework.jdbc.support.JdbcUtils; 14 | 15 | import java.sql.ResultSet; 16 | import java.sql.SQLException; 17 | import java.util.Map; 18 | 19 | public class ConvertMap { 20 | private ConvertMap() { 21 | throw new IllegalStateException("Utility class"); 22 | } 23 | 24 | 25 | /** 26 | * Map to JavaBean 27 | */ 28 | @SuppressWarnings("unchecked") 29 | public static T toBean(Map orgMap,T entity) { 30 | Assert.notNull(entity,"entity can not null"); 31 | for (Map.Entry entry : orgMap.entrySet()) { 32 | BeanUtil.setProperty(entity,entry.getKey(),entry.getValue()); 33 | } 34 | return entity; 35 | } 36 | public static EnumMappedClass enumMappedClass(Class mappedClass){ 37 | if(ClazzUtils.isBaseType(mappedClass)){ 38 | return EnumMappedClass.base; 39 | } 40 | if(mappedClass == Map.class){ 41 | return EnumMappedClass.map; 42 | } 43 | return EnumMappedClass.bean; 44 | } 45 | public static T toMappedClass(ResultSet rs, Class mappedClass,EnumMappedClass enumMappedClass,EntityInfo entityInfo) throws SQLException { 46 | if(null==enumMappedClass){ 47 | enumMappedClass=enumMappedClass(mappedClass); 48 | } 49 | if(enumMappedClass.equals(EnumMappedClass.base)){ 50 | return ConvertUtil.toObject(JdbcUtils.getResultSetValue(rs, 1),mappedClass); 51 | } 52 | if(enumMappedClass.equals(EnumMappedClass.map)){ 53 | return (T) CrudUtil.rowToMap(null,rs,null); 54 | } 55 | if(null==entityInfo){ 56 | entityInfo = EntityUtil.getEntityInfo(mappedClass); 57 | } 58 | return ConvertMap.toBean(CrudUtil.rowToMap(entityInfo,rs,null),mappedClass); 59 | } 60 | public static T toBean(Map map,Class type){ 61 | Assert.notNull(type,"need class type"); 62 | T entity =null; 63 | try { 64 | entity = (T) type.newInstance(); 65 | } catch (InstantiationException | IllegalAccessException e) { 66 | throw new JdbcMybatisRuntimeException(EnumJdbcErrorCode.NewInstanceError, 67 | ErrorMsg.builder().message("java.lang.InstantiationException {} need no-arguments constructor",type.getName())); 68 | } 69 | return toBean(map,entity); 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /jdbc-mybatis/src/main/java/com/vonchange/jdbc/util/JdbcUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.vonchange.jdbc.util; 17 | 18 | 19 | import org.springframework.jdbc.support.JdbcUtils; 20 | 21 | import java.math.BigDecimal; 22 | import java.math.BigInteger; 23 | import java.sql.Date; 24 | import java.sql.Time; 25 | import java.sql.Timestamp; 26 | import java.sql.Types; 27 | import java.util.HashMap; 28 | import java.util.Map; 29 | 30 | /** 31 | * Contains methods dealing with the quirks of JDBC, independent of any Entity, Aggregate or Repository abstraction. 32 | * 33 | * @author Jens Schauder 34 | */ 35 | public class JdbcUtil { 36 | 37 | private static final Map, Integer> sqlTypeMappings = new HashMap<>(); 38 | 39 | static { 40 | 41 | sqlTypeMappings.put(String.class, Types.VARCHAR); 42 | sqlTypeMappings.put(BigInteger.class, Types.BIGINT); 43 | sqlTypeMappings.put(BigDecimal.class, Types.NUMERIC); 44 | sqlTypeMappings.put(Byte.class, Types.TINYINT); 45 | sqlTypeMappings.put(byte.class, Types.TINYINT); 46 | sqlTypeMappings.put(Short.class, Types.SMALLINT); 47 | sqlTypeMappings.put(short.class, Types.SMALLINT); 48 | sqlTypeMappings.put(Integer.class, Types.INTEGER); 49 | sqlTypeMappings.put(int.class, Types.INTEGER); 50 | sqlTypeMappings.put(Long.class, Types.BIGINT); 51 | sqlTypeMappings.put(long.class, Types.BIGINT); 52 | sqlTypeMappings.put(Double.class, Types.DOUBLE); 53 | sqlTypeMappings.put(double.class, Types.DOUBLE); 54 | sqlTypeMappings.put(Float.class, Types.REAL); 55 | sqlTypeMappings.put(float.class, Types.REAL); 56 | sqlTypeMappings.put(Boolean.class, Types.BIT); 57 | sqlTypeMappings.put(boolean.class, Types.BIT); 58 | sqlTypeMappings.put(byte[].class, Types.VARBINARY); 59 | sqlTypeMappings.put(Date.class, Types.DATE); 60 | sqlTypeMappings.put(Time.class, Types.TIME); 61 | sqlTypeMappings.put(Timestamp.class, Types.TIMESTAMP); 62 | } 63 | 64 | public static int sqlTypeFor(Class type) { 65 | return sqlTypeMappings.keySet().stream() // 66 | .filter(k -> k.isAssignableFrom(type)) // 67 | .findFirst() // 68 | .map(sqlTypeMappings::get) // 69 | .orElse(JdbcUtils.TYPE_UNKNOWN); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /jdbc-mybatis/src/main/java/com/vonchange/jdbc/util/OrmUtil.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.jdbc.util; 2 | 3 | 4 | import com.vonchange.common.util.UtilAll; 5 | 6 | /** 7 | * Orm field 8 | * 9 | */ 10 | public class OrmUtil { 11 | /** 12 | * _ to up 13 | * 14 | */ 15 | public static String toFiled(String colName) { 16 | return toUp(colName); 17 | } 18 | private static String toUp(String colName){ 19 | if(null==colName||!colName.contains("_")){ 20 | return colName; 21 | } 22 | StringBuilder sb = new StringBuilder(); 23 | boolean flag = false; 24 | for (int i = 0; i < colName.length(); i++) { 25 | char cur = colName.charAt(i); 26 | if (cur == '_') { 27 | flag = true; 28 | 29 | } else { 30 | if (flag) { 31 | sb.append(Character.toUpperCase(cur)); 32 | flag = false; 33 | } else { 34 | sb.append(Character.toLowerCase(cur)); 35 | } 36 | } 37 | } 38 | return sb.toString(); 39 | } 40 | 41 | 42 | /** 43 | * Hql to sql 44 | * 45 | */ 46 | public static String toSql(String myHql) { 47 | StringBuilder sb = new StringBuilder(); 48 | boolean flag = false; 49 | boolean isLetter = false; 50 | for (int i = 0; i < myHql.length(); i++) { 51 | char cur = myHql.charAt(i); 52 | if (cur == '_') { 53 | throw new RuntimeException("not allow _ !"); 54 | } 55 | if (cur == ':') { 56 | flag = true; 57 | } 58 | if (cur != ':' && !Character.isLetter(cur)) { 59 | flag = false; 60 | } 61 | if (flag) { 62 | sb.append(cur); 63 | continue; 64 | } 65 | if (Character.isUpperCase(cur) && isLetter) { 66 | sb.append("_"); 67 | sb.append(Character.toLowerCase(cur)); 68 | } else { 69 | sb.append(Character.toLowerCase(cur)); 70 | } 71 | if (!Character.isLetter(cur)) { 72 | isLetter = false; 73 | } else { 74 | isLetter = true; 75 | } 76 | } 77 | return sb.toString(); 78 | } 79 | 80 | /** 81 | * toEntity 82 | */ 83 | public static String toEntity(String tableName) { 84 | return UtilAll.UString.capitalize(toUp(tableName)); 85 | } 86 | 87 | 88 | 89 | 90 | } 91 | -------------------------------------------------------------------------------- /jdbc-mybatis/src/main/java/com/vonchange/jdbc/util/SqlFill.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.jdbc.util; 2 | 3 | 4 | import com.vonchange.common.util.TimeUtil; 5 | 6 | import java.time.LocalDate; 7 | import java.time.LocalDateTime; 8 | import java.time.LocalTime; 9 | import java.util.Date; 10 | 11 | /** 12 | * 填充sql 13 | * 14 | * @author von_change@163.com 15 | * 2016年4月6日 下午6:07:00 16 | * @since 1.0 17 | */ 18 | public class SqlFill { 19 | private SqlFill() { 20 | throw new IllegalStateException("Utility class"); 21 | } 22 | 23 | private static String getParameterValue(Object obj) { 24 | if (null == obj) { 25 | return "NULL"; 26 | } 27 | if (obj instanceof String||obj.getClass().isEnum()) { 28 | // 排除恶意sql漏洞 29 | //return "'" + obj.toString().replaceAll("([';])+|(--)+", "") + "'"; 30 | return "'" + obj.toString() + "'"; 31 | } 32 | if (obj instanceof Date) { 33 | return "'"+ TimeUtil.fromDate((Date) obj).toString()+"'"; 34 | //return "'" + DateFormatUtils.format((Date) obj, FORMAT) + "'"; 35 | } 36 | if(obj instanceof LocalDateTime|| obj instanceof LocalDate || obj instanceof LocalTime){ 37 | return "'"+obj.toString()+"'"; 38 | } 39 | return obj.toString(); 40 | } 41 | 42 | public static String fill(String source, Object[] params) { 43 | if (null == params || params.length == 0) { 44 | return source; 45 | } 46 | //[ \x0B]+ "[\s]+ 47 | String sql = source.replaceAll("[ \\x0B]+", " ");//去掉多余空格 48 | char[] chars = sql.toCharArray(); 49 | StringBuilder sb = new StringBuilder(); 50 | char j; 51 | int p = 0; 52 | for (int i = 0; i < chars.length; i++) { 53 | j = chars[i]; 54 | if (j == '?') { 55 | sb.append(getParameterValue(params[p]));// 56 | p++; 57 | } else { 58 | sb.append(j); 59 | } 60 | } 61 | return sb.toString(); 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /method-name-query.md: -------------------------------------------------------------------------------- 1 | ## method name query 2 | 3 | | keyword | sample | SQL | 4 | |:--------|:--------------------------------|:---------------------------------------------------------------------------------------------------------------------------| 5 | | And | findByLastnameAndFirstname | ... where lastname = ? and firstname = ? | 6 | | Or | findByLastnameOrFirstname | ... where lastname = ? or firstname = ? | 7 | | Is, Eq | findByLastnameEq/findByLastname | … where lastname = ? | 8 | | not | findByLastnameNot | … where lastname != ? | 9 | | Between | findByStartDateBetween | … where startDate between ? and ? | 10 | | Lt | findByStartDateLt | … where startDate > ? | 11 | | Lte | findByStartDateLte | … where startDate >= ? | 12 | | Gt | findByStartDateGr | … where startDate > ? | 13 | | Gte | findByStartDateGte | … where startDate >= ? | 14 | | After | findByStartDateAfter | … where startDate > ? | 15 | | Before | findByStartDateBefore | … where startDate < ? | 16 | | Like | findByFirstnameLike | … where firstname like ? | 17 | | NotLike | findByFirstnameNotLike | … where firstname not like ? | 18 | | OrderBy | findByAgeOrderByLastnameDesc | … where age = ? order by lastname desc | 19 | | in | findByAgeIn | … where age in (?,?) | 20 | | NotIn | findByAgeNotIn | … where age not in (?,?) | -------------------------------------------------------------------------------- /multi-datasource.md: -------------------------------------------------------------------------------- 1 | 2 | ```java 3 | @Configuration 4 | public class DbConfig { 5 | @Bean(name = "dataSource") 6 | @Primary 7 | @ConfigurationProperties(prefix = "spring.datasource") 8 | public DataSource mainDataSource() { 9 | return DataSourceBuilder.create().build(); 10 | } 11 | 12 | @Bean(name = "orderDataSource") 13 | @ConfigurationProperties(prefix = "spring.datasource.order") 14 | public DataSource oldDataSource() { 15 | return DataSourceBuilder.create().build(); 16 | } 17 | 18 | @Bean("dataSourceWrapper") 19 | public DataSourceWrapper dataSourceWrapper(@Qualifier("dataSource")DataSource dataSource) { 20 | return new DataSourceWrapper(dataSource,"dataSource"); 21 | } 22 | 23 | 24 | @Bean("orderDataSourceWrapper") 25 | public DataSourceWrapper oldDataSourceWrapper(@Qualifier("orderDataSource")DataSource dataSource) { 26 | return new DataSourceWrapper(dataSource,"orderDataSource"); 27 | } 28 | 29 | } 30 | ``` 31 | 32 | ```java 33 | @DataSourceKey("orderDataSource") 34 | public interface OrderQueryDao extends QueryRepository { 35 | } 36 | ``` -------------------------------------------------------------------------------- /mybatis-sql-extend-test/src/main/java/com/vonchange/mybatis/MybatisSqlExtendTestApplication.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.mybatis; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | //@SpringBootApplication(exclude={JdbcConfiguration.class}) 7 | @SpringBootApplication 8 | //@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) 9 | public class MybatisSqlExtendTestApplication { 10 | 11 | public static void main(String[] args) { 12 | 13 | SpringApplication.run(MybatisSqlExtendTestApplication.class, args); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /mybatis-sql-extend-test/src/main/java/com/vonchange/mybatis/test/config/BaseCrudMapper.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.mybatis.test.config; 2 | 3 | import org.apache.ibatis.annotations.Insert; 4 | import org.apache.ibatis.annotations.Options; 5 | 6 | public interface BaseCrudMapper { 7 | 8 | 9 | @Insert("@UserMapper.insert") 10 | @Options(useGeneratedKeys = true,keyProperty = "id") 11 | public ID insert(T instance); 12 | } 13 | -------------------------------------------------------------------------------- /mybatis-sql-extend-test/src/main/java/com/vonchange/mybatis/test/config/SimpleLanguageDriver.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.mybatis.test.config; 2 | 3 | import org.apache.ibatis.mapping.SqlSource; 4 | import org.apache.ibatis.scripting.xmltags.XMLLanguageDriver; 5 | import org.apache.ibatis.session.Configuration; 6 | 7 | import com.vonchange.mybatis.dialect.MySQLDialect; 8 | import com.vonchange.mybatis.language.MybatisSqlLanguageUtil; 9 | 10 | public class SimpleLanguageDriver extends XMLLanguageDriver { 11 | @Override 12 | public SqlSource createSqlSource(Configuration configuration, String script, Class parameterType) { 13 | String sqlInXml = MybatisSqlLanguageUtil.sqlInXml("mapper", script, new MySQLDialect()); 14 | return super.createSqlSource(configuration, sqlInXml, parameterType); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /mybatis-sql-extend-test/src/main/java/com/vonchange/mybatis/test/config/UserBaseDO.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.mybatis.test.config; 2 | 3 | 4 | 5 | 6 | import lombok.AllArgsConstructor; 7 | import lombok.Data; 8 | 9 | 10 | import java.time.LocalDateTime; 11 | import java.util.Date; 12 | 13 | @Data 14 | @AllArgsConstructor 15 | public class UserBaseDO { 16 | 17 | 18 | private Long id; 19 | 20 | private String code; 21 | 22 | private String userName; 23 | private String mobilePhone; 24 | 25 | private Integer isDelete; 26 | 27 | private LocalDateTime createTime; 28 | 29 | private Date updateTime; 30 | 31 | private byte[] headImageData; 32 | public UserBaseDO(){ 33 | 34 | } 35 | 36 | 37 | 38 | 39 | } 40 | -------------------------------------------------------------------------------- /mybatis-sql-extend-test/src/main/java/com/vonchange/mybatis/test/config/UserMapper.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.mybatis.test.config; 2 | 3 | import org.apache.ibatis.annotations.Insert; 4 | import org.apache.ibatis.annotations.Mapper; 5 | import org.apache.ibatis.annotations.Options; 6 | import org.apache.ibatis.annotations.Param; 7 | import org.apache.ibatis.annotations.Select; 8 | 9 | import java.time.LocalDateTime; 10 | import java.util.List; 11 | 12 | @Mapper 13 | public interface UserMapper{ 14 | @Insert("@UserMapper.insert") 15 | @Options(useGeneratedKeys = true,keyProperty = "id") 16 | int insert(UserBaseDO userBaseDO); 17 | @Select(" ") 26 | List findListOrg(@Param("userName") String userName, 27 | @Param("createTime") LocalDateTime createTime); 28 | 29 | @Select("@UserMapper.findList") 30 | List findList(@Param("userName") String userName, 31 | @Param("createTime") LocalDateTime createTime); 32 | 33 | 34 | 35 | } 36 | -------------------------------------------------------------------------------- /mybatis-sql-extend-test/src/main/resources/application-h2.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | datasource: 3 | hikari: 4 | driver-class-name: org.h2.Driver 5 | #jdbc-url: jdbc:h2:mem:test;DB_CLOSE_DELAY=-1 6 | jdbc-url: jdbc:h2:mem:db_users;MODE=MYSQL;INIT=RUNSCRIPT FROM 'classpath:db-init.sql' 7 | username: root 8 | password: 123456 9 | 10 | mybatis: 11 | default-scripting-language-driver: com.vonchange.mybatis.test.config.SimpleLanguageDriver 12 | configuration: 13 | map-underscore-to-camel-case: true 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /mybatis-sql-extend-test/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | profiles: 3 | active: local 4 | application: 5 | name: mybatis-sql-extend 6 | datasource: 7 | hikari: 8 | driver-class-name: com.mysql.cj.jdbc.Driver 9 | jdbc-url: jdbc:mysql://127.0.0.1:3306/nine_user?autoReconnect=true&rewriteBatchedStatements=true&allowMultiQueries=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=CTT 10 | username: root 11 | password: 123456 12 | connection-timeout: 20000 13 | minimum-idle: 5 14 | maximum-pool-size: 20 15 | idle-timeout: 60000 16 | max-lifetime: 600000 17 | leak-detection-threshold: 20000 18 | 19 | mybatis: 20 | default-scripting-language-driver: com.vonchange.mybatis.test.config.SimpleLanguageDriver 21 | configuration: 22 | map-underscore-to-camel-case: true 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /mybatis-sql-extend-test/src/main/resources/db-init.sql: -------------------------------------------------------------------------------- 1 | SET MODE=MySQL; 2 | SET FOREIGN_KEY_CHECKS=0; 3 | drop table if exists `user_base`; 4 | CREATE TABLE IF NOT EXISTS `user_base` ( 5 | `id` bigint(13) NOT NULL AUTO_INCREMENT COMMENT 'id序列,自增', 6 | `code` varchar(36) DEFAULT NULL COMMENT '编码', 7 | `user_name` varchar(30) DEFAULT NULL COMMENT '用户名', 8 | `mobile_phone` varchar(13) DEFAULT NULL COMMENT '手机号', 9 | `address` varchar(20) DEFAULT NULL COMMENT 'address', 10 | `is_delete` tinyint(1) DEFAULT '0' COMMENT '是否已删除', 11 | `create_time` datetime DEFAULT NULL COMMENT '创建时间', 12 | `update_time` datetime DEFAULT NULL COMMENT '更新时间', 13 | `head_image_data` blob DEFAULT NULL COMMENT '头像', 14 | PRIMARY KEY (`id`) 15 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 16 | insert into user_base(id,code,user_name,mobile_phone,address,create_time) values (1,UUID(),'test','120','xxx',now()); 17 | insert into user_base(user_name,mobile_phone,address,create_time) values ('李4','110','xxx额',now()); 18 | insert into user_base(user_name,mobile_phone,address,create_time,update_time) values ('张三日子','911','xxx是啥',now(),now()); 19 | insert into user_base(user_name,mobile_phone,address,create_time) values ('test','333','ufo',now()); -------------------------------------------------------------------------------- /mybatis-sql-extend-test/src/main/resources/mapper/UserMapper.md: -------------------------------------------------------------------------------- 1 | ``` 2 | -- insert 3 | insert into user_base(user_name) values (#{userName}) 4 | ``` 5 | ``` 6 | -- findList 7 | select * from user_base 8 | [@sql findListWhereSql] 9 | ``` 10 | 11 | > sql 片段 12 | ``` 13 | -- findListWhereSql 14 | 15 | [@@and user_name like userName] 16 | [@and create_time < createTime] 17 | 18 | ``` 19 | 20 | 21 | 22 | ``` 23 | -- findListOrg 24 | select * from user_base 25 | 26 | and user_name like CONCAT('%',#{userName},'%') 27 | 28 | [@and create_time < createTime] 29 | 30 | 31 | 32 | ``` -------------------------------------------------------------------------------- /mybatis-sql-extend-test/src/test/java/com/vonchange/mybatis/test/MybatisSqlExtendTest.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.mybatis.test; 2 | 3 | import com.vonchange.common.util.JsonUtil; 4 | import com.vonchange.mybatis.test.config.UserBaseDO; 5 | import com.vonchange.mybatis.test.config.UserMapper; 6 | import lombok.extern.slf4j.Slf4j; 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | import org.springframework.boot.test.context.SpringBootTest; 10 | import org.springframework.test.context.junit4.SpringRunner; 11 | 12 | import javax.annotation.Resource; 13 | import java.time.LocalDateTime; 14 | import java.util.List; 15 | 16 | @RunWith(SpringRunner.class) 17 | @SpringBootTest 18 | @Slf4j 19 | public class MybatisSqlExtendTest { 20 | 21 | @Resource 22 | private UserMapper userMapper; 23 | 24 | @Test 25 | public void sqlExtendTest(){ 26 | System.err.println("XXXXXX"); 27 | List userBaseDOList = userMapper.findList("test", LocalDateTime.now().plusHours(1L)); 28 | userBaseDOList.forEach(userBaseDO -> { 29 | log.info("\n {}", JsonUtil.toJson(userBaseDO)); 30 | }); 31 | userBaseDOList = userMapper.findList("test", LocalDateTime.now().plusHours(1L)); 32 | userBaseDOList.forEach(userBaseDO -> { 33 | log.info("\n {}", JsonUtil.toJson(userBaseDO)); 34 | }); 35 | userBaseDOList = userMapper.findList("test", LocalDateTime.now().plusHours(1L)); 36 | userBaseDOList.forEach(userBaseDO -> { 37 | log.info("\n {}", JsonUtil.toJson(userBaseDO)); 38 | }); 39 | } 40 | 41 | @Test 42 | public void sqlExtendTestOrg(){ 43 | List userBaseDOList = userMapper.findListOrg("test", LocalDateTime.now().plusHours(1L)); 44 | userBaseDOList.forEach(userBaseDO -> { 45 | log.info("\n {}", JsonUtil.toJson(userBaseDO)); 46 | }); 47 | } 48 | 49 | @Test 50 | public void insert(){ 51 | UserBaseDO userBaseDO = new UserBaseDO(); 52 | userBaseDO.setUserName("2333"); 53 | userMapper.insert(userBaseDO); 54 | System.out.println(userBaseDO.getId()); 55 | //System.out.println(result); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /mybatis-sql-extend.md: -------------------------------------------------------------------------------- 1 | == mybatis-spring-boot extend 2 | 3 | ### dependency 4 | ``` 5 | 6 | com.vonchange.common 7 | mybatis-sql-extend 8 | ${spring.mybatis.mini} 9 | 10 | ``` 11 | ### config 12 | [config](mybatis-sql-extend-test/src/main/java/com/vonchange/mybatis/test/config/SimpleLanguageDriver.java) 13 | ``` 14 | public class SimpleLanguageDriver extends XMLLanguageDriver implements LanguageDriver { 15 | @Override 16 | public SqlSource createSqlSource(Configuration configuration, String script, Class parameterType) { 17 | String sqlInXml = MybatisSqlLanguageUtil.sqlInXml("mapper",script,new MySQLDialect()); 18 | return super.createSqlSource(configuration, sqlInXml, parameterType); 19 | } 20 | } 21 | ``` 22 | 23 | ![例子](https://image.yonghuivip.com/20221031/4a9e97a668f84bbcbf8b8214630efb4d/sql.png) 24 | > [UserMapper.md 文件](mybatis-sql-extend-test/src/main/resources/mapper/UserMapper.md) 25 | 26 | ``` 27 | -- 配置 28 | mybatis: 29 | default-scripting-language-driver: com.vonchange.mybatis.test.config.SimpleLanguageDriver 30 | configuration: 31 | map-underscore-to-camel-case: true 32 | 33 | ``` -------------------------------------------------------------------------------- /mybatis-sql-extend/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-data-jdbc-mybatis-parent 7 | com.vonchange.common 8 | 2.5.0 9 | 10 | 4.0.0 11 | mybatis-sql-extend 12 | 2.5.1 13 | 14 | 15 | com.vonchange.common 16 | common-util 17 | 2.5.1 18 | 19 | 20 | org.slf4j 21 | slf4j-api 22 | 2.0.11 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /mybatis-sql-extend/src/main/java/com/vonchange/mybatis/dialect/Dialect.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.mybatis.dialect; 2 | 3 | 4 | /** 5 | *方言接口 6 | * @author von_change@163.com 7 | * 2015-6-14 下午12:46:50 8 | */ 9 | public interface Dialect { 10 | 11 | /** 12 | * 获取分页的sql 13 | * @param sql 要分页sql 14 | * @param beginNo 开始数 15 | * @return 分页sql 16 | */ 17 | String getPageSql(String sql, int beginNo, int pageSize); 18 | int getBigDataFetchSize(); 19 | int getFetchSize(); 20 | String getDialogName(); 21 | LikeTemplate getLikeTemplate(); 22 | } 23 | -------------------------------------------------------------------------------- /mybatis-sql-extend/src/main/java/com/vonchange/mybatis/dialect/H2MySqlDialect.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.mybatis.dialect; 2 | 3 | public class H2MySqlDialect extends MySQLDialect { 4 | @Override 5 | public int getBigDataFetchSize() { 6 | return 500; 7 | } 8 | 9 | @Override 10 | public int getFetchSize() { 11 | return -1; 12 | } 13 | 14 | @Override 15 | public String getDialogName() { 16 | return "h2-mysql"; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /mybatis-sql-extend/src/main/java/com/vonchange/mybatis/dialect/LikeTemplate.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.mybatis.dialect; 2 | 3 | public class LikeTemplate { 4 | private String full; 5 | private String left; 6 | private String right; 7 | 8 | public LikeTemplate(String full, String left, String right) { 9 | this.full = full; 10 | this.left = left; 11 | this.right = right; 12 | } 13 | 14 | public String getFull() { 15 | return full; 16 | } 17 | 18 | public void setFull(String full) { 19 | this.full = full; 20 | } 21 | 22 | public String getLeft() { 23 | return left; 24 | } 25 | 26 | public void setLeft(String left) { 27 | this.left = left; 28 | } 29 | 30 | public String getRight() { 31 | return right; 32 | } 33 | 34 | public void setRight(String right) { 35 | this.right = right; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /mybatis-sql-extend/src/main/java/com/vonchange/mybatis/dialect/MariaDialect.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.mybatis.dialect; 2 | 3 | public class MariaDialect extends MySQLDialect { 4 | } 5 | -------------------------------------------------------------------------------- /mybatis-sql-extend/src/main/java/com/vonchange/mybatis/dialect/MySQLDialect.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.mybatis.dialect; 2 | 3 | 4 | import com.vonchange.common.util.ConvertUtil; 5 | import com.vonchange.common.util.UtilAll; 6 | 7 | 8 | /** 9 | *mysql方言 10 | * @author von_change@163.com 11 | * 2015-6-14 下午12:47:21 12 | */ 13 | public class MySQLDialect implements Dialect { 14 | 15 | @Override 16 | public String getPageSql(String sql, int beginNo, int pageSize) { 17 | return UtilAll.UString.format("{} limit {},{} ", sql, ConvertUtil.toString(beginNo), ConvertUtil.toString(pageSize)); 18 | } 19 | 20 | 21 | 22 | @Override 23 | public int getBigDataFetchSize() { 24 | return Integer.MIN_VALUE; 25 | } 26 | 27 | @Override 28 | public int getFetchSize() { 29 | return -1; 30 | } 31 | 32 | @Override 33 | public String getDialogName() { 34 | return "mysql"; 35 | } 36 | 37 | @Override 38 | public LikeTemplate getLikeTemplate() { 39 | return new LikeTemplate(" CONCAT('%',#{{}},'%') "," CONCAT('%',#{{}})"," CONCAT(#{{}},'%') "); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /mybatis-sql-extend/src/main/java/com/vonchange/mybatis/dialect/OracleDialect.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.mybatis.dialect; 2 | 3 | 4 | import com.vonchange.common.util.ConvertUtil; 5 | import com.vonchange.common.util.UtilAll; 6 | 7 | 8 | /** 9 | * 10 | * Created by 冯昌义 on 2018/4/16. 11 | */ 12 | public class OracleDialect implements Dialect { 13 | @Override 14 | public String getPageSql(String sql, int beginNo, int pageSize) { 15 | if(beginNo==0){ 16 | String sqlLimit="{}" + 17 | " fetch first {} rows only" ; 18 | return UtilAll.UString.format(sqlLimit, sql, ConvertUtil.toString(pageSize)); 19 | } 20 | String sqlOrg="{}" + 21 | " offset {} rows fetch next {} rows only " ; 22 | return UtilAll.UString.format(sqlOrg, sql, ConvertUtil.toString(beginNo), ConvertUtil.toString(pageSize)); 23 | } 24 | 25 | 26 | @Override 27 | public int getBigDataFetchSize() { 28 | return 500; 29 | } 30 | 31 | @Override 32 | public int getFetchSize() { 33 | return 500; 34 | } 35 | 36 | @Override 37 | public String getDialogName() { 38 | return "oracle"; 39 | } 40 | 41 | @Override 42 | public LikeTemplate getLikeTemplate() { 43 | return new LikeTemplate(" ''%''||#{{}}||''%'' "," ''%''||#{{}} "," #{{}}||''%'' "); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /mybatis-sql-extend/src/main/java/com/vonchange/mybatis/dialect/OracleLowDialect.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.mybatis.dialect; 2 | 3 | public class OracleLowDialect implements Dialect { 4 | @Override 5 | public String getPageSql(String sql, int beginNo, int pageSize) { 6 | return "select * from (select row_.*, rownum rownum_ from (" + sql + ")row_ where rownum <= " + (beginNo + pageSize) + 7 | " ) where rownum_ >= " + (beginNo + 1); 8 | } 9 | 10 | @Override 11 | public int getBigDataFetchSize() { 12 | return 500; 13 | } 14 | 15 | @Override 16 | public int getFetchSize() { 17 | return 500; 18 | } 19 | 20 | @Override 21 | public String getDialogName() { 22 | return "oracle_low"; 23 | } 24 | 25 | @Override 26 | public LikeTemplate getLikeTemplate() { 27 | return new LikeTemplate(" ''%''||#'{'{0}'}'||''%'' "," ''%''||#'{'{0}'}' "," #'{'{0}'}'||''%'' "); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /mybatis-sql-extend/src/main/java/com/vonchange/mybatis/dialect/PostgresDialect.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.mybatis.dialect; 2 | 3 | import com.vonchange.common.util.ConvertUtil; 4 | import com.vonchange.common.util.UtilAll; 5 | 6 | public class PostgresDialect implements Dialect { 7 | @Override 8 | public String getPageSql(String sql, int beginNo, int pageSize) { 9 | return UtilAll.UString.format("{} limit {} OFFSET {} ", sql,ConvertUtil.toString(pageSize), ConvertUtil.toString(beginNo)); 10 | } 11 | 12 | @Override 13 | public int getBigDataFetchSize() { 14 | return 500; 15 | } 16 | 17 | @Override 18 | public int getFetchSize() { 19 | return 500; 20 | } 21 | 22 | @Override 23 | public String getDialogName() { 24 | return "postgres"; 25 | } 26 | 27 | @Override 28 | public LikeTemplate getLikeTemplate() { 29 | return new LikeTemplate(" CONCAT('%',#{{}},'%') "," CONCAT('%',#{{}})"," CONCAT(#{{}},'%') "); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /mybatis-sql-extend/src/main/java/com/vonchange/mybatis/exception/EnumJdbcErrorCode.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.mybatis.exception; 2 | 3 | public enum EnumJdbcErrorCode { 4 | Error,CanNotGenNameQuery, OrderSqlMustStartWithOrderBy, OrderSqlCanNotGen, NotSupportClass, FieldNotAllowed, ParamEmpty, NeedIdAnnotation, MustArray, SqlIdNotFound, MybatisSqlError, PlaceholderNotFound, NewInstanceError, TypeError, SqlError, DataSourceNotFound; 5 | public static final String CanNotGenNameQueryMessage="{} can not generate sql by method name,must start with find or count,please define in the markdown"; 6 | } 7 | -------------------------------------------------------------------------------- /mybatis-sql-extend/src/main/java/com/vonchange/mybatis/exception/JdbcMybatisRuntimeException.java: -------------------------------------------------------------------------------- 1 | 2 | package com.vonchange.mybatis.exception; 3 | 4 | 5 | import com.vonchange.common.util.exception.CommonRuntimeException; 6 | import com.vonchange.common.util.exception.ErrorMsg; 7 | 8 | public class JdbcMybatisRuntimeException extends CommonRuntimeException { 9 | 10 | private static final long serialVersionUID = 4638320203258180664L; 11 | public JdbcMybatisRuntimeException(EnumJdbcErrorCode errorCode) { 12 | super(errorCode); 13 | } 14 | public JdbcMybatisRuntimeException(EnumJdbcErrorCode errorCode, ErrorMsg message) { 15 | super(errorCode,message); 16 | } 17 | public EnumJdbcErrorCode getErrorCode() { 18 | return (EnumJdbcErrorCode) super.getErrorCode(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /mybatis-sql-extend/src/main/java/com/vonchange/mybatis/language/MybatisSqlLanguageUtil.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.mybatis.language; 2 | 3 | import com.vonchange.common.util.MarkdownUtil; 4 | import com.vonchange.common.util.UtilAll; 5 | import com.vonchange.mybatis.dialect.Dialect; 6 | 7 | import com.vonchange.mybatis.sql.DynamicSql; 8 | 9 | 10 | public class MybatisSqlLanguageUtil { 11 | /** 12 | * 13 | * @param prePackage 前缀报名 比如mapper 14 | * @param script sqlInXml 15 | * @param dialect 方言 16 | */ 17 | public static String sqlInXml(String prePackage,String script, Dialect dialect){ 18 | String sqlInXml = script; 19 | if (script.startsWith("@")) { 20 | String sqlId = script.substring(1); 21 | sqlInXml = MarkdownUtil.getContent(null==prePackage?sqlId:(prePackage+"."+sqlId)); 22 | sqlInXml = DynamicSql.dynamicSql(sqlInXml,dialect); 23 | sqlInXml = sqlInXml.trim(); 24 | if (sqlInXml.contains("" + sqlInXml + ""; 26 | sqlInXml = UtilAll.UString.replaceEach(sqlInXml, new String[]{" > ", " < ", " >= ", " <= ", " <> "}, 27 | new String[]{" > ", " < ", " >= ", " <= ", " <> "}); 28 | } 29 | } 30 | return sqlInXml; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /mybatis-sql-extend/src/main/java/com/vonchange/mybatis/sql/AnalyeNamed.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.mybatis.sql; 2 | 3 | /** 4 | * 分析后的实体类 5 | */ 6 | public class AnalyeNamed { 7 | private String condition; 8 | //private String type; 9 | /** 10 | * 1 String 2 其他 base 3:list 4.arr 11 | */ 12 | private String namedFull; 13 | private String itemProperty; 14 | private String link; 15 | //private Object value; 16 | private String column; 17 | 18 | public String getCondition() { 19 | return condition; 20 | } 21 | 22 | public void setCondition(String condition) { 23 | this.condition = condition; 24 | } 25 | 26 | 27 | 28 | 29 | 30 | 31 | public String getNamedFull() { 32 | return namedFull; 33 | } 34 | 35 | public void setNamedFull(String namedFull) { 36 | this.namedFull = namedFull; 37 | } 38 | 39 | public String getItemProperty() { 40 | return itemProperty; 41 | } 42 | 43 | public void setItemProperty(String itemProperty) { 44 | this.itemProperty = itemProperty; 45 | } 46 | 47 | public String getLink() { 48 | return link; 49 | } 50 | 51 | public void setLink(String link) { 52 | this.link = link; 53 | } 54 | 55 | public String getColumn() { 56 | return column; 57 | } 58 | 59 | public void setColumn(String column) { 60 | this.column = column; 61 | } 62 | 63 | 64 | } 65 | -------------------------------------------------------------------------------- /mybatis-sql-extend/src/main/java/com/vonchange/mybatis/sql/SqlParamResult.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.mybatis.sql; 2 | 3 | import java.util.List; 4 | 5 | public class SqlParamResult { 6 | private List param; 7 | private String newSql; 8 | 9 | public SqlParamResult(List param, String newSql) { 10 | this.param = param; 11 | this.newSql = newSql; 12 | } 13 | 14 | public List getParam() { 15 | return param; 16 | } 17 | 18 | public void setParam(List param) { 19 | this.param = param; 20 | } 21 | 22 | public String getNewSql() { 23 | return newSql; 24 | } 25 | 26 | public void setNewSql(String newSql) { 27 | this.newSql = newSql; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /mybatis-sql-extend/src/main/java/com/vonchange/mybatis/tpl/MyOgnl.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.mybatis.tpl; 2 | 3 | import java.util.Collection; 4 | import java.util.Map; 5 | 6 | public class MyOgnl { 7 | private static boolean isBlank(final CharSequence cs) { 8 | int strLen; 9 | if (cs == null || (strLen = cs.length()) == 0) { 10 | return true; 11 | } 12 | for (int i = 0; i < strLen; i++) { 13 | if (Character.isWhitespace(cs.charAt(i)) == false) { 14 | return false; 15 | } 16 | } 17 | return true; 18 | } 19 | 20 | public static boolean isEmpty(Object value) { 21 | if (null == value) { 22 | return true; 23 | } 24 | if (value instanceof String) { 25 | if (isBlank((String) value)) { 26 | return true; 27 | } 28 | return false; 29 | } 30 | if (value instanceof Collection) { 31 | if (((Collection) value).isEmpty()) { 32 | return true; 33 | } 34 | return false; 35 | } 36 | if (value.getClass().isArray()) { 37 | if (((Object[]) value).length == 0) { 38 | return true; 39 | } 40 | return false; 41 | } 42 | if (value instanceof Map) { 43 | if (((Map) value).isEmpty()) { 44 | return true; 45 | } 46 | return false; 47 | } 48 | return false; 49 | } 50 | 51 | public static boolean isNotEmpty(Object value) { 52 | return !isEmpty(value); 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /recommend.md: -------------------------------------------------------------------------------- 1 | 2 | - [欢迎点击star github地址](https://github.com/VonChange/spring-data-jdbc-mybatis) 3 | - [欢迎点击star gitee地址](https://gitee.com/vonchange/spring-data-jdbc-mybatis) 4 | 5 | **简单点 开发的方法简单点 繁琐的功能请省略 你有不是个AI** 6 | ### spring data jdbc 扩展 mybatis 动态sql能力 7 | ##### 官方spring data jdbc原生直接扩展 mybatis动态sql能力 8 | 9 | 使用方式和官方教程一样 引入spring-boot-starter-data-jdbc 即可 10 | 只需要配置扩展的NamedParameterJdbcTemplate 即可 11 | ``` 12 | @Configuration 13 | public class MybatisQuerySupportConfig { 14 | @Bean 15 | public NamedParameterJdbcOperations namedParameterJdbcOperations(DataSource dataSource) { 16 | return new MybatisJdbcTemplate(dataSource) {@Override protected Dialect dialect() {return new MySQLDialect();}}; 17 | } 18 | } 19 | ``` 20 | @Query 的ID 是user.md里面ID为queryByUserCode的mybatis sql片段 21 | ``` 22 | @Query("user.queryByUserCode") 23 | List queryByUserCode(@Param("userCode") String userCode); 24 | ``` 25 | 具体使用参考spring-data-jdbc-demo 26 | 但是 @Query spring 6(jdk17以上) 以上才支持SPEL 不支持实体参数 27 | 通过改代码可以解决(支持mybatis版本的) 但有代码侵入性 28 | 无法直接 根据方法名 自动查找sql片段 29 | 30 | ##### 仿spring 6+ jdbcClient实现 更推荐crudClient 31 | ##### 更推荐自研版本spring data jdbc扩展 mybatis动态sql框架(spring-data-jdbc-mybatis) 32 | * 底层 jdbcTemplate 复杂SQL才需要mybatis动态模板能力 无QueryDSL/queryMapper 提供crudClient 和jdbcClient 33 | 34 | * 和spring data jdbc一样的追求简单,使用jdbcTemplate,调用jdbc。不提供缓存、延迟加载、QueryDSL等JPA或mybatis的许多特性。一个简单、有限的ORM 35 | 36 | * 扩展并兼容mybatis动态sql能力(不依赖mybatis!提取了动态sql代码),可以应对复杂sql,如果换其他模板引擎(后续可以加)也是可以的,但有学习成本 37 | 38 | * 复杂的SQL写在Markdown的代码片段中,更方便编写和阅读,不提供@Query和QueryDSL写法,但按方法名查找和扩展的findByExample可以应付大部分单表查询需求 39 | 40 | * 简化mybatis动态sql写法 [easy-dynamic-sql.md](easy-dynamic-sql.md) 41 | 42 | ##### 这真是缺点? 43 | 44 | - 缺点一:无QueryDSL/QueryWrapper 我是个懒人 既然service层里可以写QueryWrapper 为啥不可以写在service 为啥要重用? 45 | 要我独立个dao/Repository把数据层下放?想啥呢?! 46 | 我这个框架就只能在dao/Repository层 写确实太麻烦了 复杂的sql还得建个markdown文件 47 | - 缺点二:没有数据缓存 审计 数据脱敏 IService接口 就不能替我做了吗 非得在应用层实现 48 | 其实我这给了spring缓存框架等用武之地 自己实现可以增加代码量和工作量 在还没被ai替代之前 薅羊毛 -------------------------------------------------------------------------------- /spring-data-jdbc-demo/.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | !**/src/main/**/target/ 4 | !**/src/test/**/target/ 5 | 6 | ### IntelliJ IDEA ### 7 | .idea/modules.xml 8 | .idea/jarRepositories.xml 9 | .idea/compiler.xml 10 | .idea/libraries/ 11 | *.iws 12 | *.iml 13 | *.ipr 14 | 15 | ### Eclipse ### 16 | .apt_generated 17 | .classpath 18 | .factorypath 19 | .project 20 | .settings 21 | .springBeans 22 | .sts4-cache 23 | 24 | ### NetBeans ### 25 | /nbproject/private/ 26 | /nbbuild/ 27 | /dist/ 28 | /nbdist/ 29 | /.nb-gradle/ 30 | build/ 31 | !**/src/main/**/build/ 32 | !**/src/test/**/build/ 33 | 34 | ### VS Code ### 35 | .vscode/ 36 | 37 | ### Mac OS ### 38 | .DS_Store -------------------------------------------------------------------------------- /spring-data-jdbc-demo/README.md: -------------------------------------------------------------------------------- 1 | configuration 2 | ``` 3 | @Configuration 4 | public class MybatisQuerySupportConfig { 5 | @Bean 6 | public NamedParameterJdbcOperations namedParameterJdbcOperations(DataSource dataSource) { 7 | return new MybatisJdbcTemplate(dataSource) {@Override protected Dialect dialect() {return new MySQLDialect();}}; 8 | } 9 | } 10 | ``` 11 | dependency 12 | ```xml 13 | 14 | com.vonchange.common 15 | jdbc-mybatis 16 | ${jdbc.mybatis} 17 | 18 | 19 | ``` 20 | use 21 | ``` 22 | @Query("user.queryByUserCode") 23 | List queryByUserCode(@Param("userCode") String userCode); 24 | ``` -------------------------------------------------------------------------------- /spring-data-jdbc-demo/src/main/java/com/vonchange/common/App.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.common; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.data.jdbc.repository.config.EnableJdbcRepositories; 6 | 7 | /** 8 | * Hello world! 9 | * 10 | */ 11 | @SpringBootApplication 12 | @EnableJdbcRepositories 13 | public class App 14 | { 15 | public static void main( String[] args ) 16 | { 17 | SpringApplication.run(App.class, args); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /spring-data-jdbc-demo/src/main/java/com/vonchange/common/config/MybatisQuerySupportConfig.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.common.config; 2 | 3 | import com.vonchange.jdbc.mybatis.MybatisJdbcTemplate; 4 | import com.vonchange.mybatis.dialect.Dialect; 5 | import com.vonchange.mybatis.dialect.MySQLDialect; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations; 9 | 10 | import javax.sql.DataSource; 11 | @Configuration 12 | public class MybatisQuerySupportConfig { 13 | @Bean 14 | public NamedParameterJdbcOperations namedParameterJdbcOperations(DataSource dataSource) { 15 | return new MybatisJdbcTemplate(dataSource) {@Override protected Dialect dialect() {return new MySQLDialect();}}; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /spring-data-jdbc-demo/src/main/java/com/vonchange/common/dao/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.common.dao; 2 | 3 | import com.vonchange.common.domain.ReqUser; 4 | import com.vonchange.common.domain.UserDTO; 5 | import com.vonchange.common.domain.UserInfoDO; 6 | import org.springframework.data.domain.Page; 7 | import org.springframework.data.domain.Pageable; 8 | import org.springframework.data.jdbc.repository.query.Modifying; 9 | import org.springframework.data.jdbc.repository.query.Query; 10 | import org.springframework.data.repository.CrudRepository; 11 | import org.springframework.data.repository.query.Param; 12 | 13 | import java.util.List; 14 | 15 | public interface UserRepository extends CrudRepository { 16 | 17 | @Query("user.queryByUserCode") 18 | //@Query("select * from user_info where user_code =:userCode") 19 | List queryByUserCode(@Param("userCode") String userCode); 20 | 21 | Page findByUserCode(String userCode, Pageable pageable); 22 | //@Query("user.queryByBean") 23 | @Query("select * from user_info where user_code = #{user.userCode}") 24 | List queryByBean(@Param("user") ReqUser user); 25 | @Query("user.queryByUserCodes") 26 | //@Query("select * from user_info where user_code in (:userCodes)") 27 | List queryByUserCodes(@Param("userCodes")List userCodes); 28 | List queryByUserName(@Param("userName") String userName); 29 | @Modifying 30 | @Query("update user_info set user_name = #{user.userName} where user_code = #{user.userCode}") 31 | int updateByUserCode(@Param("user") UserDTO user); 32 | } -------------------------------------------------------------------------------- /spring-data-jdbc-demo/src/main/java/com/vonchange/common/domain/ReqUser.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.common.domain; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Builder; 5 | import lombok.Getter; 6 | import lombok.NoArgsConstructor; 7 | import lombok.Setter; 8 | 9 | @Getter 10 | @Setter 11 | @AllArgsConstructor 12 | @NoArgsConstructor 13 | @Builder 14 | public class ReqUser { 15 | private String userCode; 16 | } 17 | -------------------------------------------------------------------------------- /spring-data-jdbc-demo/src/main/java/com/vonchange/common/domain/UserDTO.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.common.domain; 2 | 3 | import lombok.Getter; 4 | import lombok.Setter; 5 | import lombok.ToString; 6 | 7 | @Getter 8 | @Setter 9 | @ToString 10 | public class UserDTO { 11 | private String userCode; 12 | private String userName; 13 | private String address; 14 | } 15 | -------------------------------------------------------------------------------- /spring-data-jdbc-demo/src/main/java/com/vonchange/common/domain/UserInfoDO.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.common.domain; 2 | 3 | 4 | import lombok.AllArgsConstructor; 5 | import lombok.Builder; 6 | import lombok.Getter; 7 | import lombok.NoArgsConstructor; 8 | import lombok.Setter; 9 | import lombok.ToString; 10 | import org.springframework.data.annotation.Id; 11 | import org.springframework.data.relational.core.mapping.Table; 12 | 13 | @Getter 14 | @Setter 15 | @Table("user_info") 16 | @Builder 17 | @AllArgsConstructor 18 | @NoArgsConstructor 19 | @ToString 20 | public class UserInfoDO { 21 | @Id 22 | private Long id; 23 | private String userCode; 24 | //@Column("user_name") 25 | private String userName; 26 | private String mobileNo; 27 | private String address; 28 | private String order; 29 | // private boolean isValid; 30 | // private Integer status; 31 | // private byte[] headImageData; 32 | 33 | 34 | } 35 | -------------------------------------------------------------------------------- /spring-data-jdbc-demo/src/main/resources/META-INF/spring.factories: -------------------------------------------------------------------------------- 1 | org.springframework.data.jdbc.repository.config.DialectResolver$JdbcDialectProvider=com.vonchange.common.config.MyDialectResolver -------------------------------------------------------------------------------- /spring-data-jdbc-demo/src/main/resources/application-h2.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 9001 3 | 4 | 5 | jdbc: 6 | mybatis: 7 | dialect: com.vonchange.mybatis.dialect.H2MysqlDialect 8 | logRead: true 9 | logWrite: true 10 | logFullSql: true 11 | 12 | spring: 13 | datasource: 14 | hikari: 15 | driver-class-name: org.h2.Driver 16 | #jdbc-url: jdbc:h2:mem:test;DB_CLOSE_DELAY=-1 MYSQL MODE=MYSQL; DATABASE_TO_LOWER=TRUE; 17 | jdbc-url: jdbc:h2:mem:db_users;DATABASE_TO_LOWER=TRUE;MODE=MYSQL;INIT=RUNSCRIPT FROM 'classpath:db-init.sql' 18 | username: root 19 | password: 123456 20 | 21 | -------------------------------------------------------------------------------- /spring-data-jdbc-demo/src/main/resources/application-mysql.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 9002 3 | 4 | jdbc: 5 | mybatis: 6 | isReadAllScopeOpen: false 7 | logRead: true 8 | logWrite: true 9 | logFullSql: true 10 | 11 | spring: 12 | datasource: 13 | hikari: 14 | driver-class-name: com.mysql.cj.jdbc.Driver 15 | #&rewriteBatchedStatements=true&allowMultiQueries=true 1万 3247/245 16 | jdbc-url: jdbc:mysql://127.0.0.1:3306/jdbc_test?autoReconnect=true&rewriteBatchedStatements=true&allowMultiQueries=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=CTT 17 | username: root 18 | password: 123456 19 | # -------------------------------------------------------------------------------- /spring-data-jdbc-demo/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | logging.config= classpath:log4j2.xml 2 | 3 | 4 | -------------------------------------------------------------------------------- /spring-data-jdbc-demo/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | profiles: 3 | active: h2 4 | application: 5 | name: demo 6 | datasource: 7 | hikari: 8 | driver-class-name: com.mysql.cj.jdbc.Driver 9 | jdbc-url: jdbc:mysql://127.0.0.1:3306/jdbc_test?autoReconnect=true&rewriteBatchedStatements=true&allowMultiQueries=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=CTT 10 | username: root 11 | password: 123456 12 | maximum-pool-size: 10 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /spring-data-jdbc-demo/src/main/resources/log4j2.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | %d %-5p [%traceId] %c - {} [%T] %m%n 6 | ./logs/ 7 | 8 | 9 | 10 | 11 | 12 | 13 | 16 | 17 | 18 | 19 | 21 | 22 | 23 | 24 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /spring-data-jdbc-demo/src/main/resources/sql/user.md: -------------------------------------------------------------------------------- 1 | ```sql 2 | -- queryByUserCode 3 | select * from user_info where user_code = #{userCode} 4 | ``` 5 | 6 | ```sql 7 | -- queryByBean 8 | select * from user_info 9 | 10 | [@and user_code = user.userCode] 11 | [@and user_name like user.userName%] 12 | 13 | ``` 14 | 15 | ```sql 16 | -- queryByUserCodes 17 | select * from user_info where 1=1 [@@and user_code in userCodes] 18 | ``` -------------------------------------------------------------------------------- /spring-data-jdbc-demo/src/test/java/com/vonchange/common/AppTest.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.common; 2 | 3 | import com.vonchange.common.dao.UserRepository; 4 | import com.vonchange.common.domain.ReqUser; 5 | import com.vonchange.common.domain.UserDTO; 6 | import com.vonchange.common.domain.UserInfoDO; 7 | import lombok.extern.slf4j.Slf4j; 8 | import org.junit.jupiter.api.Test; 9 | import org.springframework.boot.test.context.SpringBootTest; 10 | import org.springframework.data.domain.Page; 11 | import org.springframework.data.domain.PageRequest; 12 | 13 | import javax.annotation.Resource; 14 | import java.util.Arrays; 15 | import java.util.List; 16 | 17 | /** 18 | * Unit test for simple App. 19 | */ 20 | @Slf4j 21 | @SpringBootTest 22 | //@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) 23 | public class AppTest { 24 | @Resource 25 | private UserRepository userRepository; 26 | @Test 27 | public void queryByUserCode() { 28 | List userInfoDOList= userRepository.queryByUserCode("u001"); 29 | log.info("queryByUserCode:{}",userInfoDOList); 30 | } 31 | @Test 32 | public void queryByUserCodes() { 33 | List userInfoDOList= userRepository.queryByUserCodes(Arrays.asList("u001","u002","u003")); 34 | log.info("queryByUserCodes:{}",userInfoDOList); 35 | } 36 | @Test 37 | public void queryByBean() { 38 | ReqUser userInfoDO=new ReqUser(); 39 | userInfoDO.setUserCode("u001"); 40 | List userInfoDOList= userRepository.queryByBean(userInfoDO); 41 | log.info("queryByBean:{}",userInfoDOList); 42 | } 43 | 44 | @Test 45 | public void findByUserCode() { 46 | Page page= userRepository.findByUserCode("u001", PageRequest.of(0, 1)); 47 | log.info("findByUserCode:{} {}",page,page.getContent()); 48 | } 49 | @Test 50 | public void queryByUserName() { 51 | List userInfoDOList= userRepository.queryByUserName("name:0"); 52 | log.info("queryByUserName:{}",userInfoDOList); 53 | } 54 | @Test 55 | public void findById() { 56 | userRepository.findById(1).ifPresent(item->log.info("findById:{}",item)); 57 | } 58 | @Test 59 | public void updateByUserCode() { 60 | UserDTO userDTO = new UserDTO(); 61 | userDTO.setUserCode("u001"); 62 | userDTO.setUserName("updateByUserCode"); 63 | int num = userRepository.updateByUserCode(userDTO); 64 | log.info("updateByUserCode:{}",num); 65 | List userInfoDOList= userRepository.queryByUserCode("u001"); 66 | log.info("updateByUserCode:{}",userInfoDOList); 67 | } 68 | 69 | @Test 70 | //@Rollback 71 | //@Transactional 72 | public void insert() { 73 | UserInfoDO userInfoDO =userRepository.save(UserInfoDO.builder() 74 | .userCode("u009").userName("insert").order("order").build()); 75 | log.info("insert:{}",userInfoDO); 76 | } 77 | @Test 78 | public void update() { 79 | UserInfoDO userInfoDO =userRepository.save(UserInfoDO.builder().id(1L).userCode("u000001").userName("update").mobileNo("13888888888").build()); 80 | log.info("insert:{}",userInfoDO); 81 | } 82 | 83 | @Test 84 | public void findAll() { 85 | userRepository.findAll().forEach(item->{log.info("item {}",item);}); 86 | } 87 | 88 | } 89 | -------------------------------------------------------------------------------- /spring-data-jdbc-demo/src/test/resources/db-init.sql: -------------------------------------------------------------------------------- 1 | SET MODE=MySQL; 2 | SET FOREIGN_KEY_CHECKS=0; 3 | drop table if exists `user_info`; 4 | CREATE TABLE IF NOT EXISTS `user_info` ( 5 | `id` bigint(13) NOT NULL AUTO_INCREMENT COMMENT 'id', 6 | `user_code` varchar(36) DEFAULT NULL COMMENT 'user code', 7 | `user_name` varchar(30) DEFAULT NULL COMMENT 'user name', 8 | `mobile_no` varchar(13) DEFAULT NULL COMMENT 'mobile nubmer', 9 | `address` varchar(20) DEFAULT NULL COMMENT 'address', 10 | `order` varchar(50) DEFAULT NULL COMMENT 'order', 11 | `version` int(11) DEFAULT '1' Not NULL COMMENT 'version', 12 | `is_delete` tinyint(1) DEFAULT '0' Not NULL COMMENT 'is delete', 13 | `is_valid` tinyint(1) DEFAULT '0' Not NULL COMMENT 'isValid', 14 | `create_time` datetime DEFAULT NULL, 15 | `update_time` datetime DEFAULT NULL, 16 | `head_image_data` blob DEFAULT NULL, 17 | PRIMARY KEY (`id`) 18 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 19 | insert into user_info(user_code,user_name,mobile_no,address,create_time) values ('u000','change','000','tang',now()); 20 | insert into user_info(user_code,user_name,mobile_no,address,create_time) values ('u001','Jack','001','hang zhou',now()); 21 | insert into user_info(user_code,user_name,mobile_no,address,create_time,update_time) values ('u002','Elon Reeve Musk','002','Mars',now(),now()); 22 | insert into user_info(user_code,user_name,mobile_no,address,create_time) values ('u003','Bill Gates','003',null,now()); -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis-demo/src/main/java/com/vonchange/nine/demo/JdbcMybatisTestApplication.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.nine.demo; 2 | 3 | import com.vonchange.jdbc.mybatis.core.config.EnableJdbcRepositories; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | 7 | //@SpringBootApplication(exclude={JdbcConfiguration.class}) 8 | //@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) 9 | //(basePackages ="com.vonchange.nine.demo.dao") 10 | @SpringBootApplication 11 | @EnableJdbcRepositories 12 | public class JdbcMybatisTestApplication { 13 | public static void main(String[] args) { 14 | SpringApplication.run(JdbcMybatisTestApplication.class, args); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis-demo/src/main/java/com/vonchange/nine/demo/config/DBConfig.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.nine.demo.config; 2 | 3 | 4 | import com.vonchange.jdbc.model.DataSourceWrapper; 5 | import org.springframework.beans.factory.annotation.Qualifier; 6 | import org.springframework.boot.context.properties.ConfigurationProperties; 7 | import org.springframework.boot.jdbc.DataSourceBuilder; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | import org.springframework.context.annotation.Primary; 11 | 12 | import javax.sql.DataSource; 13 | 14 | 15 | @Configuration 16 | public class DBConfig { 17 | @Bean(name = "dataSource") 18 | @Primary 19 | @ConfigurationProperties(prefix = "spring.datasource.hikari") 20 | public DataSource mainDataSource() { 21 | return DataSourceBuilder.create().build(); 22 | } 23 | 24 | @Bean(name = "dataSourceRead") 25 | @ConfigurationProperties(prefix = "spring.datasource.hikari") 26 | public DataSource readDataSource() { 27 | return DataSourceBuilder.create().build(); 28 | } 29 | 30 | //@DataSourceKey 31 | @Bean 32 | public DataSourceWrapper readDataSourceWrapper(@Qualifier("dataSourceRead") DataSource dataSource) { 33 | return new DataSourceWrapper(dataSource,"dataSourceRead",null); 34 | } 35 | 36 | 37 | } -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis-demo/src/main/java/com/vonchange/nine/demo/dao/IUserInfoCrudClientDao.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.nine.demo.dao; 2 | 3 | import com.vonchange.nine.demo.domain.UserInfoDO; 4 | 5 | import java.util.List; 6 | 7 | public interface IUserInfoCrudClientDao { 8 | List findList(String userCode); 9 | 10 | } 11 | -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis-demo/src/main/java/com/vonchange/nine/demo/dao/UserInfoCrudClientDao.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.nine.demo.dao; 2 | 3 | 4 | import com.vonchange.jdbc.client.CrudClient; 5 | import com.vonchange.nine.demo.domain.UserInfoDO; 6 | import lombok.AllArgsConstructor; 7 | import org.springframework.stereotype.Repository; 8 | 9 | import java.util.List; 10 | 11 | @Repository 12 | @AllArgsConstructor 13 | public class UserInfoCrudClientDao implements IUserInfoCrudClientDao{ 14 | 15 | private CrudClient crudClient; 16 | 17 | @Override 18 | public List findList(String userCode) { 19 | return crudClient.sqlId("findList").namespace(this) 20 | .param("userCode",userCode) 21 | .query(UserInfoDO.class).list(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis-demo/src/main/java/com/vonchange/nine/demo/dao/UserInfoMethodDao.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.nine.demo.dao; 2 | 3 | import com.vonchange.jdbc.mybatis.core.support.CrudExtendRepository; 4 | import com.vonchange.nine.demo.domain.UserInfoDO; 5 | import org.springframework.data.domain.Page; 6 | import org.springframework.data.domain.Pageable; 7 | 8 | import java.time.LocalDateTime; 9 | import java.util.List; 10 | 11 | public interface UserInfoMethodDao extends CrudExtendRepository { 12 | UserInfoDO findByUserCode(String userCode); 13 | 14 | List findByCreateTimeBetween(List time); 15 | boolean countByUserCodeIn(List userCodes); 16 | List findByUserCodeIn(List userCodes); 17 | Page findPageByUserCodeIn(Pageable pageable,List userCodes); 18 | List findByUserCodeInOrderByCreateTimeDesc(List userCodes); 19 | } 20 | -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis-demo/src/main/java/com/vonchange/nine/demo/dao/UserInfoQueryDao.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.nine.demo.dao; 2 | 3 | import com.vonchange.jdbc.mybatis.core.support.QueryRepository; 4 | import com.vonchange.nine.demo.domain.UserInfoDO; 5 | import org.springframework.data.repository.query.Param; 6 | 7 | import java.util.List; 8 | import java.util.Map; 9 | 10 | 11 | public interface UserInfoQueryDao extends QueryRepository { 12 | 13 | List findList(@Param("userCode") String userCode); 14 | List> findMapList(@Param("userCode") String userCode); 15 | } -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis-demo/src/main/java/com/vonchange/nine/demo/dao/UserInfoRepository.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.nine.demo.dao; 2 | 3 | import com.vonchange.jdbc.mybatis.core.query.BatchUpdate; 4 | import com.vonchange.jdbc.mybatis.core.support.CrudExtendRepository; 5 | import com.vonchange.nine.demo.domain.SearchParam; 6 | import com.vonchange.nine.demo.domain.UserInfoDO; 7 | import org.springframework.data.domain.Page; 8 | import org.springframework.data.domain.Pageable; 9 | import org.springframework.data.repository.query.Param; 10 | 11 | import java.time.LocalDateTime; 12 | import java.util.List; 13 | 14 | public interface UserInfoRepository extends CrudExtendRepository { 15 | 16 | List findByUserCodes(@Param("userCodes") List userCodes); 17 | // 根据用户代码查找用户信息 18 | UserInfoDO findByUserCode(@Param("userCode") String userCode); 19 | 20 | String findUserNameByCode(@Param("userCode") String userCode); 21 | 22 | List findUserList(@Param("userCodes") List userCodes, 23 | @Param("userName")String userName, 24 | @Param("createTime") LocalDateTime createTime); 25 | Page findUserList(Pageable pageable, 26 | @Param("userCodes") List userCodes, 27 | @Param("userName")String userName, 28 | @Param("createTime") LocalDateTime createTime); 29 | 30 | List findUserBySearchParam(@Param("param") SearchParam searchParam); 31 | 32 | 33 | int updateIsDelete(@Param("isDelete") Integer isDelete,@Param("id") Long id); 34 | 35 | @BatchUpdate 36 | int batchUpdate(List list); 37 | 38 | } -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis-demo/src/main/java/com/vonchange/nine/demo/domain/BaseDO.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.nine.demo.domain; 2 | 3 | 4 | import com.vonchange.jdbc.annotation.InsertOnlyProperty; 5 | import lombok.Getter; 6 | import lombok.Setter; 7 | import lombok.ToString; 8 | import org.springframework.data.annotation.Version; 9 | 10 | import javax.persistence.Id; 11 | import java.time.LocalDateTime; 12 | import java.util.Date; 13 | 14 | @Getter 15 | @Setter 16 | @ToString 17 | public class BaseDO { 18 | @Id 19 | private Long id; 20 | @InsertOnlyProperty 21 | private Integer isDelete; 22 | @InsertOnlyProperty 23 | private LocalDateTime createTime; 24 | @Version 25 | private Integer version; 26 | private Date updateTime; 27 | } 28 | -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis-demo/src/main/java/com/vonchange/nine/demo/domain/SearchParam.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.nine.demo.domain; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Builder; 5 | import lombok.Getter; 6 | import lombok.NoArgsConstructor; 7 | import lombok.Setter; 8 | 9 | import java.util.Date; 10 | import java.util.List; 11 | 12 | @Getter 13 | @Setter 14 | @NoArgsConstructor 15 | @AllArgsConstructor 16 | @Builder 17 | public class SearchParam { 18 | private List userCodes; 19 | private String userName; 20 | private Date createTime; 21 | 22 | private String sort; 23 | 24 | } 25 | -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis-demo/src/main/java/com/vonchange/nine/demo/domain/UserInfoDO.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.nine.demo.domain; 2 | 3 | 4 | import lombok.AllArgsConstructor; 5 | import lombok.Builder; 6 | import lombok.Getter; 7 | import lombok.NoArgsConstructor; 8 | import lombok.Setter; 9 | import lombok.ToString; 10 | 11 | import javax.persistence.Column; 12 | import javax.persistence.Id; 13 | import javax.persistence.Table; 14 | 15 | @Getter 16 | @Setter 17 | @Table(name = "user_info") 18 | @Builder 19 | @AllArgsConstructor 20 | @NoArgsConstructor 21 | @ToString 22 | public class UserInfoDO extends BaseDO{ 23 | @Id 24 | private Long id; 25 | private String userCode; 26 | @Column(name="user_name") 27 | private String userName; 28 | private String mobileNo; 29 | private String address; 30 | private boolean isValid; 31 | // private Integer status; 32 | private byte[] headImageData; 33 | 34 | 35 | @Column(name="`order`") 36 | private String order; 37 | 38 | 39 | } 40 | -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis-demo/src/main/java/com/vonchange/nine/demo/util/H2DBFunctionExt.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.nine.demo.util; 2 | 3 | import java.util.UUID; 4 | 5 | public class H2DBFunctionExt { 6 | /** 7 | * 用法:SELECT uuid(); H2数据库注册uuid函数:CREATE ALIAS uuid FOR 8 | * "h2db.function.ext.H2DBFunctionExt.uuid"; 9 | * 10 | * @return 11 | * @Method: uuid 12 | * @Description: 实现MySQL数据库的uuid函数,用于生成UUID 13 | */ 14 | public static String uuid() { 15 | return UUID.randomUUID().toString(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis-demo/src/main/resources/sql/UserInfoCrudClientDao.md: -------------------------------------------------------------------------------- 1 | ``` 2 | -- findList 3 | select * from user_info 4 | where is_delete=0 5 | and user_code = #{userCode} 6 | 7 | ``` -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis-demo/src/main/resources/sql/UserInfoQueryDao.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ``` 4 | -- findList 5 | select * from user_info 6 | where is_delete=0 7 | and user_code = #{userCode} 8 | 9 | ``` 10 | 11 | ``` 12 | -- findMapList 13 | select * from user_info 14 | where is_delete=0 15 | and user_code = #{userCode} 16 | 17 | ``` -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis-demo/src/main/resources/sql/UserInfoRepository.md: -------------------------------------------------------------------------------- 1 | ## query example 2 | 3 | ### base query columns 4 | ``` 5 | -- column 6 | id,user_code,user_name,mobile_no,address,create_time,update_time,is_delete 7 | ``` 8 | 9 | ``` 10 | -- findByUserCodes 11 | select [@id column] from user_info 12 | [@@and user_code in userCodes] 13 | ``` 14 | 15 | 16 | ``` 17 | -- findUserNameByCode 18 | select user_name from user_info where user_code = #{userCode} [@id isDelete] 19 | ``` 20 | 21 | ``` 22 | -- isDelete 23 | and is_delete=0 24 | ``` 25 | 26 | ``` 27 | -- isDeleteOracle 28 | and is_delete=1 29 | ``` 30 | 31 | ``` 32 | -- findUserList 33 | select [@id column] from user_info 34 | where is_delete=0 35 | [@and user_name like userName%] 36 | [@@and user_code in userCodes] 37 | and create_time < #{createTime} 38 | 39 | ``` 40 | 41 | 42 | ``` 43 | -- findUserBySearchParam 44 | select * from user_info 45 | 46 | [@id whereSql] 47 | 48 | ${param.sort} 49 | ``` 50 | 51 | ```sql 52 | -- whereSql 53 | [@@and user_name like param.userName] 54 | [@and user_code in param.userCodes] 55 | [@and create_time <= param.createTime] 56 | ``` 57 | 58 | 59 | 60 | 61 | ``` 62 | -- findList 63 | SELECT [@id column] FROM user_info 64 | 65 | [@@and id in #{idList:in} and user_name like #{userName:like}] 66 | [@and user_name like userName%] 67 | [@and id in idList] 68 | and create_time < #{createTime} 69 | 70 | ``` 71 | 72 | > update 73 | 74 | ``` 75 | -- updateIsDelete 76 | update user_info set is_delete = #{isDelete} where id =#{id} 77 | ``` 78 | 79 | ``` 80 | -- batchUpdate 81 | update user_info set is_delete = IFNULL(#{isDelete},is_delete),user_name =#{userName} where id =#{id} 82 | ``` 83 | 84 | 85 | ``` 86 | -- findBigData 87 | select * from user_info 88 | 89 | [@and user_name like userName] 90 | 91 | ``` 92 | 93 | -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis-demo/src/test/java/com/vonchange/nine/demo/dao/CrudClientTest.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.nine.demo.dao; 2 | 3 | import com.vonchange.common.util.JsonUtil; 4 | import com.vonchange.jdbc.client.CrudClient; 5 | import com.vonchange.jdbc.mapper.AbstractPageWork; 6 | import com.vonchange.nine.demo.domain.UserInfoDO; 7 | import lombok.extern.slf4j.Slf4j; 8 | import org.junit.jupiter.api.Test; 9 | import org.springframework.boot.test.context.SpringBootTest; 10 | 11 | import javax.annotation.Resource; 12 | import java.time.LocalDateTime; 13 | import java.util.ArrayList; 14 | import java.util.List; 15 | import java.util.Map; 16 | 17 | @SpringBootTest 18 | @Slf4j 19 | public class CrudClientTest { 20 | @Resource 21 | private CrudClient crudClient; 22 | @Resource 23 | private UserInfoRepository userInfoRepository; 24 | @Resource 25 | private IUserInfoCrudClientDao iUserInfoCrudClientDao; 26 | 27 | @Test 28 | public void findList() { 29 | for (UserInfoDO userInfoDO : iUserInfoCrudClientDao.findList("u000")) { 30 | log.info("userInfoDO {}", JsonUtil.toJson(userInfoDO)); 31 | } 32 | } 33 | 34 | @Test 35 | public void findListBase() { 36 | for (UserInfoDO userInfoDO : crudClient.sqlId("findList").namespace(this) 37 | .param("userCode", "u000") 38 | .query(UserInfoDO.class).list()) { 39 | log.info("userInfoDO {}", JsonUtil.toJson(userInfoDO)); 40 | } 41 | } 42 | 43 | @Test 44 | public void findListJdbc() { 45 | for (UserInfoDO userInfoDO : crudClient.jdbc().sql("select * from user_info\n" + 46 | "where is_delete=0\n" + 47 | "and user_code = #{userCode}") 48 | .param("userCode", "u000") 49 | .query(UserInfoDO.class).list()) { 50 | log.info("userInfoDO {}", JsonUtil.toJson(userInfoDO)); 51 | } 52 | } 53 | 54 | @Test 55 | public void findBigData() { 56 | long start = System.currentTimeMillis(); 57 | List list = new ArrayList<>(); 58 | for (int i=0;i<10006;i++) { 59 | UserInfoDO userInfoDO = UserInfoDO.builder().userCode("code:"+i).userName("name:"+i) 60 | .build(); 61 | userInfoDO.setCreateTime(LocalDateTime.now()); 62 | list.add(userInfoDO); 63 | } 64 | int resultNum = 0; 65 | userInfoRepository.insertBatch(list,false); 66 | log.info("resultNum {}",resultNum); 67 | log.info("time {}",System.currentTimeMillis()-start);//1554 68 | AbstractPageWork abstractPageWork = new AbstractPageWork() { 69 | @Override 70 | protected void doPage(List pageContentList, int pageNum, Map extData) { 71 | pageContentList.forEach(UserInfoDO -> { 72 | log.info("{}",UserInfoDO.toString()); 73 | }); 74 | 75 | } 76 | 77 | @Override 78 | protected int getPageSize() { 79 | return 500; 80 | } 81 | }; 82 | crudClient.sqlId("findBigData").namespace(this).param("userName","name").queryBatch(UserInfoDO.class,abstractPageWork); 83 | //.findBigData(abstractPageWork,"name"); 84 | log.info("{} {} {}",abstractPageWork.getSize(),abstractPageWork.getTotalPages(),abstractPageWork.getTotalElements()); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis-demo/src/test/java/com/vonchange/nine/demo/dao/UserExample.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.nine.demo.dao; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Builder; 5 | import lombok.Getter; 6 | import lombok.NoArgsConstructor; 7 | import lombok.Setter; 8 | 9 | import java.util.List; 10 | 11 | @Getter 12 | @Setter 13 | @Builder 14 | @AllArgsConstructor 15 | @NoArgsConstructor 16 | public class UserExample { 17 | private String userNameLike; 18 | private List userCodeIn; 19 | 20 | private Boolean createTimeDesc; 21 | } 22 | -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis-demo/src/test/java/com/vonchange/nine/demo/dao/UserInfoQueryDaoTest.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.nine.demo.dao; 2 | 3 | 4 | import com.vonchange.common.util.JsonUtil; 5 | import lombok.extern.slf4j.Slf4j; 6 | import org.junit.jupiter.api.Test; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | 9 | import javax.annotation.Resource; 10 | 11 | @Slf4j 12 | @SpringBootTest 13 | class UserInfoQueryDaoTest { 14 | 15 | @Resource 16 | private UserInfoQueryDao userInfoQueryDao; 17 | @Test 18 | void findList() { 19 | userInfoQueryDao.findList("u001").stream().forEach(item->{ 20 | log.info("item {}", JsonUtil.toJson(item)); 21 | });; 22 | } 23 | @Test 24 | void findMapList() { 25 | userInfoQueryDao.findMapList("u001").stream().forEach(item->{ 26 | log.info("item {}", JsonUtil.toJson(item)); 27 | });; 28 | } 29 | } -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis-demo/src/test/resources/application-h2.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 9001 3 | 4 | 5 | jdbc: 6 | mybatis: 7 | dialect: com.vonchange.mybatis.dialect.H2MySqlDialect 8 | logRead: true 9 | logWrite: true 10 | logFullSql: true 11 | 12 | spring: 13 | datasource: 14 | hikari: 15 | driver-class-name: org.h2.Driver 16 | #jdbc-url: jdbc:h2:mem:test;DB_CLOSE_DELAY=-1 17 | jdbc-url: jdbc:h2:mem:db_users;MODE=MYSQL;INIT=RUNSCRIPT FROM 'classpath:db-init.sql' 18 | username: root 19 | password: 123456 20 | -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis-demo/src/test/resources/application-mysql.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 9002 3 | 4 | jdbc: 5 | mybatis: 6 | isReadAllScopeOpen: false 7 | logRead: true 8 | logWrite: true 9 | logFullSql: true 10 | 11 | spring: 12 | datasource: 13 | hikari: 14 | driver-class-name: com.mysql.cj.jdbc.Driver 15 | #&rewriteBatchedStatements=true&allowMultiQueries=true 1万 3247/245 16 | jdbc-url: jdbc:mysql://127.0.0.1:3306/jdbc_test?autoReconnect=true&rewriteBatchedStatements=true&allowMultiQueries=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=CTT 17 | username: root 18 | password: 123456 19 | # -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis-demo/src/test/resources/application.properties: -------------------------------------------------------------------------------- 1 | logging.config= classpath:log4j2.xml 2 | 3 | 4 | -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis-demo/src/test/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | profiles: 3 | active: h2 4 | application: 5 | name: demo 6 | datasource: 7 | hikari: 8 | driver-class-name: com.mysql.cj.jdbc.Driver 9 | jdbc-url: jdbc:mysql://127.0.0.1:3306/jdbc_test?autoReconnect=true&rewriteBatchedStatements=true&allowMultiQueries=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=CTT 10 | username: root 11 | password: 123456 12 | maximum-pool-size: 10 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis-demo/src/test/resources/db-init.sql: -------------------------------------------------------------------------------- 1 | SET MODE=MySQL; 2 | SET FOREIGN_KEY_CHECKS=0; 3 | drop table if exists `user_info`; 4 | CREATE TABLE IF NOT EXISTS `user_info` ( 5 | `id` bigint(13) NOT NULL AUTO_INCREMENT COMMENT 'id', 6 | `user_code` varchar(36) DEFAULT NULL COMMENT 'user code', 7 | `user_name` varchar(30) DEFAULT NULL COMMENT 'user name', 8 | `mobile_no` varchar(13) DEFAULT NULL COMMENT 'mobile nubmer', 9 | `address` varchar(20) DEFAULT NULL COMMENT 'address', 10 | `order` varchar(50) DEFAULT NULL COMMENT 'order', 11 | `version` int(11) DEFAULT '1' Not NULL COMMENT 'version', 12 | `is_delete` tinyint(1) DEFAULT '0' Not NULL COMMENT 'is delete', 13 | `is_valid` tinyint(1) DEFAULT '0' Not NULL COMMENT 'isValid', 14 | `create_time` datetime DEFAULT NULL, 15 | `update_time` datetime DEFAULT NULL, 16 | `head_image_data` blob DEFAULT NULL, 17 | PRIMARY KEY (`id`) 18 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 19 | insert into user_info(user_code,user_name,mobile_no,address,create_time) values ('u000','change','000','tang',now()); 20 | insert into user_info(user_code,user_name,mobile_no,address,create_time) values ('u001','Jack','001','hang zhou',now()); 21 | insert into user_info(user_code,user_name,mobile_no,address,create_time,update_time) values ('u002','Elon Reeve Musk','002','Mars',now(),now()); 22 | insert into user_info(user_code,user_name,mobile_no,address,create_time) values ('u003','Bill Gates','003',null,now()); -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis-demo/src/test/resources/log4j2.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | %d %-5p [%traceId] %c - {} [%T] %m%n 6 | ./logs/ 7 | 8 | 9 | 10 | 11 | 12 | 13 | 16 | 17 | 18 | 19 | 21 | 22 | 23 | 24 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis-demo/src/test/resources/sql/CrudClientTest.md: -------------------------------------------------------------------------------- 1 | ``` 2 | -- findBigData 3 | select * from user_info 4 | 5 | [@and user_name like userName] 6 | 7 | ``` 8 | 9 | ``` 10 | -- findList 11 | select * from user_info 12 | where is_delete=0 13 | and user_code = #{userCode} 14 | 15 | ``` -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 4.0.0 5 | 6 | spring-data-jdbc-mybatis-parent 7 | com.vonchange.common 8 | 2.5.0 9 | 10 | spring-data-jdbc-mybatis 11 | 2.5.1 12 | 13 | spring-data-jdbc-mybatis 14 | spring data jdbc with mybatis template dynamic query 15 | https://github.com/VonChange/spring-data-jdbc-mybatis 16 | 17 | 2.1.5.RELEASE 18 | 5.1.5.RELEASE 19 | 8.0.15 20 | 2.5.1 21 | 22 | 23 | 24 | com.vonchange.common 25 | jdbc-mybatis 26 | ${jdbc.mybatis} 27 | 28 | 29 | org.springframework.data 30 | spring-data-commons 31 | ${springdata.commons} 32 | provided 33 | 34 | 35 | org.springframework 36 | spring-tx 37 | ${spring.commons} 38 | provided 39 | 40 | 41 | org.springframework 42 | spring-context 43 | ${spring.commons} 44 | provided 45 | 46 | 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis/src/main/java/com/vonchange/jdbc/mybatis/core/config/BindParameterWrapper.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.jdbc.mybatis.core.config; 2 | 3 | import org.springframework.data.domain.Pageable; 4 | 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | public class BindParameterWrapper { 9 | private Pageable pageable; 10 | private Map namedParams; 11 | private List indexedParams; 12 | private Object firstParam; 13 | 14 | public Object getFirstParam() { 15 | return firstParam; 16 | } 17 | 18 | public void setFirstParam(Object firstParam) { 19 | this.firstParam = firstParam; 20 | } 21 | 22 | public Pageable getPageable() { 23 | return pageable; 24 | } 25 | 26 | public void setPageable(Pageable pageable) { 27 | this.pageable = pageable; 28 | } 29 | 30 | public Map getNamedParams() { 31 | return namedParams; 32 | } 33 | 34 | public void setNamedParams(Map namedParams) { 35 | this.namedParams = namedParams; 36 | } 37 | 38 | public List getIndexedParams() { 39 | return indexedParams; 40 | } 41 | 42 | public void setIndexedParams(List indexedParams) { 43 | this.indexedParams = indexedParams; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis/src/main/java/com/vonchange/jdbc/mybatis/core/config/ConfigInfo.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.jdbc.mybatis.core.config; 2 | 3 | import com.vonchange.jdbc.model.DataSourceWrapper; 4 | 5 | public class ConfigInfo { 6 | private String location; 7 | private String method; 8 | private Class domainType; 9 | private String repositoryName; 10 | private DataSourceWrapper dataSourceWrapper; 11 | 12 | 13 | public String getRepositoryName() { 14 | return repositoryName; 15 | } 16 | 17 | public DataSourceWrapper getDataSourceWrapper() { 18 | return dataSourceWrapper; 19 | } 20 | 21 | public void setDataSourceWrapper(DataSourceWrapper dataSourceWrapper) { 22 | this.dataSourceWrapper = dataSourceWrapper; 23 | } 24 | 25 | public void setRepositoryName(String repositoryName) { 26 | this.repositoryName = repositoryName; 27 | } 28 | 29 | public String getLocation() { 30 | return location; 31 | } 32 | 33 | public void setLocation(String location) { 34 | this.location = location; 35 | } 36 | 37 | public String getMethod() { 38 | return method; 39 | } 40 | 41 | public void setMethod(String method) { 42 | this.method = method; 43 | } 44 | 45 | public Class getDomainType() { 46 | return domainType; 47 | } 48 | 49 | public void setDomainType(Class domainType) { 50 | this.domainType = domainType; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis/src/main/java/com/vonchange/jdbc/mybatis/core/config/JdbcConfiguration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.vonchange.jdbc.mybatis.core.config; 17 | 18 | import com.vonchange.common.util.exception.ErrorMsg; 19 | import com.vonchange.jdbc.client.CrudClient; 20 | import com.vonchange.jdbc.config.ConstantJdbc; 21 | import com.vonchange.jdbc.model.DataSourceWrapper; 22 | import com.vonchange.mybatis.dialect.Dialect; 23 | import com.vonchange.mybatis.exception.EnumJdbcErrorCode; 24 | import com.vonchange.mybatis.exception.JdbcMybatisRuntimeException; 25 | import org.springframework.beans.factory.annotation.Autowired; 26 | import org.springframework.beans.factory.annotation.Qualifier; 27 | import org.springframework.beans.factory.annotation.Value; 28 | import org.springframework.context.annotation.Bean; 29 | import org.springframework.context.annotation.Configuration; 30 | 31 | import javax.sql.DataSource; 32 | 33 | /** 34 | * Beans that must be registered for Spring Data JDBC to work. 35 | * 36 | * @author Greg Turnquist 37 | * @author Jens Schauder 38 | * @author Mark Paluch 39 | * @author Michael Simons 40 | * @author Christoph Strobl 41 | */ 42 | @Configuration("jdbcConfiguration") 43 | public class JdbcConfiguration { 44 | 45 | private DataSource dataSource; 46 | 47 | @Value("${jdbc.mybatis.dialect:com.vonchange.mybatis.dialect.MySQLDialect}") 48 | private String dialog; 49 | 50 | @Autowired 51 | public void setDataSource(@Qualifier("dataSource") DataSource dataSource) { 52 | this.dataSource = dataSource; 53 | CrudClient.create(defaultDataSource()); 54 | } 55 | 56 | public CrudClient getCrudClient(String key){ 57 | if(!CrudClient.crudClientMap.containsKey(key)){ 58 | throw new JdbcMybatisRuntimeException(EnumJdbcErrorCode.DataSourceNotFound, 59 | ErrorMsg.builder().message("datasource {} not found",key)); 60 | } 61 | return CrudClient.crudClientMap.get(key); 62 | } 63 | @Bean 64 | public CrudClient defaultCrudClient(){ 65 | return getCrudClient(ConstantJdbc.DataSourceDefault); 66 | } 67 | @Autowired 68 | public void setDataSourceWrappers(@Autowired(required = false)DataSourceWrapper... dataSourceWrapper) { 69 | if(null==dataSourceWrapper){ 70 | return; 71 | } 72 | for (DataSourceWrapper sourceWrapper : dataSourceWrapper) { 73 | CrudClient.create(sourceWrapper); 74 | } 75 | } 76 | private DataSourceWrapper defaultDataSource() { 77 | Dialect defaultDialect; 78 | try { 79 | defaultDialect= (Dialect) Class.forName(dialog).newInstance(); 80 | } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { 81 | throw new RuntimeException(e); 82 | } 83 | return new DataSourceWrapper(dataSource, ConstantJdbc.DataSourceDefault,defaultDialect); 84 | } 85 | 86 | } 87 | -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis/src/main/java/com/vonchange/jdbc/mybatis/core/config/JdbcRepositoriesRegistrar.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.vonchange.jdbc.mybatis.core.config; 17 | 18 | 19 | import org.springframework.data.repository.config.RepositoryBeanDefinitionRegistrarSupport; 20 | import org.springframework.data.repository.config.RepositoryConfigurationExtension; 21 | 22 | import java.lang.annotation.Annotation; 23 | 24 | /** 25 | * enable {@link EnableJdbcRepositories} annotation. 26 | * 27 | * @author Jens Schauder 28 | */ 29 | class JdbcRepositoriesRegistrar extends RepositoryBeanDefinitionRegistrarSupport { 30 | 31 | /* 32 | * (non-Javadoc) 33 | * @see org.springframework.data.repository.config.RepositoryBeanDefinitionRegistrarSupport#getAnnotation() 34 | */ 35 | @Override 36 | protected Class getAnnotation() { 37 | return EnableJdbcRepositories.class; 38 | } 39 | 40 | /* 41 | * (non-Javadoc) 42 | * @see org.springframework.data.repository.config.RepositoryBeanDefinitionRegistrarSupport#getExtension() 43 | */ 44 | @Override 45 | protected RepositoryConfigurationExtension getExtension() { 46 | return new JdbcRepositoryConfigExtension(); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis/src/main/java/com/vonchange/jdbc/mybatis/core/config/JdbcRepositoryConfigExtension.java: -------------------------------------------------------------------------------- 1 | 2 | package com.vonchange.jdbc.mybatis.core.config; 3 | 4 | import com.vonchange.jdbc.mybatis.core.support.JdbcRepositoryFactoryBean; 5 | import org.springframework.data.repository.config.RepositoryConfigurationExtensionSupport; 6 | 7 | import java.util.Locale; 8 | 9 | 10 | 11 | 12 | public class JdbcRepositoryConfigExtension extends RepositoryConfigurationExtensionSupport { 13 | 14 | 15 | 16 | @Override 17 | public String getModuleName() { 18 | return "JDBC"; 19 | } 20 | 21 | public String getRepositoryFactoryClassName() { 22 | return JdbcRepositoryFactoryBean.class.getName(); 23 | } 24 | 25 | public String getRepositoryFactoryBeanClassName() { 26 | return JdbcRepositoryFactoryBean.class.getName(); 27 | } 28 | 29 | @Override 30 | protected String getModulePrefix() { 31 | return getModuleName().toLowerCase(Locale.US); 32 | } 33 | 34 | 35 | } 36 | -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis/src/main/java/com/vonchange/jdbc/mybatis/core/query/BatchUpdate.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.jdbc.mybatis.core.query; 2 | 3 | import java.lang.annotation.*; 4 | 5 | @Retention(RetentionPolicy.RUNTIME) 6 | @Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE }) 7 | @Documented 8 | public @interface BatchUpdate { 9 | } -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis/src/main/java/com/vonchange/jdbc/mybatis/core/query/DataSourceKey.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.jdbc.mybatis.core.query; 2 | 3 | import java.lang.annotation.*; 4 | 5 | @Retention(RetentionPolicy.RUNTIME) 6 | @Target(ElementType.TYPE) 7 | @Documented 8 | @Inherited 9 | public @interface DataSourceKey { 10 | 11 | /** 12 | * 数据源key 13 | */ 14 | String value() default ""; 15 | } -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis/src/main/java/com/vonchange/jdbc/mybatis/core/query/Modifying.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.jdbc.mybatis.core.query; 2 | 3 | import java.lang.annotation.Documented; 4 | import java.lang.annotation.ElementType; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | @Retention(RetentionPolicy.RUNTIME) 10 | @Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE }) 11 | @Documented 12 | public @interface Modifying { 13 | } -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis/src/main/java/com/vonchange/jdbc/mybatis/core/support/CrudExtendRepository.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2008-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.vonchange.jdbc.mybatis.core.support; 17 | 18 | import org.springframework.data.domain.Page; 19 | import org.springframework.data.domain.Pageable; 20 | import org.springframework.data.repository.CrudRepository; 21 | import org.springframework.data.repository.NoRepositoryBean; 22 | 23 | import java.util.List; 24 | import java.util.Optional; 25 | 26 | /** 27 | * Interface for generic CRUD operations on a repository for a specific type. 28 | * 29 | * @author Oliver Gierke 30 | * @author Eberhard Wolff 31 | */ 32 | @NoRepositoryBean 33 | public interface CrudExtendRepository extends CrudRepository { 34 | /** 35 | * insert not null filed 36 | * @param entity 37 | * @return 38 | * @param 39 | */ 40 | 41 | int insert(S entity); 42 | 43 | /** 44 | * update not null field 45 | * @param entity 46 | * @param 47 | */ 48 | int update(S entity); 49 | 50 | int insertBatch(List entities, boolean ifNullInsertByFirstEntity); 51 | int updateBatch(List entities,boolean ifNullUpdateByFirstEntity); 52 | 53 | List findAll(X example); 54 | 55 | Optional findOne(X example); 56 | 57 | Page findAll(X example, Pageable pageable); 58 | 59 | Long count(X example); 60 | 61 | void deleteAllById(Iterable ids); 62 | } 63 | -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis/src/main/java/com/vonchange/jdbc/mybatis/core/support/JdbcQueryLookupStrategy.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.vonchange.jdbc.mybatis.core.support; 17 | 18 | import com.vonchange.jdbc.client.CrudClient; 19 | import com.vonchange.jdbc.config.ConstantJdbc; 20 | import com.vonchange.jdbc.core.CrudUtil; 21 | import com.vonchange.jdbc.mybatis.core.config.ConfigInfo; 22 | import com.vonchange.jdbc.mybatis.core.config.JdbcConfiguration; 23 | import com.vonchange.jdbc.mybatis.core.query.DataSourceKey; 24 | import org.springframework.beans.factory.annotation.Qualifier; 25 | import org.springframework.data.projection.ProjectionFactory; 26 | import org.springframework.data.repository.core.NamedQueries; 27 | import org.springframework.data.repository.core.RepositoryMetadata; 28 | import org.springframework.data.repository.query.QueryLookupStrategy; 29 | import org.springframework.data.repository.query.RepositoryQuery; 30 | 31 | import java.lang.reflect.Method; 32 | 33 | /** 34 | * {@link QueryLookupStrategy} for JDBC repositories. Currently only supports annotated queries. 35 | * 36 | * @author Jens Schauder 37 | * @author Kazuki Shimizu 38 | * @author Oliver Gierke 39 | * @author Mark Paluch 40 | * @author Maciej Walkowiak 41 | */ 42 | class JdbcQueryLookupStrategy implements QueryLookupStrategy { 43 | 44 | private final JdbcConfiguration jdbcConfiguration; 45 | //private final DataSourceWrapperHelper dataSourceWrapperHelper; 46 | 47 | /** 48 | * Creates a new {@link JdbcQueryLookupStrategy} for the given 49 | * 50 | */ 51 | JdbcQueryLookupStrategy(@Qualifier("jdbcConfiguration")JdbcConfiguration jdbcConfiguration) { 52 | this.jdbcConfiguration = jdbcConfiguration; 53 | } 54 | 55 | /* 56 | * (non-Javadoc) 57 | * @see org.springframework.data.repository.query.QueryLookupStrategy#resolveQuery(java.lang.reflect.Method, org.springframework.data.repository.core.RepositoryMetadata, org.springframework.data.projection.ProjectionFactory, org.springframework.data.repository.core.NamedQueries) 58 | */ 59 | @Override 60 | public RepositoryQuery resolveQuery(Method method, RepositoryMetadata repositoryMetadata, 61 | ProjectionFactory projectionFactory, NamedQueries namedQueries) { 62 | String configLoc = CrudUtil.interfaceNameMd(repositoryMetadata.getRepositoryInterface()); 63 | DataSourceKey dataSourceKey= repositoryMetadata.getRepositoryInterface().getAnnotation(DataSourceKey.class); 64 | String dataSourceKeyValue=null!=dataSourceKey?dataSourceKey.value(): ConstantJdbc.DataSourceDefault; 65 | JdbcQueryMethod queryMethod = new JdbcQueryMethod(method, repositoryMetadata, projectionFactory); 66 | ConfigInfo configInfo= new ConfigInfo(); 67 | configInfo.setMethod(method.getName()); 68 | configInfo.setLocation(configLoc); 69 | configInfo.setDomainType(repositoryMetadata.getDomainType()); 70 | CrudClient crudClient= jdbcConfiguration.getCrudClient(dataSourceKeyValue); 71 | return new JdbcRepositoryQuery(queryMethod, crudClient,configInfo); 72 | } 73 | 74 | 75 | } 76 | -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis/src/main/java/com/vonchange/jdbc/mybatis/core/support/JdbcQueryMethod.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.vonchange.jdbc.mybatis.core.support; 17 | 18 | import com.vonchange.jdbc.mybatis.core.query.BatchUpdate; 19 | import com.vonchange.jdbc.mybatis.core.query.Modifying; 20 | import org.springframework.core.annotation.AnnotationUtils; 21 | import org.springframework.data.projection.ProjectionFactory; 22 | import org.springframework.data.repository.core.RepositoryMetadata; 23 | import org.springframework.data.repository.query.QueryMethod; 24 | 25 | import java.lang.reflect.Method; 26 | 27 | /** 28 | * {QueryMethod} implementation that implements a method by executing the query 29 | * from a { Query} annotation on 30 | * that method. Binds method arguments to named parameters in the SQL statement. 31 | * 32 | * @author Jens Schauder 33 | * @author Kazuki Shimizu 34 | */ 35 | public class JdbcQueryMethod extends QueryMethod { 36 | 37 | private final Method method; 38 | 39 | public JdbcQueryMethod(Method method, RepositoryMetadata metadata, ProjectionFactory factory) { 40 | super(method, metadata, factory); 41 | this.method = method; 42 | } 43 | 44 | 45 | public boolean isBatchUpdate() { 46 | return AnnotationUtils.findAnnotation(method, BatchUpdate.class) != null; 47 | } 48 | 49 | 50 | 51 | public boolean isUpdateQuery() { 52 | return AnnotationUtils.findAnnotation(method, Modifying.class) != null; 53 | } 54 | 55 | 56 | 57 | } 58 | -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis/src/main/java/com/vonchange/jdbc/mybatis/core/support/JdbcRepositoryFactoryBean.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.vonchange.jdbc.mybatis.core.support; 17 | 18 | import com.vonchange.jdbc.mybatis.core.config.JdbcConfiguration; 19 | import org.springframework.beans.factory.annotation.Autowired; 20 | import org.springframework.beans.factory.annotation.Qualifier; 21 | import org.springframework.context.ApplicationEventPublisher; 22 | import org.springframework.data.repository.Repository; 23 | import org.springframework.data.repository.core.support.RepositoryFactorySupport; 24 | import org.springframework.data.repository.core.support.TransactionalRepositoryFactoryBeanSupport; 25 | 26 | import java.io.Serializable; 27 | 28 | //import org.springframework.data.jdbc.core.DefaultDataAccessStrategy; 29 | 30 | /** 31 | * Special adapter for Springs 32 | * {@link org.springframework.beans.factory.FactoryBean} interface to allow easy 33 | * setup of 34 | * repository factories via Spring configuration. 35 | * 36 | * @author Jens Schauder 37 | * @author Greg Turnquist 38 | * @author Christoph Strobl 39 | * @author Oliver Gierke 40 | * @author Mark Paluch 41 | */ 42 | public class JdbcRepositoryFactoryBean, S, ID extends Serializable> // 43 | extends TransactionalRepositoryFactoryBeanSupport { 44 | 45 | private JdbcConfiguration jdbcConfiguration; 46 | 47 | /** 48 | * Creates a new {@link JdbcRepositoryFactoryBean} for the given repository 49 | * interface. 50 | * 51 | * @param repositoryInterface must not be {@literal null}. 52 | */ 53 | JdbcRepositoryFactoryBean(Class repositoryInterface) { 54 | super(repositoryInterface); 55 | } 56 | 57 | /* 58 | * (non-Javadoc) 59 | * 60 | * @see 61 | * org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport 62 | * #setApplicationEventPublisher(org.springframework.context. 63 | * ApplicationEventPublisher) 64 | */ 65 | @Override 66 | public void setApplicationEventPublisher(ApplicationEventPublisher publisher) { 67 | 68 | super.setApplicationEventPublisher(publisher); 69 | } 70 | 71 | /** 72 | * Creates the actual {@link RepositoryFactorySupport} instance. 73 | */ 74 | @Override 75 | protected RepositoryFactorySupport doCreateRepositoryFactory() { 76 | return new JdbcRepositoryFactory(jdbcConfiguration); 77 | } 78 | 79 | 80 | 81 | @Autowired 82 | public void setJdbcOperations(@Qualifier("jdbcConfiguration") JdbcConfiguration jdbcConfiguration) { 83 | this.jdbcConfiguration = jdbcConfiguration; 84 | } 85 | 86 | } 87 | -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis/src/main/java/com/vonchange/jdbc/mybatis/core/support/QueryModel.java: -------------------------------------------------------------------------------- 1 | package com.vonchange.jdbc.mybatis.core.support; 2 | 3 | import org.springframework.data.annotation.Id; 4 | 5 | public class QueryModel { 6 | @Id 7 | private Long id; 8 | } 9 | -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis/src/main/java/com/vonchange/jdbc/mybatis/core/support/QueryRepository.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2008-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.vonchange.jdbc.mybatis.core.support; 17 | 18 | import org.springframework.data.repository.NoRepositoryBean; 19 | import org.springframework.data.repository.Repository; 20 | 21 | /** 22 | * only query 23 | */ 24 | @NoRepositoryBean 25 | public interface QueryRepository extends Repository { 26 | 27 | } 28 | -------------------------------------------------------------------------------- /spring-data-jdbc-mybatis/src/main/resources/META-INF/spring.factories: -------------------------------------------------------------------------------- 1 | org.springframework.data.repository.core.support.RepositoryFactorySupport=jdbc.com.vonchange.jdbc.mybatis.core.support.JdbcRepositoryFactory 2 | org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.vonchange.jdbc.mybatis.core.config.JdbcConfiguration --------------------------------------------------------------------------------