├── .bithoundrc ├── .coveralls.yml ├── .gitignore ├── .travis.yml ├── README.md ├── pom.xml └── src ├── main ├── java │ ├── README.md │ └── my │ │ └── sqlite │ │ ├── annotation │ │ ├── SqliteColumn.java │ │ ├── SqliteID.java │ │ ├── SqliteSql.java │ │ ├── SqliteSqlWhereIf.java │ │ ├── SqliteSqlWhereIfs.java │ │ ├── SqliteTable.java │ │ ├── SqliteTableSplit.java │ │ └── SqliteTransient.java │ │ ├── base │ │ ├── SqliteBaseDao.java │ │ ├── SqliteBaseEntity.java │ │ └── SqliteBaseService.java │ │ ├── config │ │ └── SqliteConfig.java │ │ ├── connection │ │ ├── README.md │ │ ├── SqliteBaseConnection.java │ │ ├── SqliteBaseConnectionFactory.java │ │ └── SqliteConnectionPool.java │ │ ├── console │ │ ├── SqliteConsoleBaseDao.java │ │ ├── SqliteConsoleBaseEntity.java │ │ └── SqliteConsoleBaseService.java │ │ ├── constant │ │ └── SqliteConstant.java │ │ ├── exception │ │ ├── SqliteConnectionException.java │ │ └── SqliteConnectionMaxException.java │ │ ├── thread │ │ └── SqliteThreadUtils.java │ │ └── utils │ │ ├── SqliteConnectionUtils.java │ │ ├── SqliteHelper.java │ │ ├── SqliteJsonUtils.java │ │ ├── SqliteLogUtils.java │ │ ├── SqliteSqlHelper.java │ │ └── SqliteUtils.java └── resources │ ├── README.md │ ├── config │ └── sqlite.properties │ └── database │ ├── readme.md │ └── test.db └── test ├── java ├── README.md └── my │ └── test │ └── sqlite │ ├── SqliteBatchTest.java │ ├── SqliteCmdTest.java │ ├── SqliteConnectionPoolTest.java │ ├── SqliteSplitTest.java │ ├── SqliteTableSplitTest.java │ ├── SqliteTest.java │ ├── dao │ ├── TestSqliteSplitDao.java │ ├── TestTableDao.java │ └── TestTableSplitDao.java │ ├── entity │ ├── TestSqliteSplit.java │ ├── TestTable.java │ └── TestTableSplit.java │ └── service │ ├── TestSqliteSplitService.java │ ├── TestTableService.java │ └── TestTableSplitService.java └── resources ├── README.md └── database └── test.db /.bithoundrc: -------------------------------------------------------------------------------- 1 | { 2 | "ignore": [ 3 | "**/deps/**", 4 | "**/node_modules/**", 5 | "**/thirdparty/**", 6 | "**/third_party/**", 7 | "**/vendor/**", 8 | "**/**-min-**", 9 | "**/**-min.**", 10 | "**/**.min.**", 11 | "**/**jquery.?(ui|effects)-*.*.?(*).?(cs|j)s", 12 | "**/**jquery-*.*.?(*).?(cs|j)s", 13 | "**/prototype?(*).js", 14 | "**/mootools*.*.*.js", 15 | "**/dojo.js", 16 | "**/MochiKit.js", 17 | "**/yahoo-*.js", 18 | "**/yui*.js", 19 | "**/ckeditor*.js", 20 | "**/tiny_mce*.js", 21 | "**/tiny_mce/?(langs|plugins|themes|utils)/**", 22 | "**/MathJax/**", 23 | "**/shBrush*.js", 24 | "**/shCore.js", 25 | "**/shLegacy.js", 26 | "**/modernizr.custom.?(*).js", 27 | "**/knockout-*.*.*.debug.js", 28 | "**/extjs/*.js", 29 | "**/extjs/*.xml", 30 | "**/extjs/*.txt", 31 | "**/extjs/*.html", 32 | "**/extjs/*.properties", 33 | "**/extjs/.sencha", 34 | "**/extjs/docs/**", 35 | "**/extjs/builds/**", 36 | "**/extjs/cmd/**", 37 | "**/extjs/examples/**", 38 | "**/extjs/locale/**", 39 | "**/extjs/packages/**", 40 | "**/extjs/plugins/**", 41 | "**/extjs/resources/**", 42 | "**/extjs/src/**", 43 | "**/extjs/welcome/**", 44 | "bower_components/**" 45 | ], 46 | "test": [ 47 | "**/test/**", 48 | "**/tests/**", 49 | "**/spec/**", 50 | "**/specs/**" 51 | ] 52 | } -------------------------------------------------------------------------------- /.coveralls.yml: -------------------------------------------------------------------------------- 1 | service_name: travis-ci 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Built application files and Maven 2 | target/ 3 | 4 | # Compiled class files 5 | *.class 6 | 7 | # Log Files 8 | *.log 9 | 10 | # About IntelliJ 11 | *.iml 12 | /.idea/ 13 | /out/ 14 | 15 | # BlueJ files 16 | *.ctxt 17 | 18 | # Mobile Tools for Java (J2ME) 19 | .mtj.tmp/ 20 | 21 | # macOS 22 | .DS_Store 23 | 24 | # Package Files 25 | *.jar 26 | *.war 27 | *.ear 28 | *.zip 29 | *.tar.gz 30 | *.rar 31 | 32 | # CMake 33 | cmake-build-debug/ 34 | 35 | # File-based project format 36 | *.iws 37 | 38 | # mpeltonen/sbt-idea plugin 39 | .idea_modules/ 40 | 41 | # JIRA plugin 42 | atlassian-ide-plugin.xml 43 | 44 | # Crashlytics plugin (for Android Studio and IntelliJ) 45 | com_crashlytics_export_strings.xml 46 | crashlytics.properties 47 | crashlytics-build.properties 48 | fabric.properties 49 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: 3 | - oraclejdk8 4 | after_success: 5 | - mvn clean cobertura:cobertura coveralls:cobertura 6 | notifications: 7 | slack: my-github:HR5snotT4kXfhchurTHqQOvc 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/petterobam/my-sqlite.svg?branch=master)](https://travis-ci.org/petterobam/my-sqlite) 2 | [![MIT Licence](https://badges.frapsoft.com/os/mit/mit.svg?v=103)](https://opensource.org/licenses/mit-license.php) 3 | [![Analytics](https://ga-beacon.appspot.com/UA-85522412-2/welcome-page)](https://github.com/igrigorik/ga-beacon) 4 | [![stable](http://badges.github.io/stability-badges/dist/stable.svg)](http://github.com/badges/stability-badges) 5 | 6 | # my-sqlite 7 | sqlite 面向对象的数据库封装,自动创建、默认通用操作、自定义SQL和动态SQL,及无xml配置等。扩展实现sqlite表格分库,按日期自动生成库等。 8 | 9 | 新增控制台超类基础实现,应用实例:[https://github.com/petterobam/my-sqlite-console](https://github.com/petterobam/my-sqlite-console) 10 | 11 | # wiki目录 12 | 1. [使用示例](https://github.com/petterobam/my-sqlite/wiki/%E4%BD%BF%E7%94%A8%E7%A4%BA%E4%BE%8B) 13 | 2. [实现思路](https://github.com/petterobam/my-sqlite/wiki/%E5%AE%9E%E7%8E%B0%E6%80%9D%E8%B7%AF) 14 | 15 | # Todo清单 16 | 1. ~~自动建表~~ 17 | 1. ~~增删查改等基本功能~~ 18 | 1. ~~数量查询功能~~ 19 | 1. ~~分表分库~~ 20 | 1. ~~Sqlite控制台基础功能类~~ 21 | 1. ~~自定义配置加载~~ 22 | 1. **~~批量操作(事务)~~** 23 | 1. **缓存库基础功能类实现** 24 | 1. 缓存库和文件库混用实现 25 | 1. **~~连接池实现~~** 26 | 1. 查询分页功能实现 27 | 1. 备份工具实现 28 | 1. 密码连接实现 29 | 1. 密码库生成实现 30 | 31 | PS:更多完善的功能请参照 32 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | my-sqlite 8 | my-sqlite 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 3.15.1 13 | 1.2.31 14 | 4.11 15 | 16 | 3.1 17 | UTF-8 18 | 2.19.1 19 | 20 | 21 | 22 | 23 | 24 | org.xerial 25 | sqlite-jdbc 26 | ${sqlite.version} 27 | 28 | 29 | 30 | 31 | com.alibaba 32 | fastjson 33 | ${fastjson.version} 34 | 35 | 36 | 37 | 38 | junit 39 | junit 40 | ${junit.version} 41 | test 42 | 43 | 44 | 45 | 46 | 47 | my-nexus-snapshots 48 | User Porject Snapshot 49 | http://localhost:8081/nexus/content/repositories/my-nexus-snapshots 50 | false 51 | 52 | 53 | my-nexus-releases 54 | User Porject Release 55 | http://localhost:8081/nexus/content/repositories/my-nexus-releases 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | src/main/java 64 | 65 | **/*.properties 66 | **/*.xml 67 | 68 | 69 | 70 | 71 | src/main/resources 72 | 73 | 74 | **/*.* 75 | 76 | 77 | 78 | 79 | 80 | 81 | org.apache.maven.plugins 82 | maven-surefire-plugin 83 | ${surefire-plugin.version} 84 | 85 | true 86 | 87 | 88 | 89 | 90 | 91 | maven-source-plugin 92 | 93 | true 94 | 95 | 96 | 97 | compile 98 | 99 | jar 100 | 101 | 102 | 103 | 104 | 105 | 106 | org.codehaus.mojo 107 | cobertura-maven-plugin 108 | 2.5.2 109 | 110 | xml 111 | 256m 112 | true 113 | 114 | 115 | 116 | org.eluder.coveralls 117 | coveralls-maven-plugin 118 | 2.2.0 119 | 120 | 121 | 122 | 123 | 124 | -------------------------------------------------------------------------------- /src/main/java/README.md: -------------------------------------------------------------------------------- 1 | # Sqlite-OOP 2 | 3 | 源码负者人:[petterobam](https://github.com/petterobam) 4 | 5 | 相关博客: 6 | 7 | 1. [Sqlite数据库面向对象封装思路](http://www.db2oop.cn/blog/2018/03/25/sqlite-oop-idea) 8 | 2. [Sqlite-OOP子项目使用示例](http://www.db2oop.cn/blog/2018/03/25/sqlite-oop-use-cases) 9 | 10 | 问题建议: 11 | 12 | 1. [待办] - 将 ```@SqliteSql*({...})``` 这种动态Sql生成注解,用代码生成(编译时候)或动态规则转化存储(运行时候),优化动态解析效率 —— by [xiesiwen](https://github.com/xiesiwen) 13 | 2. [待办] - 动态分表功能简化实现 —— by [petterobam](https://github.com/petterobam) -------------------------------------------------------------------------------- /src/main/java/my/sqlite/annotation/SqliteColumn.java: -------------------------------------------------------------------------------- 1 | package my.sqlite.annotation; 2 | 3 | /** 4 | * Sqlite的表字段注解类 5 | * 6 | * @author 欧阳洁 7 | * @create 2017-09-30 11:20 8 | **/ 9 | @java.lang.annotation.Target(value = {java.lang.annotation.ElementType.FIELD}) 10 | @java.lang.annotation.Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME) 11 | public @interface SqliteColumn { 12 | /** 13 | * 列名,默认空 14 | * 15 | * @return 16 | */ 17 | String name() default ""; 18 | 19 | /** 20 | * 主键默认类型,默认最大20位长度的字符串 21 | * 22 | * @return 23 | */ 24 | String type() default "char(20)"; 25 | 26 | /** 27 | * 是否不为空,默认否 28 | * 29 | * @return 30 | */ 31 | boolean notNull() default false; 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/my/sqlite/annotation/SqliteID.java: -------------------------------------------------------------------------------- 1 | package my.sqlite.annotation; 2 | 3 | /** 4 | * Sqlite的ID注解类 5 | * 6 | * @author 欧阳洁 7 | * @create 2017-09-30 11:20 8 | **/ 9 | @java.lang.annotation.Target(value = {java.lang.annotation.ElementType.FIELD}) 10 | @java.lang.annotation.Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME) 11 | public @interface SqliteID { 12 | /** 13 | * 主键列名,默认空 14 | * @return 15 | */ 16 | String name() default ""; 17 | /** 18 | * 主键默认类型,默认integer类型 19 | * @return 20 | */ 21 | String type() default "integer"; 22 | 23 | /** 24 | * 主键是否自增长,默认是true 25 | * @return 26 | */ 27 | boolean autoincrement() default true; 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/my/sqlite/annotation/SqliteSql.java: -------------------------------------------------------------------------------- 1 | package my.sqlite.annotation; 2 | 3 | /** 4 | * 自定义SQL注解类 5 | * 6 | * @author 欧阳洁 7 | */ 8 | @java.lang.annotation.Target(value = {java.lang.annotation.ElementType.METHOD}) 9 | @java.lang.annotation.Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME) 10 | public @interface SqliteSql { 11 | /** 12 | * 自定义的Sql语句,带占位符的Sql 13 | * @return 14 | */ 15 | String sql(); 16 | /** 17 | * 占位符顺序对应的参数顺序,默认不带参数 18 | * @return 19 | */ 20 | String[] params() default ""; 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/my/sqlite/annotation/SqliteSqlWhereIf.java: -------------------------------------------------------------------------------- 1 | package my.sqlite.annotation; 2 | 3 | /** 4 | * 自定义注解辅助,条件判断注解,用于生成动态SQL 5 | * 6 | * @author 欧阳洁 7 | */ 8 | @java.lang.annotation.Target(value = {java.lang.annotation.ElementType.METHOD}) 9 | @java.lang.annotation.Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME) 10 | @java.lang.annotation.Repeatable(SqliteSqlWhereIfs.class) 11 | public @interface SqliteSqlWhereIf { 12 | /** 13 | * 判断条件标识ID 14 | * 15 | * @return 16 | */ 17 | int testId(); 18 | 19 | /** 20 | * 所属层级,默认0,最外层 21 | * 22 | * @return 23 | */ 24 | int parentTestId() default 0; 25 | 26 | /** 27 | * 判断条件类型,==、>、<、>=、<=、eq、ne 28 | * 29 | * @return 30 | */ 31 | String testType() default "eq"; 32 | 33 | /** 34 | * 判断字段名 35 | * 36 | * @return 37 | */ 38 | String testName(); 39 | 40 | /** 41 | * 符合条件的值 42 | * 43 | * @return 44 | */ 45 | String[] testTrueValue(); 46 | 47 | /** 48 | * 符合条件对应的动态SQL 49 | * 50 | * @return 51 | */ 52 | String[] testTrueSql() default ""; 53 | 54 | /** 55 | * 占位符顺序对应的参数顺序,默认不带参数 56 | * 57 | * @return 58 | */ 59 | String[] params() default ""; 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/my/sqlite/annotation/SqliteSqlWhereIfs.java: -------------------------------------------------------------------------------- 1 | package my.sqlite.annotation; 2 | 3 | /** 4 | * 实现SqliteSqlWhereIf的重复注解 5 | * @author 欧阳洁 6 | */ 7 | @java.lang.annotation.Target(value = {java.lang.annotation.ElementType.METHOD}) 8 | @java.lang.annotation.Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME) 9 | public @interface SqliteSqlWhereIfs { 10 | SqliteSqlWhereIf[] value(); 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/my/sqlite/annotation/SqliteTable.java: -------------------------------------------------------------------------------- 1 | package my.sqlite.annotation; 2 | 3 | 4 | /** 5 | * 表名注解类 6 | * 7 | * @author 欧阳洁 8 | * @create 2017-09-30 11:16 9 | **/ 10 | @java.lang.annotation.Target(value = {java.lang.annotation.ElementType.TYPE}) 11 | @java.lang.annotation.Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME) 12 | public @interface SqliteTable { 13 | /** 14 | * 表名 15 | * @return 16 | */ 17 | String name() default ""; 18 | /** 19 | * 数据库文件路径 20 | * @return 21 | */ 22 | String dbPath() default my.sqlite.constant.SqliteConstant.DB_PATH; 23 | /** 24 | * 数据库文件路径类型 25 | * @return 26 | */ 27 | int dbType() default my.sqlite.constant.SqliteConstant.DB_TYPE_DEFAULT; 28 | } -------------------------------------------------------------------------------- /src/main/java/my/sqlite/annotation/SqliteTableSplit.java: -------------------------------------------------------------------------------- 1 | package my.sqlite.annotation; 2 | 3 | /** 4 | * 分表属性注解 5 | * @author 欧阳洁 6 | */ 7 | @java.lang.annotation.Target(value = {java.lang.annotation.ElementType.FIELD}) 8 | @java.lang.annotation.Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME) 9 | public @interface SqliteTableSplit { 10 | /** 11 | * 后缀链接字符 12 | * @return 13 | */ 14 | String joinStr() default "_"; 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/my/sqlite/annotation/SqliteTransient.java: -------------------------------------------------------------------------------- 1 | package my.sqlite.annotation; 2 | 3 | /** 4 | * 非表字段标识注解 5 | * 6 | * @author 欧阳洁 7 | */ 8 | @java.lang.annotation.Target(value = {java.lang.annotation.ElementType.FIELD}) 9 | @java.lang.annotation.Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME) 10 | public @interface SqliteTransient { 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/my/sqlite/base/SqliteBaseDao.java: -------------------------------------------------------------------------------- 1 | package my.sqlite.base; 2 | 3 | import my.sqlite.constant.SqliteConstant; 4 | import my.sqlite.utils.SqliteHelper; 5 | import my.sqlite.utils.SqliteSqlHelper; 6 | import my.sqlite.utils.SqliteUtils; 7 | 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | import java.util.Map; 11 | import java.util.Vector; 12 | 13 | /** 14 | * Sqlite基础dao 15 | * 16 | * @author 欧阳洁 17 | * @create 2017-09-30 10:28 18 | **/ 19 | public abstract class SqliteBaseDao { 20 | private String tableName; 21 | private Class entityClazz; 22 | private SqliteSqlHelper sqlHelper; 23 | private SqliteHelper sqliteHelper; 24 | 25 | public SqliteBaseDao(Class entityClass) { 26 | this.entityClazz = entityClass; 27 | this.sqlHelper = new SqliteSqlHelper(entityClass); 28 | this.tableName = this.sqlHelper.getTableName(); 29 | this.sqliteHelper = new SqliteHelper(entityClass); 30 | //调用该方法就能在使用时检查和创建表,可以通过配置信息判断是否执调用,达到开关控制的效果 31 | this.existOrCreateTable(); 32 | } 33 | 34 | /** 35 | * 检查表是否存在,不存在则创建 36 | */ 37 | public void existOrCreateTable() { 38 | String sql = this.sqlHelper.createTableSql(); 39 | this.sqliteHelper.execute(sql); 40 | } 41 | 42 | /** 43 | * 插入 44 | * 45 | * @param sql 46 | * @return 47 | */ 48 | public int insert(String sql) { 49 | return this.sqliteHelper.insert(sql); 50 | } 51 | 52 | /** 53 | * 插入 54 | * 55 | * @param entity 56 | * @return 57 | */ 58 | public int insert(T entity) { 59 | this.sqlHelper.createInsert(entity); 60 | if (!SqliteUtils.isBlank(entity.getNeedCreateBefSql())) { 61 | //插入数据之前判断是否需要建表 62 | this.sqliteHelper.execute(entity.getNeedCreateBefSql()); 63 | } 64 | return this.sqliteHelper.insert(entity.getCurrentSql(), entity.getCurrentParam()); 65 | } 66 | 67 | /** 68 | * 批量插入 69 | * 70 | * @param sqlList 71 | * @return 72 | */ 73 | public int batchInsertSql(List sqlList) { 74 | return this.sqliteHelper.batchInsertSql(sqlList); 75 | } 76 | 77 | /** 78 | * 批量插入 79 | * 80 | * @param sqlList 81 | * @param batchCount 82 | * @return 83 | */ 84 | public int batchInsertSql(List sqlList, int batchCount) { 85 | return this.sqliteHelper.batchInsertSql(sqlList, batchCount); 86 | } 87 | 88 | /** 89 | * 批量插入 90 | * 91 | * @param list 92 | * @return 93 | */ 94 | public int batchInsert(List list) { 95 | return this.batchInsert(list, SqliteConstant.DEFAULT_BATCH_COUNT); 96 | } 97 | 98 | /** 99 | * 批量插入 100 | * 101 | * @param list 102 | * @param batchCount 103 | * @return 104 | */ 105 | public int batchInsert(List list, int batchCount) { 106 | if (SqliteUtils.isNotEmpty(list)) { 107 | for (T entity : list) { 108 | this.sqlHelper.createInsert(entity); 109 | } 110 | } else { 111 | return 0; 112 | } 113 | return this.sqliteHelper.batchInsert(list, batchCount); 114 | } 115 | 116 | /** 117 | * 修改 118 | * 119 | * @param sql 120 | * @return 121 | */ 122 | public int update(String sql) { 123 | return this.sqliteHelper.update(sql); 124 | } 125 | 126 | /** 127 | * 修改 128 | * 129 | * @param entity 130 | * @return 131 | */ 132 | public int update(T entity) { 133 | this.sqlHelper.createUpdate(entity); 134 | return this.sqliteHelper.update(entity.getCurrentSql(), entity.getCurrentParam()); 135 | } 136 | 137 | /** 138 | * 批量修改 139 | * 140 | * @param sqlList 141 | * @return 142 | */ 143 | public int batchUpdateSql(List sqlList) { 144 | return this.sqliteHelper.batchUpdateSql(sqlList); 145 | } 146 | 147 | /** 148 | * 批量修改 149 | * 150 | * @param sqlList 151 | * @param batchCount 152 | * @return 153 | */ 154 | public int batchUpdateSql(List sqlList, int batchCount) { 155 | return this.sqliteHelper.batchUpdateSql(sqlList, batchCount); 156 | } 157 | 158 | /** 159 | * 批量修改 160 | * 161 | * @param list 162 | * @return 163 | */ 164 | public int batchUpdate(List list) { 165 | return this.batchUpdate(list, SqliteConstant.DEFAULT_BATCH_COUNT); 166 | } 167 | 168 | /** 169 | * 批量修改 170 | * 171 | * @param list 172 | * @param batchCount 173 | * @return 174 | */ 175 | public int batchUpdate(List list, int batchCount) { 176 | if (SqliteUtils.isNotEmpty(list)) { 177 | for (T entity : list) { 178 | this.sqlHelper.createUpdate(entity); 179 | } 180 | } else { 181 | return 0; 182 | } 183 | return this.sqliteHelper.batchUpdate(list, batchCount); 184 | } 185 | 186 | /** 187 | * 删除 188 | * 189 | * @param sql 190 | * @return 191 | */ 192 | public int delete(String sql) { 193 | return this.sqliteHelper.delete(sql); 194 | } 195 | 196 | /** 197 | * 删除 198 | * 199 | * @param entity 200 | * @return 201 | */ 202 | public int delete(T entity) { 203 | this.sqlHelper.createDelete(entity); 204 | return this.sqliteHelper.delete(entity.getCurrentSql(), entity.getCurrentParam()); 205 | } 206 | 207 | /** 208 | * 批量删除 209 | * 210 | * @param sqlList 211 | * @return 212 | */ 213 | public int batchDeleteSql(List sqlList) { 214 | return this.sqliteHelper.batchDeleteSql(sqlList); 215 | } 216 | 217 | /** 218 | * 批量删除 219 | * 220 | * @param sqlList 221 | * @param batchCount 222 | * @return 223 | */ 224 | public int batchDeleteSql(List sqlList, int batchCount) { 225 | return this.sqliteHelper.batchDeleteSql(sqlList, batchCount); 226 | } 227 | 228 | /** 229 | * 批量删除 230 | * 231 | * @param list 232 | * @return 233 | */ 234 | public int batchDelete(List list) { 235 | return this.batchDelete(list, SqliteConstant.DEFAULT_BATCH_COUNT); 236 | } 237 | 238 | /** 239 | * 批量删除 240 | * 241 | * @param list 242 | * @param batchCount 243 | * @return 244 | */ 245 | public int batchDelete(List list, int batchCount) { 246 | if (SqliteUtils.isNotEmpty(list)) { 247 | for (T entity : list) { 248 | this.sqlHelper.createDelete(entity); 249 | } 250 | } else { 251 | return 0; 252 | } 253 | return this.sqliteHelper.batchDelete(list, batchCount); 254 | } 255 | 256 | /** 257 | * 通过ID集合,批量删除 258 | * 259 | * @param list 260 | * @return 261 | */ 262 | public int batchDeleteByIdList(List list) { 263 | return this.batchDeleteByIdList(list, SqliteConstant.DEFAULT_BATCH_COUNT); 264 | } 265 | 266 | /** 267 | * 通过ID集合,批量删除 268 | * 269 | * @param list 270 | * @param batchCount 271 | * @return 272 | */ 273 | public int batchDeleteByIdList(List list, int batchCount) { 274 | String sql = this.sqlHelper.createDeleteById(); 275 | return this.sqliteHelper.batchDeleteByIdList(sql, list, batchCount); 276 | } 277 | 278 | /** 279 | * 删除 280 | * 281 | * @param id 282 | * @return 283 | */ 284 | public int deleteById(Object id) { 285 | return this.deleteById(id, null); 286 | } 287 | 288 | /** 289 | * 删除,分表字段值 290 | * 291 | * @param id 292 | * @return 293 | */ 294 | public int deleteById(Object id, String tableExt) { 295 | String sql = this.sqlHelper.createDeleteById(tableExt); 296 | List param = new ArrayList(1); 297 | param.add(id); 298 | return this.sqliteHelper.delete(sql, param); 299 | } 300 | 301 | /** 302 | * 非查询语句执行,返回List 303 | * 304 | * @param sql 305 | * @return 306 | */ 307 | public List query(String sql) { 308 | String jsonStr = this.sqliteHelper.queryJsonResult(sql, this.getColumMap()); 309 | if (jsonStr == null) return null; 310 | List result = SqliteUtils.getInstance(jsonStr, this.entityClazz); 311 | return result; 312 | } 313 | 314 | /** 315 | * 查询语句执行,返回List 316 | * 317 | * @param entity 318 | * @return 319 | */ 320 | public List query(T entity) { 321 | this.sqlHelper.createSelect(entity); 322 | String jsonStr = this.sqliteHelper.queryJsonResult(entity.getCurrentSql(), entity.getCurrentParam(), this.getColumMap()); 323 | if (jsonStr == null) return null; 324 | List result = SqliteUtils.getInstance(jsonStr, entity.getClass()); 325 | return result; 326 | } 327 | 328 | /** 329 | * 查询语句执行,返回T 330 | * 331 | * @param id 332 | * @return 333 | */ 334 | public T queryById(Object id) { 335 | return this.queryById(id, null); 336 | } 337 | 338 | /** 339 | * 查询语句执行,返回T 340 | * 341 | * @param id 342 | * @param tableExt 分表字段的值 343 | * @return 344 | */ 345 | public T queryById(Object id, String tableExt) { 346 | String sql = this.sqlHelper.createSelectById(id, tableExt); 347 | List param = new ArrayList(1); 348 | param.add(id); 349 | String jsonStr = this.sqliteHelper.queryJsonResult(sql, param, this.getColumMap()); 350 | if (jsonStr == null) return null; 351 | List result = SqliteUtils.getInstance(jsonStr, this.entityClazz); 352 | if (SqliteUtils.isNotEmpty(result)) { 353 | return result.get(0); 354 | } else { 355 | return null; 356 | } 357 | } 358 | 359 | /** 360 | * 查询条数 361 | * 362 | * @param sql 363 | * @return 364 | */ 365 | public int count(String sql) { 366 | return sqliteHelper.queryCountResult(sql); 367 | } 368 | 369 | /** 370 | * 查询条数语句执行,返回List 371 | * 372 | * @param entity 373 | * @return 374 | */ 375 | public int count(T entity) { 376 | this.sqlHelper.createCount(entity); 377 | return this.sqliteHelper.queryCountResult(entity.getCurrentSql(), entity.getCurrentParam()); 378 | } 379 | 380 | 381 | /** 382 | * 通过自定义注解执行查询的语句 383 | * 384 | * @param entity 385 | * @return 386 | */ 387 | public List excuteQuery(T entity) { 388 | //[0]为getStackTrace方法,[1]当前的excuteQuery方法,[2]为调用excuteQuery方法的方法 389 | StackTraceElement parrentMethodInfo = Thread.currentThread().getStackTrace()[2];// [2]该结果不可能为空 390 | this.sqlHelper.convertSelfSql(parrentMethodInfo, entity); 391 | String jsonStr = this.sqliteHelper.queryJsonResult(entity.getCurrentSql(), entity.getCurrentParam(), this.getColumMap()); 392 | if (jsonStr == null) return null; 393 | List result = SqliteUtils.getInstance(jsonStr, entity.getClass()); 394 | if (SqliteUtils.isNotEmpty(result)) { 395 | return result; 396 | } else { 397 | return null; 398 | } 399 | } 400 | 401 | /** 402 | * 通过自定义注解执行查询的语句 403 | * 404 | * @param params 405 | * @return 406 | */ 407 | public List excuteQuery(Object... params) { 408 | //[0]为getStackTrace方法,[1]当前的excuteQuery方法,[2]为调用excuteQuery方法的方法 409 | StackTraceElement parrentMethodInfo = Thread.currentThread().getStackTrace()[2];// [2]该结果不可能为空 410 | String sql = this.sqlHelper.convertSelfSql(parrentMethodInfo, params); 411 | List paramList = new Vector(); 412 | if (null != params && params.length > 0) { 413 | for (Object o : params) { 414 | paramList.add(o); 415 | } 416 | } 417 | String jsonStr = this.sqliteHelper.queryJsonResult(sql, paramList, this.getColumMap()); 418 | if (jsonStr == null) return null; 419 | List result = SqliteUtils.getInstance(jsonStr, this.entityClazz); 420 | if (SqliteUtils.isNotEmpty(result)) { 421 | return result; 422 | } else { 423 | return null; 424 | } 425 | } 426 | 427 | /** 428 | * 通过自定义注解执行非查询的语句 429 | * 430 | * @param params 431 | * @return 432 | */ 433 | public int excute(Object... params) { 434 | //[0]为getStackTrace方法,[1]当前的excute方法,[2]为调用excute方法的方法 435 | StackTraceElement parrentMethodInfo = Thread.currentThread().getStackTrace()[2];// [2]该结果不可能为空 436 | String sql = this.sqlHelper.convertSelfSql(parrentMethodInfo, params); 437 | List paramList = new Vector(); 438 | if (null != params && params.length > 0) { 439 | for (Object o : params) { 440 | paramList.add(o); 441 | } 442 | } 443 | return this.sqliteHelper.execute(sql, paramList); 444 | } 445 | 446 | /** 447 | * 通过自定义注解执行非查询的语句 448 | * 449 | * @param entity 450 | * @return 451 | */ 452 | public int excute(T entity) { 453 | //[0]为getStackTrace方法,[1]当前的excute方法,[2]为调用excute方法的方法 454 | StackTraceElement parrentMethodInfo = Thread.currentThread().getStackTrace()[2];// [2]该结果不可能为空 455 | this.sqlHelper.convertSelfSql(parrentMethodInfo, entity); 456 | return this.sqliteHelper.execute(entity.getCurrentSql(), entity.getCurrentParam()); 457 | } 458 | 459 | public String getTableName() { 460 | return tableName; 461 | } 462 | 463 | public void setTableName(String tableName) { 464 | this.tableName = tableName; 465 | } 466 | 467 | public Class getEntityClazz() { 468 | return entityClazz; 469 | } 470 | 471 | public void setEntityClazz(Class entityClazz) { 472 | this.entityClazz = entityClazz; 473 | } 474 | 475 | public SqliteSqlHelper getSqlHelper() { 476 | return sqlHelper; 477 | } 478 | 479 | public void setSqlHelper(SqliteSqlHelper sqlHelper) { 480 | this.sqlHelper = sqlHelper; 481 | } 482 | 483 | public Map getColumMap() { 484 | return this.sqlHelper.getColumnMap(); 485 | } 486 | } 487 | -------------------------------------------------------------------------------- /src/main/java/my/sqlite/base/SqliteBaseEntity.java: -------------------------------------------------------------------------------- 1 | package my.sqlite.base; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * Sqlite基础Entity 7 | * 8 | * @author 欧阳洁 9 | * @create 2017-09-30 10:41 10 | **/ 11 | public class SqliteBaseEntity { 12 | private String currentSql; 13 | 14 | private List currentParam; 15 | 16 | private String needCreateBefSql; 17 | 18 | public Class getCurrentClass(){ 19 | return this.getClass(); 20 | } 21 | 22 | public String getCurrentSql() { 23 | return currentSql; 24 | } 25 | 26 | public void setCurrentSql(String currentSql) { 27 | this.currentSql = currentSql; 28 | } 29 | 30 | public List getCurrentParam() { 31 | return currentParam; 32 | } 33 | 34 | public void setCurrentParam(List currentParam) { 35 | this.currentParam = currentParam; 36 | } 37 | 38 | public String getNeedCreateBefSql() { 39 | return needCreateBefSql; 40 | } 41 | 42 | public void setNeedCreateBefSql(String needCreateBefSql) { 43 | this.needCreateBefSql = needCreateBefSql; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/my/sqlite/base/SqliteBaseService.java: -------------------------------------------------------------------------------- 1 | package my.sqlite.base; 2 | 3 | import my.sqlite.utils.SqliteUtils; 4 | 5 | import java.util.List; 6 | 7 | /** 8 | * Sqlite的基础service 9 | * 10 | * @author 欧阳洁 11 | * @create 2017-09-30 15:18 12 | **/ 13 | public abstract class SqliteBaseService> { 14 | private D baseDao; 15 | 16 | public SqliteBaseService(Class daoClass) { 17 | this.baseDao = SqliteUtils.getInstance(daoClass); 18 | } 19 | 20 | public D getBaseDao() { 21 | return baseDao; 22 | } 23 | 24 | public void setBaseDao(D baseDao) { 25 | this.baseDao = baseDao; 26 | } 27 | 28 | /** 29 | * 插入 30 | * 31 | * @param sql 32 | * @return 33 | */ 34 | public int insert(String sql) { 35 | return this.baseDao.insert(sql); 36 | } 37 | 38 | /** 39 | * 插入 40 | * 41 | * @param entity 42 | * @return 43 | */ 44 | public int insert(T entity) { 45 | return this.baseDao.insert(entity); 46 | } 47 | 48 | /** 49 | * 批量插入功能 50 | * 51 | * @param list 52 | * @return 53 | */ 54 | public int batchInsert(List list) { 55 | return this.baseDao.batchInsert(list); 56 | } 57 | 58 | /** 59 | * 修改 60 | * 61 | * @param sql 62 | * @return 63 | */ 64 | public int update(String sql) { 65 | return this.baseDao.update(sql); 66 | } 67 | 68 | /** 69 | * 修改 70 | * 71 | * @param entity 72 | * @return 73 | */ 74 | public int update(T entity) { 75 | return this.baseDao.update(entity); 76 | } 77 | 78 | /** 79 | * 批量修改功能 80 | * 81 | * @param list 82 | * @return 83 | */ 84 | public int batchUpdate(List list) { 85 | return this.baseDao.batchUpdate(list); 86 | } 87 | 88 | /** 89 | * 删除 90 | * 91 | * @param sql 92 | * @return 93 | */ 94 | public int delete(String sql) { 95 | return this.baseDao.delete(sql); 96 | } 97 | 98 | /** 99 | * 删除 100 | * 101 | * @param entity 102 | * @return 103 | */ 104 | public int delete(T entity) { 105 | return this.baseDao.delete(entity); 106 | } 107 | 108 | /** 109 | * 批量删除功能 110 | * 111 | * @param list 112 | * @return 113 | */ 114 | public int batchDelete(List list) { 115 | return this.baseDao.batchDelete(list); 116 | } 117 | 118 | /** 119 | * 删除 120 | * 121 | * @param id 122 | * @return 123 | */ 124 | public int deleteById(Object id) { 125 | return this.baseDao.deleteById(id); 126 | } 127 | 128 | /** 129 | * 删除 130 | * 131 | * @param id 132 | * @param tableExt 分表字段值 133 | * @return 134 | */ 135 | public int deleteById(Object id, String tableExt) { 136 | return this.baseDao.deleteById(id, tableExt); 137 | } 138 | 139 | /** 140 | * 根据ID集合,批量删除功能 141 | * 142 | * @return 143 | */ 144 | public int batchDeleteByIdList(List idList) { 145 | return this.baseDao.batchDeleteByIdList(idList); 146 | } 147 | 148 | /** 149 | * 查询语句执行,返回List 150 | * 151 | * @param sql 152 | * @return 153 | */ 154 | public List query(String sql) { 155 | return this.baseDao.query(sql); 156 | } 157 | 158 | /** 159 | * 查询语句执行,返回List 160 | * 161 | * @param entity 162 | * @return 163 | */ 164 | public List query(T entity) { 165 | return this.baseDao.query(entity); 166 | } 167 | 168 | /** 169 | * 查询语句执行,返回List 170 | * 171 | * @param id 172 | * @return 173 | */ 174 | public T queryById(Object id) { 175 | return this.baseDao.queryById(id); 176 | } 177 | 178 | /** 179 | * 查询语句执行,返回List 180 | * 181 | * @param id 182 | * @param tableExt 分表字段的值 183 | * @return 184 | */ 185 | public T queryById(Object id, String tableExt) { 186 | return this.baseDao.queryById(id, tableExt); 187 | } 188 | 189 | 190 | /** 191 | * 查询条数语句执行,返回条数 192 | * 193 | * @param sql 194 | * @return 195 | */ 196 | public int count(String sql) { 197 | return this.baseDao.count(sql); 198 | } 199 | 200 | /** 201 | * 查询条数语句执行,返回条数 202 | * 203 | * @param entity 204 | * @return 205 | */ 206 | public int count(T entity) { 207 | return this.baseDao.count(entity); 208 | } 209 | } 210 | -------------------------------------------------------------------------------- /src/main/java/my/sqlite/config/SqliteConfig.java: -------------------------------------------------------------------------------- 1 | package my.sqlite.config; 2 | 3 | import my.sqlite.utils.SqliteUtils; 4 | import org.sqlite.SQLiteConfig; 5 | 6 | import java.io.IOException; 7 | import java.util.Properties; 8 | 9 | /** 10 | * sqlite的一些静态配置 11 | */ 12 | public class SqliteConfig { 13 | 14 | /** 15 | * sqlite配置文件的配置信息 16 | */ 17 | private static Properties properties = new Properties(); 18 | 19 | private static SQLiteConfig config = null; 20 | 21 | /** 22 | * 启动程序的时候读取properties配置文件信息,并永久缓存 23 | */ 24 | static { 25 | try { 26 | //使用 properties 配置文件,默认在 config/sqlite.properties 目录下面,若该项目被引用,启动项目只需要在相同目录下相同配置文件覆盖即可生效 27 | properties.load(SqliteConfig.class.getClassLoader().getResourceAsStream("config/sqlite.properties")); 28 | //properties.loadFromXML(SqliteConfig.class.getClassLoader().getResourceAsStream("config/sqlite.xml")); 29 | //创建Sqlite API 配置对象 30 | config = new SQLiteConfig(properties); 31 | } catch (IOException e) { 32 | e.printStackTrace(); 33 | } 34 | } 35 | 36 | /** 37 | * 单例模式获取配置对象 38 | * 39 | * @return 40 | */ 41 | public static SQLiteConfig getConfig() { 42 | if (null == config) { 43 | config = new SQLiteConfig(properties); 44 | } 45 | return config; 46 | } 47 | 48 | /** 49 | * 动态加载新配置 50 | * 51 | * @param classPath 52 | */ 53 | public static void loadConfig(String classPath) { 54 | try { 55 | //使用 properties 配置文件,默认在 config/sqlite.properties 目录下面,若该项目被引用,启动项目只需要在相同目录下相同配置文件覆盖即可生效 56 | properties.load(SqliteConfig.class.getClassLoader().getResourceAsStream(classPath)); 57 | //properties.loadFromXML(SqliteConfig.class.getClassLoader().getResourceAsStream("config/sqlite.xml")); 58 | //创建Sqlite API 配置对象 59 | config = new SQLiteConfig(properties); 60 | } catch (IOException e) { 61 | e.printStackTrace(); 62 | properties = new Properties(); 63 | } 64 | } 65 | 66 | /** 67 | * 根据key得到value的值 68 | */ 69 | public static String getValue(String key) { 70 | return properties.getProperty(key); 71 | } 72 | 73 | /** 74 | * 默认要配置的参数:数据库uri 75 | * 76 | * @return 77 | */ 78 | public static String getUri() { 79 | return properties.getProperty("sqlite.uri"); 80 | } 81 | 82 | /** 83 | * 默认要配置的参数:用户名 84 | * 85 | * @return 86 | */ 87 | public static String getUserName() { 88 | return properties.getProperty("sqlite.username"); 89 | } 90 | 91 | /** 92 | * 默认要配置的参数:密码 93 | * 94 | * @return 95 | */ 96 | public static String getPassword() { 97 | return properties.getProperty("sqlite.password"); 98 | } 99 | 100 | /*********************************************连接相关配置******************************************/ 101 | /** 102 | * 获取connection对象的时候是否加载对内置配置的自定义配置 103 | * 104 | * @return 105 | */ 106 | public static boolean isConnectionWithCofig() { 107 | return Boolean.parseBoolean(properties.getProperty("sqlite.config.enable")); 108 | } 109 | 110 | /** 111 | * 数据库路径是否是基于classpath路径 112 | * 113 | * @return 114 | */ 115 | public static boolean isPathBaseClasspath() { 116 | return Boolean.parseBoolean(properties.getProperty("sqlite.path.classpath")); 117 | } 118 | 119 | /***********************************连接池相关配置*********************************************/ 120 | /** 121 | * 是否开启连接池 122 | * @return 123 | */ 124 | public static boolean isConnectionPoolEnable() { 125 | return Boolean.parseBoolean(properties.getProperty("sqlite.connection.pool.enable")); 126 | } 127 | 128 | /** 129 | * 连接池最大连接对象数量 130 | * @return 131 | */ 132 | public static int getPoolConnectionMax() { 133 | return SqliteUtils.parseInt(properties.getProperty("sqlite.connection.max"), 2); 134 | } 135 | 136 | /** 137 | * 连接池最小连接对象数量 138 | * @return 139 | */ 140 | public static int getPoolConnectionMin() { 141 | return SqliteUtils.parseInt(properties.getProperty("sqlite.connection.min"), 1); 142 | } 143 | 144 | /** 145 | * 连接池每次新增连接对象最大数量 146 | * @return 147 | */ 148 | public static int getPoolConnectionStep() { 149 | return SqliteUtils.parseInt(properties.getProperty("sqlite.connection.step"), 1); 150 | } 151 | 152 | /** 153 | * 连接池分配后失效清除时间 154 | * @return 155 | */ 156 | public static int getPoolConnectionTimeout() { 157 | return SqliteUtils.parseInt(properties.getProperty("sqlite.connection.timeout"), 500000); 158 | } 159 | 160 | /** 161 | * 连接池线程轮询时长 162 | * @return 163 | */ 164 | public static int getPoolThreadSleep() { 165 | return SqliteUtils.parseInt(properties.getProperty("sqlite.pool.thread.sleep"), 1000); 166 | } 167 | } 168 | -------------------------------------------------------------------------------- /src/main/java/my/sqlite/connection/README.md: -------------------------------------------------------------------------------- 1 | # Sqlite连接池设计 2 | 1. 建立连接是一个耗时过程。 3 | 2. 如果能另起一个线程,不断监控补充连接,清除无效连接等,免去连接时候的时耗。 4 | 3. 多库连接池维护,需要对库进行连接管理。 5 | -------------------------------------------------------------------------------- /src/main/java/my/sqlite/connection/SqliteBaseConnection.java: -------------------------------------------------------------------------------- 1 | package my.sqlite.connection; 2 | 3 | import my.sqlite.config.SqliteConfig; 4 | import my.sqlite.utils.SqliteLogUtils; 5 | import my.sqlite.utils.SqliteUtils; 6 | 7 | import java.sql.Connection; 8 | import java.sql.DriverManager; 9 | import java.sql.SQLException; 10 | 11 | /** 12 | * Sqlite连接自定义封装类 13 | * 14 | * @author 欧阳洁 15 | * @since 2018-05-02 13:26 16 | */ 17 | public class SqliteBaseConnection { 18 | private String uri;//数据库连接 19 | private long createTime;// 时间戳 20 | private Connection connection;// 链接对象 21 | 22 | public SqliteBaseConnection() { 23 | this.createTime = SqliteUtils.getNowStamp(); 24 | } 25 | 26 | /** 27 | * 构造函数 28 | * @param uri 29 | * @param createTime 30 | * @param connection 31 | */ 32 | public SqliteBaseConnection(String uri,long createTime, Connection connection) { 33 | this.uri = uri; 34 | this.createTime = createTime; 35 | this.connection = connection; 36 | } 37 | 38 | /** 39 | * 重置连接uri,并且同时会刷新连接对象 40 | * @param uri 41 | */ 42 | public boolean resetUri(String uri){ 43 | try { 44 | this.uri = uri; 45 | this.createTime = SqliteUtils.getNowStamp(); 46 | if(SqliteBaseConnectionFactory.USE_SELF_INNER_CONFIG){ 47 | this.connection = DriverManager.getConnection(uri, SqliteConfig.getConfig().toProperties()); 48 | }else { 49 | this.connection = DriverManager.getConnection(uri); 50 | } 51 | return true; 52 | } catch (SQLException e) { 53 | SqliteLogUtils.error("[resetUri]重置连接对象失败!",e); 54 | e.printStackTrace(); 55 | return false; 56 | } 57 | } 58 | 59 | /** 60 | * 刷新连接对象 61 | * @return 62 | */ 63 | public boolean refreshConnection(){ 64 | try { 65 | this.createTime = SqliteUtils.getNowStamp(); 66 | if(SqliteBaseConnectionFactory.USE_SELF_INNER_CONFIG){ 67 | this.connection = DriverManager.getConnection(uri, SqliteConfig.getConfig().toProperties()); 68 | }else { 69 | this.connection = DriverManager.getConnection(uri); 70 | } 71 | return true; 72 | } catch (SQLException e) { 73 | SqliteLogUtils.error("[refreshConnection]重新建立连接对象失败!",e); 74 | e.printStackTrace(); 75 | return false; 76 | } 77 | } 78 | 79 | public String getUri() { 80 | return uri; 81 | } 82 | 83 | public void setUri(String uri) { 84 | this.uri = uri; 85 | } 86 | 87 | public long getCreateTime() { 88 | return createTime; 89 | } 90 | 91 | public void setCreateTime(long createTime) { 92 | this.createTime = createTime; 93 | } 94 | 95 | /** 96 | * 获取连接 97 | * @return 98 | */ 99 | public Connection getConnection() { 100 | if(null == this.connection){ 101 | try { 102 | if(SqliteBaseConnectionFactory.USE_SELF_INNER_CONFIG){ 103 | this.connection = DriverManager.getConnection(uri, SqliteConfig.getConfig().toProperties()); 104 | }else { 105 | this.connection = DriverManager.getConnection(uri); 106 | } 107 | } catch (SQLException e) { 108 | SqliteLogUtils.error("连接建立失败!",e); 109 | e.printStackTrace(); 110 | } 111 | } 112 | return connection; 113 | } 114 | 115 | public void setConnection(Connection connection) { 116 | this.connection = connection; 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/main/java/my/sqlite/connection/SqliteBaseConnectionFactory.java: -------------------------------------------------------------------------------- 1 | package my.sqlite.connection; 2 | 3 | import my.sqlite.config.SqliteConfig; 4 | import my.sqlite.utils.SqliteLogUtils; 5 | import my.sqlite.utils.SqliteUtils; 6 | 7 | import java.sql.Connection; 8 | import java.sql.DriverManager; 9 | import java.sql.SQLException; 10 | import java.util.HashSet; 11 | import java.util.Vector; 12 | 13 | /** 14 | * Sqlite连接工厂 15 | * 16 | * @author 欧阳洁 17 | * @since 2018-05-02 13:30 18 | */ 19 | public class SqliteBaseConnectionFactory { 20 | private static String DEFAULT_DB_PATH = SqliteConfig.getUri();//默认库 21 | private static int CON_MAX = SqliteConfig.getPoolConnectionMax();// 最大池链接 22 | private static int CON_MIN = SqliteConfig.getPoolConnectionMin();// 初始池链接 23 | private static int CON_STEP = SqliteConfig.getPoolConnectionStep();// 每次最大补充线程数量 24 | protected static boolean REFRESH_CON_POOL = false; 25 | protected static boolean USE_CONNECT_POOL = SqliteConfig.isConnectionPoolEnable(); 26 | protected static long CON_TIMEOUT = SqliteConfig.getPoolConnectionTimeout();// 超时线程回收 27 | protected static boolean USE_SELF_INNER_CONFIG = SqliteConfig.isConnectionWithCofig(); 28 | protected static Vector idleConList = new Vector();// 闲置连接 29 | protected static Vector runConList = new Vector();// 已分配的连接 30 | 31 | static { 32 | init(); 33 | // 是否启用线程池 34 | if(USE_CONNECT_POOL){ 35 | SqliteConnectionPool.initConnectPoolThreads(); 36 | } 37 | } 38 | 39 | /** 40 | * 初始化连接池 41 | * 42 | * @throws SQLException 43 | */ 44 | private static void init() { 45 | try { 46 | if(SqliteConfig.isPathBaseClasspath()){ 47 | DEFAULT_DB_PATH = SqliteUtils.getClassRootPath(DEFAULT_DB_PATH); 48 | } 49 | loadSqliteJdbcClass();//加载 org.sqlite.JDBC 50 | addConnection(DEFAULT_DB_PATH, CON_MIN);//默认预先建立一些连接到链接对象 51 | } catch (Exception e) { 52 | idleConList.clear(); 53 | SqliteLogUtils.error("ERROR:[池初始化失败][池容器已清空]"); 54 | e.printStackTrace(); 55 | } 56 | } 57 | 58 | /** 59 | * 加载 org.sqlite.JDBC 60 | * 61 | * @return 返回结果 62 | * @author 欧阳洁 63 | * @date 2018/5/2 64 | * @description 65 | */ 66 | private static void loadSqliteJdbcClass() throws ClassNotFoundException { 67 | Class.forName("org.sqlite.JDBC"); 68 | } 69 | 70 | /** 71 | * 获取链接 72 | * 73 | * @return 74 | * @throws Exception 75 | * @throws SQLException 76 | */ 77 | public static Connection getConnection() throws SQLException { 78 | // 先进先出原则 79 | SqliteBaseConnection currCon = null; 80 | synchronized (idleConList) { 81 | // 当可用连接池不为空时候 82 | if (SqliteUtils.isNotEmpty(idleConList)) { 83 | currCon = idleConList.get(0); 84 | idleConList.remove(0); 85 | addRunningConnection(currCon); 86 | } 87 | if (currCon == null || currCon.getConnection() == null || currCon.getConnection().isClosed()) { 88 | currCon = createBaseConnection(); 89 | addRunningConnection(currCon); 90 | } 91 | } 92 | return currCon.getConnection(); 93 | } 94 | /** 95 | * 获取链接 96 | * 97 | * @return 98 | * @throws Exception 99 | * @throws SQLException 100 | */ 101 | public static Connection getConnection(String dbPath) throws SQLException { 102 | if(DEFAULT_DB_PATH.equals(dbPath)){ 103 | return getConnection(); 104 | }else { 105 | SqliteBaseConnection currCon = createBaseConnection(dbPath); 106 | addRunningConnection(currCon); 107 | return currCon.getConnection(); 108 | } 109 | } 110 | 111 | /** 112 | * 添加已分配的连接到已分配队列 113 | * 114 | * @param running 115 | * @return 116 | */ 117 | private static boolean addRunningConnection(SqliteBaseConnection running) { 118 | if (runConList.size() < CON_MAX) { 119 | runConList.add(running); 120 | return true; 121 | } 122 | SqliteLogUtils.warn("当前连接数量大于自定义的最大连接数量!"); 123 | return false; 124 | } 125 | 126 | /** 127 | * 检查容器是否满足使用需求 128 | * @return 129 | */ 130 | protected static boolean checkConnectionBox(String dbPath){ 131 | // 如果连接池里闲置的连接没有 132 | int addNum = 0; 133 | if (idleConList.size() == 0) { 134 | // 超过最大线程数 135 | addNum = CON_MAX - runConList.size(); 136 | if (addNum <= 0) { 137 | SqliteLogUtils.warn("当前使用的连接数量大于自定义的最大连接[{}]限制!", CON_MAX); 138 | return false; 139 | } 140 | } else if (idleConList.size() < CON_MIN) { 141 | addNum = CON_MAX - idleConList.size() - runConList.size(); 142 | if (addNum <= 0) { 143 | SqliteLogUtils.warn("连接池中当前使用的连接数量太多,闲置连接数量小于自定义的最小[{}]闲置连接!", CON_MIN); 144 | return false; 145 | } 146 | } 147 | // 剩余可增加连接对象数,默认每次最多增加 CON_STEP 个 148 | addNum = addNum > CON_STEP ? CON_STEP : addNum; 149 | if (SqliteUtils.isBlank(dbPath)) { 150 | addConnection(DEFAULT_DB_PATH, addNum); 151 | } else { 152 | addConnection(dbPath, addNum); 153 | } 154 | return true; 155 | } 156 | 157 | /** 158 | * 检查闲置连接 159 | * @return 检查到并重置的无效闲置连接数量 160 | * @author 欧阳洁 161 | */ 162 | protected synchronized static int checkAllIdleConnection() { 163 | int idleRefreshCount = 0; 164 | SqliteLogUtils.info("INFO:[可用链接数:{}],[已用连接数:{}]",idleConList.size(),runConList.size()); 165 | try { 166 | if (REFRESH_CON_POOL) {//是否刷新闲置连接池里面的连接 167 | for (SqliteBaseConnection con : idleConList) { 168 | if (null == con.getConnection() || con.getConnection().isClosed()) { 169 | con.refreshConnection(); 170 | idleRefreshCount++; 171 | } 172 | } 173 | REFRESH_CON_POOL = false; 174 | } 175 | } catch (Exception e) { 176 | SqliteLogUtils.error("ERROR:[新日期检查更新失败][池容器已清空]"); 177 | e.printStackTrace(); 178 | } 179 | SqliteLogUtils.info("检测到闲置连接池中无效连接并重置的数量:{}",idleRefreshCount); 180 | return idleRefreshCount; 181 | } 182 | 183 | /** 184 | * 检查已分配的连接 185 | * @return 清除已分配使用中的无效连接数量 186 | * @author 欧阳洁 187 | */ 188 | protected synchronized static int checkAllRunningConnection() { 189 | int runningRemoveCount = 0; 190 | SqliteLogUtils.info("INFO:[可用链接数:{}],[已用连接数:{}]",idleConList.size(),runConList.size()); 191 | SqliteBaseConnection con = null; 192 | for (int i = 0; i < runConList.size(); i++) { 193 | con = runConList.get(i); 194 | try { 195 | if(null == con || null == con.getConnection() || con.getConnection().isClosed() || SqliteUtils.getNowStamp() - con.getCreateTime() > CON_TIMEOUT){ 196 | runConList.remove(i--); 197 | runningRemoveCount++; 198 | } 199 | } catch (SQLException e) { 200 | SqliteLogUtils.error("检查已分配的连接出现异常!",e); 201 | e.printStackTrace(); 202 | } 203 | } 204 | SqliteLogUtils.info("定时清除已分配的废弃或超时连接,清除数量:{}",runningRemoveCount); 205 | return runningRemoveCount; 206 | } 207 | 208 | /** 209 | * 创建connection 210 | * 211 | * @return 212 | */ 213 | public static SqliteBaseConnection createBaseConnection() throws SQLException { 214 | return createBaseConnection(DEFAULT_DB_PATH); 215 | } 216 | 217 | /** 218 | * 创建connection 219 | * 220 | * @param dbPath 221 | * @return 222 | */ 223 | public static SqliteBaseConnection createBaseConnection(String dbPath) throws SQLException { 224 | if (SqliteUtils.isBlank(dbPath)) { 225 | return null; 226 | } 227 | // 获取连接字符串 228 | String JDBC = getJDBCStr(dbPath); 229 | try { 230 | SqliteBaseConnection result = new SqliteBaseConnection(); 231 | if (!result.resetUri(JDBC)) { 232 | result.setCreateTime(SqliteUtils.getNowStamp()); 233 | result.setConnection(DriverManager.getConnection(JDBC)); 234 | } 235 | return result; 236 | } catch (SQLException e) { 237 | SqliteLogUtils.error("ERROR:[Connection对象创建异常]"); 238 | e.printStackTrace(); 239 | throw e; 240 | } 241 | } 242 | 243 | /** 244 | * 获取固定格式的数据库路径信息 245 | * 246 | * @param dbPath 247 | * @return 248 | */ 249 | private static String getJDBCStr(String dbPath) { 250 | if(null != dbPath && !dbPath.startsWith("jdbc:sqlite")) { 251 | String JDBC = "jdbc:sqlite:/" + dbPath; 252 | if (SqliteUtils.isWindows()) { 253 | dbPath = dbPath.toLowerCase(); 254 | JDBC = "jdbc:sqlite:/" + dbPath; 255 | } 256 | return JDBC; 257 | }else { 258 | return dbPath; 259 | } 260 | } 261 | 262 | /** 263 | * 添加新的链接到容器 264 | * 265 | * @param dbPath 数据库的路径 266 | * @param num 添加的数量 267 | * @throws SQLException 268 | */ 269 | private static void addConnection(String dbPath, int num) { 270 | for (int i = 0; i < num; i++) { 271 | // 添加前检查连接池里面所有连接对象 272 | // checkAllIdleConnection(); 273 | // 创建新的连接对象 274 | SqliteBaseConnection newSqliteConnection = null; 275 | try { 276 | newSqliteConnection = createBaseConnection(dbPath); 277 | } catch (SQLException e) { 278 | SqliteLogUtils.error("[addConnection]添加新连接异常!",e); 279 | e.printStackTrace(); 280 | } 281 | idleConList.add(newSqliteConnection); 282 | } 283 | } 284 | } 285 | -------------------------------------------------------------------------------- /src/main/java/my/sqlite/connection/SqliteConnectionPool.java: -------------------------------------------------------------------------------- 1 | package my.sqlite.connection; 2 | 3 | import my.sqlite.config.SqliteConfig; 4 | import my.sqlite.thread.SqliteThreadUtils; 5 | import my.sqlite.utils.SqliteLogUtils; 6 | 7 | import java.util.concurrent.ExecutorService; 8 | import java.util.concurrent.LinkedBlockingQueue; 9 | import java.util.concurrent.ThreadPoolExecutor; 10 | import java.util.concurrent.TimeUnit; 11 | 12 | /** 13 | * 池回收线程 14 | * 15 | * @author 欧阳洁 16 | * @since 2018-05-02 13:41 17 | */ 18 | public class SqliteConnectionPool extends SqliteBaseConnectionFactory { 19 | private static int SLEEP = SqliteConfig.getPoolThreadSleep();// 线程每次SLEEP时长 20 | private static boolean CHECK_RUN_ACTIVE = false;// 检查 ClearRunConnectionThread 线程是否在 21 | private static boolean CHECK_IDLE_ACTIVE = false;// 检查 RefreshIdleConnectionThread 线程是否在 22 | private static boolean CHECK_MONITOR_ACTIVE = false;// 检查 MonitorConnectionPoolThread 线程是否在 23 | private static int COUNT_RUN_ACTIVE = 0;// 检查 ClearRunConnectionThread 线程活跃数量 24 | private static int COUNT_IDLE_ACTIVE = 0;// 检查 RefreshIdleConnectionThread 线程活跃数量 25 | private static int COUNT_MONITOR_ACTIVE = 0;// 检查 MonitorConnectionPoolThread 线程活跃数量 26 | 27 | /** 28 | * LINK 线程池 29 | */ 30 | private static final ExecutorService CONNECTION_POOL_EXETHREAD = new ThreadPoolExecutor(3, 10, 31 | 0L, TimeUnit.MILLISECONDS, 32 | new LinkedBlockingQueue(2000), 33 | SqliteThreadUtils.buildJobFactory("Sqlite 连接池 监控系统 线程池"), new ThreadPoolExecutor.AbortPolicy()); 34 | 35 | /** 36 | * 获取用于Sqlite连接池监控用的线程池服务 37 | * 38 | * @return 39 | */ 40 | public static ExecutorService getExethread() { 41 | return CONNECTION_POOL_EXETHREAD; 42 | } 43 | 44 | /** 45 | * 开启连接池的线程检查,一次性 46 | */ 47 | public static void checkTreadActiveStatus() { 48 | SqliteConnectionPool.CHECK_RUN_ACTIVE = true; 49 | SqliteConnectionPool.CHECK_IDLE_ACTIVE = true; 50 | SqliteConnectionPool.CHECK_MONITOR_ACTIVE = true; 51 | } 52 | 53 | /** 54 | * 开启或关闭连接池线程 55 | */ 56 | public static void switchPool(boolean on_off) { 57 | SqliteConnectionPool.USE_CONNECT_POOL = on_off; 58 | if (!on_off) { 59 | idleConList.clear(); 60 | runConList.clear(); 61 | } 62 | } 63 | 64 | /** 65 | * 初始化连接池线程 66 | */ 67 | public static void initConnectPoolThreads() { 68 | SqliteConnectionPool.USE_CONNECT_POOL = true; 69 | // 添加 池监控并适时生产新连接对象的 线程 70 | SqliteConnectionPool.addMonitorConnectionPoolThread(); 71 | // 添加 池回收无效或久置超时的连接对象的 线程 72 | SqliteConnectionPool.addClearRunConnectionThread(); 73 | // 添加 池检查刷新闲置连接对象的 线程 74 | SqliteConnectionPool.addRefreshIdleConnectionThread(); 75 | } 76 | 77 | /** 78 | * 监控连接池中已分配的连接对象,定时收取没用的连接对象 79 | */ 80 | public static void addClearRunConnectionThread() { 81 | CONNECTION_POOL_EXETHREAD.execute(new Runnable() { 82 | public void run() { 83 | COUNT_RUN_ACTIVE++; 84 | while (true) { 85 | try { 86 | if (SqliteConnectionPool.CHECK_RUN_ACTIVE) { 87 | SqliteLogUtils.info("池回收无效或久置超时的连接对象的 线程运行中...当前该类线程数量:{}", COUNT_RUN_ACTIVE); 88 | SqliteConnectionPool.CHECK_RUN_ACTIVE = false; 89 | } 90 | if (!SqliteConnectionPool.USE_CONNECT_POOL) { 91 | SqliteLogUtils.info("池回收无效或久置超时的连接对象的 线程结束...当前该类线程数量:{}", COUNT_RUN_ACTIVE - 1); 92 | break;// 如果配置不使用连接池,结束线程 93 | } 94 | SqliteThreadUtils.sleep(SLEEP); 95 | checkAllRunningConnection(); 96 | } catch (InterruptedException e) { 97 | idleConList.clear(); 98 | runConList.clear(); 99 | addClearRunConnectionThread(); 100 | SqliteLogUtils.error("ERROR:[池回收无效或久置超时的连接对象的 线程死掉,重新添加新线程!]", e); 101 | e.printStackTrace(); 102 | break; 103 | } 104 | } 105 | COUNT_RUN_ACTIVE--; 106 | } 107 | }); 108 | } 109 | 110 | /** 111 | * 监控连接池中闲置的连接对象,定时收取没用的连接对象 112 | */ 113 | public static void addRefreshIdleConnectionThread() { 114 | CONNECTION_POOL_EXETHREAD.execute(new Runnable() { 115 | public void run() { 116 | COUNT_IDLE_ACTIVE++; 117 | while (true) { 118 | try { 119 | if (SqliteConnectionPool.CHECK_MONITOR_ACTIVE) { 120 | SqliteLogUtils.info("池检查刷新闲置连接对象的 线程运行中...当前该类线程数量:{}", COUNT_IDLE_ACTIVE); 121 | SqliteConnectionPool.CHECK_MONITOR_ACTIVE = false; 122 | } 123 | if (!SqliteConnectionPool.USE_CONNECT_POOL) { 124 | SqliteLogUtils.info("池检查刷新闲置连接对象的 线程结束...当前该类线程数量:{}", COUNT_IDLE_ACTIVE - 1); 125 | break;// 如果配置不使用连接池,结束线程 126 | } 127 | SqliteThreadUtils.sleep(SLEEP); 128 | REFRESH_CON_POOL = true; 129 | checkAllIdleConnection(); 130 | } catch (InterruptedException e) { 131 | idleConList.clear(); 132 | runConList.clear(); 133 | addRefreshIdleConnectionThread(); 134 | SqliteLogUtils.error("ERROR:[池检查刷新闲置连接对象的 线程死掉,重新添加新线程!]", e); 135 | e.printStackTrace(); 136 | break; 137 | } 138 | } 139 | COUNT_IDLE_ACTIVE--; 140 | } 141 | }); 142 | } 143 | 144 | /** 145 | * 监控连接池中闲置的连接对象,定时收取没用的连接对象 146 | */ 147 | public static void addMonitorConnectionPoolThread() { 148 | CONNECTION_POOL_EXETHREAD.execute(new Runnable() { 149 | public void run() { 150 | COUNT_MONITOR_ACTIVE++; 151 | while (true) { 152 | try { 153 | if (SqliteConnectionPool.CHECK_IDLE_ACTIVE) { 154 | SqliteLogUtils.info("池监控并适时生产新连接对象的 线程运行中...当前该类线程数量:{}", COUNT_MONITOR_ACTIVE); 155 | SqliteConnectionPool.CHECK_IDLE_ACTIVE = false; 156 | } 157 | if (!SqliteConnectionPool.USE_CONNECT_POOL) { 158 | SqliteLogUtils.info("池监控并适时生产新连接对象的 线程结束...当前该类线程数量:{}", COUNT_MONITOR_ACTIVE - 1); 159 | break;// 如果配置不使用连接池,结束线程 160 | } 161 | SqliteThreadUtils.sleep(SLEEP); 162 | checkConnectionBox(null); 163 | } catch (InterruptedException e) { 164 | idleConList.clear(); 165 | runConList.clear(); 166 | addMonitorConnectionPoolThread(); 167 | SqliteLogUtils.error("ERROR:[池监控并适时生产新连接对象的 线程死掉,重新添加新线程!]", e); 168 | e.printStackTrace(); 169 | break; 170 | } 171 | } 172 | COUNT_MONITOR_ACTIVE--; 173 | } 174 | }); 175 | } 176 | } 177 | -------------------------------------------------------------------------------- /src/main/java/my/sqlite/console/SqliteConsoleBaseDao.java: -------------------------------------------------------------------------------- 1 | package my.sqlite.console; 2 | 3 | import my.sqlite.utils.SqliteHelper; 4 | import my.sqlite.utils.SqliteUtils; 5 | 6 | /** 7 | * 控制台返回的基本Dao 8 | * 9 | * @author 欧阳洁 10 | */ 11 | public class SqliteConsoleBaseDao { 12 | /** 13 | * 执行控制台语句 14 | * 15 | * @param sqlOrCmd 16 | * @return 17 | */ 18 | public SqliteConsoleBaseEntity excute(String sqlOrCmd) { 19 | if (SqliteUtils.isBlank(sqlOrCmd)) { 20 | return null; 21 | } 22 | String sqlLower = sqlOrCmd.toLowerCase().trim(); 23 | if(sqlLower.startsWith(".")){ 24 | return this.sqliteHelper.cmdExecForConsole(sqlOrCmd); 25 | }else if (sqlLower.startsWith("insert ") || sqlLower.startsWith("delete ") 26 | || sqlLower.startsWith("update ") || sqlLower.startsWith("create ") 27 | || sqlLower.startsWith("alter ") || sqlLower.startsWith("drop ")) { 28 | return this.sqliteHelper.executeForConsole(sqlOrCmd); 29 | } else { 30 | return this.sqliteHelper.queryForConsole(sqlOrCmd); 31 | } 32 | } 33 | 34 | /** 35 | * 获取数据库表名集合 36 | * @return 37 | */ 38 | public String[] getTableNameArr(){ 39 | return this.sqliteHelper.getTableNameArr(); 40 | } 41 | 42 | 43 | private SqliteHelper sqliteHelper; 44 | 45 | public SqliteConsoleBaseDao(String dbPath, boolean absolute) { 46 | this.sqliteHelper = new SqliteHelper(dbPath, absolute); 47 | } 48 | 49 | public SqliteConsoleBaseDao(String dbPath) { 50 | this.sqliteHelper = new SqliteHelper(dbPath); 51 | } 52 | 53 | public SqliteHelper getSqliteHelper() { 54 | return sqliteHelper; 55 | } 56 | 57 | public void setSqliteHelper(SqliteHelper sqliteHelper) { 58 | this.sqliteHelper = sqliteHelper; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/my/sqlite/console/SqliteConsoleBaseEntity.java: -------------------------------------------------------------------------------- 1 | package my.sqlite.console; 2 | 3 | import java.sql.SQLException; 4 | import java.util.List; 5 | import java.util.Map; 6 | 7 | /** 8 | * 控制台返回的基本实体 9 | * @author 欧阳洁 10 | */ 11 | public class SqliteConsoleBaseEntity { 12 | /** 13 | * 查询结果集 14 | */ 15 | private List> queryResult; 16 | /** 17 | * 命令行执行结果 18 | */ 19 | private String cmdResult; 20 | /** 21 | * 影响行数 22 | */ 23 | private int infactLine; 24 | /** 25 | * SQL语句执行异常 26 | */ 27 | private SQLException sqlException; 28 | /** 29 | * 程序异常 30 | */ 31 | private Exception exception; 32 | /** 33 | * 是否存在异常 34 | */ 35 | private boolean hasException = false; 36 | 37 | public List> getQueryResult() { 38 | return queryResult; 39 | } 40 | 41 | public void setQueryResult(List> queryResult) { 42 | this.queryResult = queryResult; 43 | } 44 | 45 | public String getCmdResult() { 46 | return cmdResult; 47 | } 48 | 49 | public void setCmdResult(String cmdResult) { 50 | this.cmdResult = cmdResult; 51 | } 52 | 53 | public int getInfactLine() { 54 | return infactLine; 55 | } 56 | 57 | public void setInfactLine(int infactLine) { 58 | this.infactLine = infactLine; 59 | } 60 | 61 | public SQLException getSqlException() { 62 | return sqlException; 63 | } 64 | 65 | public void setSqlException(SQLException sqlException) { 66 | this.sqlException = sqlException; 67 | } 68 | 69 | public Exception getException() { 70 | return exception; 71 | } 72 | 73 | public void setException(Exception exception) { 74 | this.exception = exception; 75 | } 76 | 77 | public boolean isHasException() { 78 | return hasException; 79 | } 80 | 81 | public void setHasException(boolean hasException) { 82 | this.hasException = hasException; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/my/sqlite/console/SqliteConsoleBaseService.java: -------------------------------------------------------------------------------- 1 | package my.sqlite.console; 2 | 3 | public class SqliteConsoleBaseService { 4 | /** 5 | * 执行控制台语句 6 | * 7 | * @param sql 8 | * @return 9 | */ 10 | public SqliteConsoleBaseEntity excute(String sql) { 11 | return this.baseDao.excute(sql); 12 | } 13 | /** 14 | * 获取数据库表名集合 15 | * 16 | * @return 17 | */ 18 | public String[] getTableNameArr() { 19 | return this.baseDao.getTableNameArr(); 20 | } 21 | 22 | private SqliteConsoleBaseDao baseDao; 23 | 24 | public SqliteConsoleBaseService(String dbPath, boolean absolute) { 25 | this.baseDao = new SqliteConsoleBaseDao(dbPath, absolute); 26 | } 27 | 28 | public SqliteConsoleBaseService(String dbPath) { 29 | this.baseDao = new SqliteConsoleBaseDao(dbPath); 30 | } 31 | 32 | public SqliteConsoleBaseDao getBaseDao() { 33 | return baseDao; 34 | } 35 | 36 | public void setBaseDao(SqliteConsoleBaseDao baseDao) { 37 | this.baseDao = baseDao; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/my/sqlite/constant/SqliteConstant.java: -------------------------------------------------------------------------------- 1 | package my.sqlite.constant; 2 | 3 | /** 4 | * Sqlite相关常量 5 | * @author 欧阳洁 6 | */ 7 | public class SqliteConstant { 8 | /** 9 | * 程序数据库 10 | */ 11 | public static final String DB_PATH = "database/sqlite.db"; 12 | public static final String DB_PATH1 = "database/sqlite1.db"; 13 | public static final String DB_PATH2 = "database/sqlite2.db"; 14 | public static final String DB_PATH3 = "database/sqlite3.db"; 15 | /** 16 | * 测试数据库 17 | */ 18 | public static final String TEST_DB_PATH = "database/test.db"; 19 | /** 20 | * 程序数据库动态生成规则 21 | */ 22 | public static final int DB_TYPE_DEFAULT = 0;//不分库 23 | public static final int DB_TYPE_BY_MINUTE = 1;//按分钟自动分库 24 | public static final int DB_TYPE_BY_HOUR = 2;//按小时自动分库 25 | public static final int DB_TYPE_BY_DAY = 3;//按天自动分库 26 | public static final int DB_TYPE_BY_MOUTH = 4;//按月自动分库 27 | public static final int DB_TYPE_BY_YEAR = 5;//按年自动分库 28 | /** 29 | * 默认批量插入条数 30 | */ 31 | public static final int DEFAULT_BATCH_COUNT = 100; 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/my/sqlite/exception/SqliteConnectionException.java: -------------------------------------------------------------------------------- 1 | package my.sqlite.exception; 2 | 3 | import my.sqlite.utils.SqliteLogUtils; 4 | 5 | /** 6 | * Sqlite连接异常 7 | * 8 | * @author 欧阳洁 9 | * @since 2018-05-02 16:57 10 | */ 11 | public final class SqliteConnectionException extends Exception { 12 | private static final long serialVersionUID = 1L; 13 | 14 | /** 15 | * 构造函数 16 | * @param e 17 | */ 18 | public SqliteConnectionException(Exception e){ 19 | super(e); 20 | } 21 | 22 | @Override 23 | public void printStackTrace() { 24 | SqliteLogUtils.error("ERROR:[池对象创建异常]"); 25 | super.printStackTrace(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/my/sqlite/exception/SqliteConnectionMaxException.java: -------------------------------------------------------------------------------- 1 | package my.sqlite.exception; 2 | 3 | import my.sqlite.config.SqliteConfig; 4 | import my.sqlite.utils.SqliteLogUtils; 5 | import my.sqlite.utils.SqliteUtils; 6 | 7 | /** 8 | * 连接池溢出异常 9 | * 10 | * @author 欧阳洁 11 | * @since 2018-05-02 16:43 12 | */ 13 | public final class SqliteConnectionMaxException extends Exception { 14 | private static final long serialVersionUID = 1L; 15 | 16 | private int max; 17 | 18 | /** 19 | * 构造函数 20 | */ 21 | public SqliteConnectionMaxException(){ 22 | this.max = SqliteConfig.getPoolConnectionMax(); 23 | } 24 | 25 | /** 26 | * 构造函数 27 | * @param max 28 | */ 29 | public SqliteConnectionMaxException(int max){ 30 | this.max = max; 31 | } 32 | 33 | @Override 34 | public void printStackTrace() { 35 | SqliteLogUtils.error("连接池总数超过最大设置 max:{}", this.max); 36 | super.printStackTrace(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/my/sqlite/thread/SqliteThreadUtils.java: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * Copyright (c) 2005, 2014 springside.github.io 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | *******************************************************************************/ 6 | package my.sqlite.thread; 7 | 8 | import my.sqlite.utils.SqliteUtils; 9 | 10 | import java.util.Arrays; 11 | import java.util.List; 12 | import java.util.Locale; 13 | import java.util.concurrent.ExecutorService; 14 | import java.util.concurrent.Executors; 15 | import java.util.concurrent.ThreadFactory; 16 | import java.util.concurrent.ThreadPoolExecutor; 17 | import java.util.concurrent.TimeUnit; 18 | import java.util.concurrent.atomic.AtomicLong; 19 | 20 | /** 21 | * 线程相关工具类. 22 | * @author 欧阳洁 23 | */ 24 | public class SqliteThreadUtils { 25 | /** 26 | * 数字 27 | */ 28 | private static final int FOUR = 4; 29 | /** 30 | * 数字 31 | */ 32 | private static final int THIRD = 3; 33 | /** 34 | * 数字 35 | */ 36 | private static final int SECOND = 2; 37 | /** 38 | * 空字符串 39 | */ 40 | public static final String STR_EMPTY = ""; 41 | 42 | 43 | /** 44 | * sleep等待, 单位为毫秒, 已捕捉并处理InterruptedException. 45 | * 46 | * @param durationMillis 毫秒 47 | */ 48 | public static void sleep(long durationMillis) throws InterruptedException { 49 | try { 50 | Thread.sleep(durationMillis); 51 | } catch (InterruptedException e) { 52 | Thread.currentThread().interrupt(); 53 | throw e; 54 | } 55 | } 56 | 57 | /** 58 | * sleep等待,已捕捉并处理InterruptedException. 59 | * 60 | * @param duration 时长 61 | * @param unit 时间单位 62 | */ 63 | public static void sleep(long duration, TimeUnit unit) { 64 | try { 65 | Thread.sleep(unit.toMillis(duration)); 66 | } catch (InterruptedException e) { 67 | Thread.currentThread().interrupt(); 68 | } 69 | } 70 | 71 | /** 72 | * 纯粹为了提醒下处理InterruptedException的正确方式,除非你是在写不可中断的任务. 73 | */ 74 | public static void handleInterruptedException() { 75 | Thread.currentThread().interrupt(); 76 | } 77 | 78 | /** 79 | * 通过StackTrace,获得调用者的类名. 80 | * 81 | * @return 类名 82 | */ 83 | public static String getCallerClass() { 84 | 85 | StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace(); 86 | if (stacktrace.length >= FOUR) { 87 | StackTraceElement element = stacktrace[THIRD]; 88 | return element.getClassName(); 89 | } else { 90 | return STR_EMPTY; 91 | } 92 | } 93 | 94 | /** 95 | * 通过StackTrace,获得调用者的"类名.方法名()" 96 | * 97 | * @return 类名.方法名() 98 | */ 99 | public static String getCallerMethod() { 100 | StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace(); 101 | if (stacktrace.length >= FOUR) { 102 | StackTraceElement element = stacktrace[THIRD]; 103 | return element.getClassName() + '.' + element.getMethodName() + "()"; 104 | } else { 105 | return STR_EMPTY; 106 | } 107 | } 108 | 109 | /** 110 | * 通过StackTrace,获得调用者的类名. 111 | * 112 | * @return 获得调用者的类名 113 | */ 114 | public static String getCurrentClass() { 115 | StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace(); 116 | if (stacktrace.length >= THIRD) { 117 | StackTraceElement element = stacktrace[SECOND]; 118 | return element.getClassName(); 119 | } else { 120 | return STR_EMPTY; 121 | } 122 | } 123 | 124 | /** 125 | * 通过StackTrace,获得当前方法的"类名.方法名()" 126 | * 127 | * @return 类名.方法名() 128 | */ 129 | public static String getCurrentMethod() { 130 | StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace(); 131 | if (stacktrace.length >= THIRD) { 132 | StackTraceElement element = stacktrace[SECOND]; 133 | return element.getClassName() + '.' + element.getMethodName() + "()"; 134 | } else { 135 | return STR_EMPTY; 136 | } 137 | } 138 | 139 | /** 140 | * 创建ThreadFactory,使得创建的线程有自己的名字而不是默认的"pool-x-thread-y", 在用threaddump查看线程时特别有用。 格式如"mythread-%d" 141 | * 142 | * @param nameFormat 线程名字 143 | * @return 线程工厂 144 | */ 145 | public static ThreadFactory buildJobFactory(final String nameFormat) { 146 | final ThreadFactory threadFactory = Executors.defaultThreadFactory(); 147 | final AtomicLong count = nameFormat != null?new AtomicLong(0L):null; 148 | final String name = format(nameFormat, new Object[]{Long.valueOf(count.getAndIncrement())}); 149 | return new ThreadFactory() { 150 | public Thread newThread(Runnable runnable) { 151 | Thread thread = threadFactory.newThread(runnable); 152 | if(nameFormat != null) { 153 | thread.setName(name); 154 | } 155 | thread.setDaemon(true); 156 | //thread.setPriority(priority.intValue()); 157 | //thread.setUncaughtExceptionHandler(uncaughtExceptionHandler); 158 | return thread; 159 | } 160 | }; 161 | } 162 | 163 | /** 164 | * 格式化线程名 165 | * @param format 166 | * @param args 167 | * @return 168 | */ 169 | private static String format(String format, Object... args) { 170 | return String.format(Locale.ROOT, format, args); 171 | } 172 | 173 | /** 174 | * 所有线程 175 | * 176 | * @return 线程集合 177 | */ 178 | public static List listThreads() { 179 | int tc = Thread.activeCount(); 180 | Thread[] ts = new Thread[tc]; 181 | Thread.enumerate(ts); 182 | return Arrays.asList(ts); 183 | } 184 | 185 | /** 186 | * 线程详细信息 187 | * 188 | * @param t 线程 189 | * @return 信息 190 | */ 191 | public static String getStackMsg(Thread t) { 192 | StringBuffer sb = new StringBuffer(); 193 | StackTraceElement[] stackArray = t.getStackTrace(); 194 | for (int i = 0; i < stackArray.length; i++) { 195 | StackTraceElement element = stackArray[i]; 196 | sb.append(element.toString() + "\n"); 197 | } 198 | return sb.toString(); 199 | } 200 | 201 | /** 202 | * 线程池信息 203 | * 204 | * @param executorService 线程对象 205 | * @return 信息字符串 206 | */ 207 | public static String getQueueInfo(ExecutorService executorService) { 208 | ThreadPoolExecutor exec = (ThreadPoolExecutor) executorService; 209 | StringBuffer str = new StringBuffer(); 210 | str.append("\r\n" + SqliteUtils.getStringDate() + "==========================="); 211 | str.append("\r\nexec.getTaskCount():" + exec.getTaskCount()); 212 | str.append("\r\nexec.getCompletedTaskCount():" + exec.getCompletedTaskCount()); 213 | str.append("\r\nexec.getActiveCount():" + exec.getActiveCount()); 214 | str.append("\r\nexec.getPoolSize():" + exec.getPoolSize()); 215 | str.append("\r\nexec.getQueue():" + exec.getQueue().size()); 216 | str.append("\r\n==========================="); 217 | return str.toString(); 218 | } 219 | } 220 | -------------------------------------------------------------------------------- /src/main/java/my/sqlite/utils/SqliteConnectionUtils.java: -------------------------------------------------------------------------------- 1 | package my.sqlite.utils; 2 | 3 | import my.sqlite.connection.SqliteBaseConnectionFactory; 4 | 5 | import java.sql.Connection; 6 | import java.sql.SQLException; 7 | 8 | /** 9 | * Sqlite连接工具类 10 | * 11 | * @author 欧阳洁 12 | * @since 2018-05-04 10:09 13 | */ 14 | public class SqliteConnectionUtils { 15 | /** 16 | * 获取默认连接 17 | * @return 18 | */ 19 | public static Connection getConnection() throws SQLException { 20 | return SqliteBaseConnectionFactory.getConnection(); 21 | } 22 | /** 23 | * 获取连接 24 | * @param dbPath 25 | * @return 26 | */ 27 | public static Connection getConnection(String dbPath) throws SQLException { 28 | return SqliteBaseConnectionFactory.getConnection(dbPath); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/my/sqlite/utils/SqliteHelper.java: -------------------------------------------------------------------------------- 1 | package my.sqlite.utils; 2 | 3 | import my.sqlite.annotation.SqliteTable; 4 | import my.sqlite.base.SqliteBaseEntity; 5 | import my.sqlite.config.SqliteConfig; 6 | import my.sqlite.console.SqliteConsoleBaseEntity; 7 | import my.sqlite.constant.SqliteConstant; 8 | 9 | import java.io.ByteArrayOutputStream; 10 | import java.io.IOException; 11 | import java.io.InputStream; 12 | import java.sql.Connection; 13 | import java.sql.PreparedStatement; 14 | import java.sql.ResultSet; 15 | import java.sql.ResultSetMetaData; 16 | import java.sql.SQLException; 17 | import java.sql.Statement; 18 | import java.util.ArrayList; 19 | import java.util.LinkedHashMap; 20 | import java.util.List; 21 | import java.util.Map; 22 | 23 | /** 24 | * 基础操作 25 | * 26 | * @author 欧阳洁 27 | * @create 2017-09-29 17:48 28 | **/ 29 | public class SqliteHelper { 30 | /** 31 | * 数据库路径 32 | */ 33 | private String dbPath; 34 | /** 35 | * 数据库类型 36 | */ 37 | private int dbType; 38 | 39 | /** 40 | * 构造函数 41 | * 42 | * @param targetClass 43 | */ 44 | public SqliteHelper(Class targetClass) { 45 | this.dbPath = SqliteUtils.isBlank(SqliteConfig.getUri()) ? SqliteConstant.DB_PATH : SqliteConfig.getUri(); 46 | this.dbType = SqliteConstant.DB_TYPE_DEFAULT; 47 | SqliteTable sqliteTable = targetClass.getAnnotation(SqliteTable.class); 48 | if (null != sqliteTable) { 49 | this.dbPath = sqliteTable.dbPath(); 50 | this.dbType = sqliteTable.dbType(); 51 | } 52 | // 默认相对路径 53 | if(SqliteConfig.isPathBaseClasspath()) { 54 | this.dbPath = SqliteUtils.getClassRootPath(this.dbPath); 55 | } 56 | } 57 | 58 | /** 59 | * 构造函数 60 | * 61 | * @param dbPath 62 | */ 63 | public SqliteHelper(String dbPath) { 64 | if (SqliteUtils.isBlank(dbPath)) { 65 | this.dbPath = SqliteUtils.isBlank(SqliteConfig.getUri()) ? SqliteConstant.DB_PATH : SqliteConfig.getUri(); 66 | } 67 | this.dbType = SqliteConstant.DB_TYPE_DEFAULT; 68 | // 默认相对路径 69 | if(SqliteConfig.isPathBaseClasspath()) { 70 | this.dbPath = SqliteUtils.getClassRootPath(this.dbPath); 71 | } 72 | } 73 | 74 | /** 75 | * 构造函数 76 | * 77 | * @param dbPath 78 | */ 79 | public SqliteHelper(String dbPath, boolean absolute) { 80 | if (SqliteUtils.isBlank(dbPath)) { 81 | this.dbPath = SqliteUtils.isBlank(SqliteConfig.getUri()) ? SqliteConstant.DB_PATH : SqliteConfig.getUri(); 82 | } else { 83 | this.dbPath = dbPath; 84 | } 85 | this.dbType = SqliteConstant.DB_TYPE_DEFAULT; 86 | if (!absolute) { 87 | this.dbPath = SqliteUtils.getClassRootPath(this.dbPath); 88 | } 89 | } 90 | 91 | /** 92 | * 创建 93 | * 94 | * @param sql 95 | * @return 96 | */ 97 | public int create(String sql) { 98 | return this.execute(sql); 99 | } 100 | 101 | /** 102 | * 插入 103 | * 104 | * @param sql 105 | * @return 106 | */ 107 | public int insert(String sql) { 108 | return this.execute(sql); 109 | } 110 | 111 | /** 112 | * 插入 113 | * 114 | * @param sql 115 | * @param param 116 | * @return 117 | */ 118 | public int insert(String sql, List param) { 119 | return this.execute(sql, param); 120 | } 121 | 122 | /** 123 | * 批量插入 124 | * 125 | * @param sqlList 126 | * @return 127 | */ 128 | public int batchInsertSql(List sqlList) { 129 | return this.batchExecuteSql(sqlList); 130 | } 131 | 132 | /** 133 | * 批量插入 134 | * 135 | * @param sqlList 136 | * @param batchCount 137 | * @return 138 | */ 139 | public int batchInsertSql(List sqlList, int batchCount) { 140 | return this.batchExecuteSql(sqlList, batchCount); 141 | } 142 | 143 | /** 144 | * 批量插入,带参数 145 | * 146 | * @param sqlWithParamList 147 | * @return 148 | */ 149 | public int batchInsert(List sqlWithParamList) { 150 | return this.batchExecute(sqlWithParamList); 151 | } 152 | 153 | /** 154 | * 批量插入,带参数 155 | * 156 | * @param sqlWithParamList 157 | * @param batchCount 158 | * @return 159 | */ 160 | public int batchInsert(List sqlWithParamList, int batchCount) { 161 | return this.batchExecute(sqlWithParamList, batchCount); 162 | } 163 | 164 | /** 165 | * 修改 166 | * 167 | * @param sql 168 | * @return 169 | */ 170 | public int update(String sql) { 171 | return this.execute(sql); 172 | } 173 | 174 | /** 175 | * 修改,带参数 176 | * 177 | * @param sql 178 | * @param param 179 | * @return 180 | */ 181 | public int update(String sql, List param) { 182 | return this.execute(sql, param); 183 | } 184 | 185 | /** 186 | * 批量更新 187 | * 188 | * @param sqlList 189 | * @return 190 | */ 191 | public int batchUpdateSql(List sqlList) { 192 | return this.batchExecuteSql(sqlList); 193 | } 194 | 195 | /** 196 | * 批量更新 197 | * 198 | * @param sqlList 199 | * @param batchCount 200 | * @return 201 | */ 202 | public int batchUpdateSql(List sqlList, int batchCount) { 203 | return this.batchExecuteSql(sqlList, batchCount); 204 | } 205 | 206 | /** 207 | * 批量更新,带参数 208 | * 209 | * @param sqlWithParamList 210 | * @return 211 | */ 212 | public int batchUpdate(List sqlWithParamList) { 213 | return this.batchExecute(sqlWithParamList); 214 | } 215 | 216 | /** 217 | * 批量更新,带参数 218 | * 219 | * @param sqlWithParamList 220 | * @param batchCount 221 | * @return 222 | */ 223 | public int batchUpdate(List sqlWithParamList, int batchCount) { 224 | return this.batchExecute(sqlWithParamList, batchCount); 225 | } 226 | 227 | /** 228 | * 删除 229 | * 230 | * @param sql 231 | * @return 232 | */ 233 | public int delete(String sql) { 234 | return this.execute(sql); 235 | } 236 | 237 | /** 238 | * 删除,带参数 239 | * 240 | * @param sql 241 | * @param param 242 | * @return 243 | */ 244 | public int delete(String sql, List param) { 245 | return this.execute(sql, param); 246 | } 247 | 248 | /** 249 | * 批量删除 250 | * 251 | * @param sqlList 252 | * @return 253 | */ 254 | public int batchDeleteSql(List sqlList) { 255 | return this.batchExecuteSql(sqlList); 256 | } 257 | 258 | /** 259 | * 批量删除 260 | * 261 | * @param sqlList 262 | * @param batchCount 263 | * @return 264 | */ 265 | public int batchDeleteSql(List sqlList, int batchCount) { 266 | return this.batchExecuteSql(sqlList, batchCount); 267 | } 268 | 269 | /** 270 | * 批量删除,带参数 271 | * 272 | * @param sqlWithParamList 273 | * @return 274 | */ 275 | public int batchDelete(List sqlWithParamList) { 276 | return this.batchExecute(sqlWithParamList); 277 | } 278 | 279 | /** 280 | * 批量删除,带参数 281 | * 282 | * @param sqlWithParamList 283 | * @param batchCount 284 | * @return 285 | */ 286 | public int batchDelete(List sqlWithParamList, int batchCount) { 287 | return this.batchExecute(sqlWithParamList, batchCount); 288 | } 289 | 290 | /** 291 | * 根据Id集合批量删除 292 | * 293 | * @param idParamSql 294 | * @param idList 295 | * @param batchCount 296 | * @return 297 | */ 298 | public int batchDeleteByIdList(String idParamSql, List idList, int batchCount) { 299 | return this.batchExecuteByIdList(idParamSql, idList, batchCount); 300 | } 301 | 302 | /** 303 | * 查询语句执行,返回list格式的json字符串 304 | * 305 | * @param sql 306 | * @return 307 | */ 308 | public String queryJsonResult(String sql) { 309 | return this.queryJsonResult(sql, null); 310 | } 311 | 312 | /** 313 | * 查询语句执行,返回list格式的json字符串 314 | * 315 | * @param sql 316 | * @param columnMap 317 | * @return 318 | */ 319 | public String queryJsonResult(String sql, Map columnMap) { 320 | Connection connection = null; 321 | try { 322 | // create a database connection 323 | connection = getConnection(); 324 | Statement statement = connection.createStatement(); 325 | statement.setQueryTimeout(300); // set timeout to 30 sec. 326 | SqliteLogUtils.info("执行查询语句==> " + sql); 327 | ResultSet rs = statement.executeQuery(sql); 328 | 329 | return this.getDataJson(rs, columnMap); 330 | } catch (SQLException e) { 331 | e.printStackTrace(); 332 | return null; 333 | } finally { 334 | try { 335 | if (connection != null) connection.close(); 336 | } catch (SQLException e) { 337 | e.printStackTrace(); 338 | } 339 | } 340 | } 341 | 342 | /** 343 | * 查询语句执行,返回list格式的json字符串,带参数 344 | * 345 | * @param sql 346 | * @param param 347 | * @param columnMap 348 | * @return 349 | */ 350 | public String queryJsonResult(String sql, List param, Map columnMap) { 351 | Connection connection = null; 352 | try { 353 | // create a database connection 354 | connection = getConnection(); 355 | SqliteLogUtils.info("执行查询语句==> " + sql); 356 | PreparedStatement prep = connection.prepareStatement(sql); 357 | prep.setQueryTimeout(300); 358 | if (SqliteUtils.isNotEmpty(param)) { 359 | int count = 1; 360 | for (Object o : param) { 361 | prep.setObject(count++, o); 362 | } 363 | } 364 | 365 | ResultSet rs = prep.executeQuery(); 366 | 367 | return this.getDataJson(rs, columnMap); 368 | } catch (SQLException e) { 369 | e.printStackTrace(); 370 | return null; 371 | } finally { 372 | try { 373 | if (connection != null) connection.close(); 374 | } catch (SQLException e) { 375 | e.printStackTrace(); 376 | } 377 | } 378 | } 379 | 380 | /** 381 | * 获取查询条数的结果 382 | * 383 | * @param sql 384 | * @return 385 | */ 386 | public int queryCountResult(String sql) { 387 | Connection connection = null; 388 | try { 389 | // create a database connection 390 | connection = getConnection(); 391 | Statement statement = connection.createStatement(); 392 | statement.setQueryTimeout(300); // set timeout to 30 sec. 393 | SqliteLogUtils.info("执行查询语句==> " + sql); 394 | ResultSet rs = statement.executeQuery(sql); 395 | 396 | rs.next();//第一行 397 | return rs.getInt(1); 398 | } catch (SQLException e) { 399 | e.printStackTrace(); 400 | return 0; 401 | } finally { 402 | try { 403 | if (connection != null) connection.close(); 404 | } catch (SQLException e) { 405 | e.printStackTrace(); 406 | } 407 | } 408 | } 409 | 410 | /** 411 | * 查询条数语句执行,返回条数,带参数 412 | * 413 | * @param sql 414 | * @param param 415 | * @return 416 | */ 417 | public int queryCountResult(String sql, List param) { 418 | Connection connection = null; 419 | try { 420 | // create a database connection 421 | connection = getConnection(); 422 | SqliteLogUtils.info("执行查询语句==> " + sql); 423 | PreparedStatement prep = connection.prepareStatement(sql); 424 | prep.setQueryTimeout(300); 425 | if (SqliteUtils.isNotEmpty(param)) { 426 | int count = 1; 427 | for (Object o : param) { 428 | prep.setObject(count++, o); 429 | } 430 | } 431 | 432 | ResultSet rs = prep.executeQuery(); 433 | rs.next();//第一行 434 | return rs.getInt(1); 435 | } catch (SQLException e) { 436 | e.printStackTrace(); 437 | return 0; 438 | } finally { 439 | try { 440 | if (connection != null) connection.close(); 441 | } catch (SQLException e) { 442 | e.printStackTrace(); 443 | } 444 | } 445 | } 446 | 447 | /** 448 | * 查询语句执行,返回list格式的json字符串 449 | * 450 | * @param sql 451 | * @return 452 | */ 453 | public List> query(String sql) { 454 | Connection connection = null; 455 | try { 456 | // create a database connection 457 | connection = getConnection(); 458 | Statement statement = connection.createStatement(); 459 | statement.setQueryTimeout(300); // set timeout to 30 sec. 460 | SqliteLogUtils.info("执行查询语句==> " + sql); 461 | ResultSet rs = statement.executeQuery(sql); 462 | 463 | return this.getListMap(rs); 464 | } catch (SQLException e) { 465 | e.printStackTrace(); 466 | return null; 467 | } finally { 468 | try { 469 | if (connection != null) connection.close(); 470 | } catch (SQLException e) { 471 | e.printStackTrace(); 472 | } 473 | } 474 | } 475 | 476 | /** 477 | * 查询语句执行,返回list格式的json字符串,带参数 478 | * 479 | * @param sql 480 | * @param param 481 | * @return 482 | */ 483 | public List> query(String sql, List param) { 484 | Connection connection = null; 485 | try { 486 | // create a database connection 487 | connection = getConnection(); 488 | SqliteLogUtils.info("执行查询语句==> " + sql); 489 | PreparedStatement prep = connection.prepareStatement(sql); 490 | prep.setQueryTimeout(300); 491 | if (SqliteUtils.isNotEmpty(param)) { 492 | int count = 1; 493 | for (Object o : param) { 494 | prep.setObject(count++, o); 495 | } 496 | } 497 | 498 | ResultSet rs = prep.executeQuery(); 499 | 500 | return this.getListMap(rs); 501 | } catch (SQLException e) { 502 | e.printStackTrace(); 503 | return null; 504 | } finally { 505 | try { 506 | if (connection != null) connection.close(); 507 | } catch (SQLException e) { 508 | e.printStackTrace(); 509 | } 510 | } 511 | } 512 | 513 | /** 514 | * 非查询语句执行,无参数 515 | * 516 | * @param sql 517 | * @return 518 | */ 519 | public SqliteConsoleBaseEntity executeForConsole(String sql) { 520 | Connection connection = null; 521 | SqliteConsoleBaseEntity consoleResult = new SqliteConsoleBaseEntity(); 522 | try { 523 | // create a database connection 524 | connection = getConnection(); 525 | Statement statement = connection.createStatement(); 526 | statement.setQueryTimeout(30); // set timeout to 30 sec. 527 | SqliteLogUtils.info("执行非查询语句==> " + sql); 528 | int result = statement.executeUpdate(sql); 529 | SqliteLogUtils.info("执行非查询语句影响行数==> " + result); 530 | consoleResult.setInfactLine(result); 531 | } catch (SQLException e) { 532 | e.printStackTrace(); 533 | consoleResult.setHasException(true); 534 | consoleResult.setSqlException(e); 535 | } catch (Exception e) { 536 | e.printStackTrace(); 537 | consoleResult.setHasException(true); 538 | consoleResult.setException(e); 539 | } finally { 540 | try { 541 | if (connection != null) connection.close(); 542 | } catch (SQLException e) { 543 | e.printStackTrace(); 544 | consoleResult.setHasException(true); 545 | consoleResult.setException(e); 546 | } 547 | } 548 | return consoleResult; 549 | } 550 | 551 | /** 552 | * 查询语句执行,返回list格式的json字符串 553 | * 554 | * @param sql 555 | * @return 556 | */ 557 | public SqliteConsoleBaseEntity queryForConsole(String sql) { 558 | Connection connection = null; 559 | SqliteConsoleBaseEntity consoleResult = new SqliteConsoleBaseEntity(); 560 | try { 561 | // create a database connection 562 | connection = getConnection(); 563 | Statement statement = connection.createStatement(); 564 | statement.setQueryTimeout(300); // set timeout to 30 sec. 565 | SqliteLogUtils.info("执行查询语句==> " + sql); 566 | ResultSet rs = statement.executeQuery(sql); 567 | List> queryResult = this.getListMap(rs); 568 | consoleResult.setQueryResult(queryResult); 569 | consoleResult.setInfactLine(queryResult.size()); 570 | } catch (SQLException e) { 571 | e.printStackTrace(); 572 | consoleResult.setHasException(true); 573 | consoleResult.setSqlException(e); 574 | } catch (Exception e) { 575 | e.printStackTrace(); 576 | consoleResult.setHasException(true); 577 | consoleResult.setException(e); 578 | } finally { 579 | try { 580 | if (connection != null) connection.close(); 581 | } catch (SQLException e) { 582 | e.printStackTrace(); 583 | consoleResult.setHasException(true); 584 | consoleResult.setException(e); 585 | } 586 | } 587 | return consoleResult; 588 | } 589 | 590 | /** 591 | * cmd语句执行 592 | * 593 | * @param cmd 594 | * @return 595 | */ 596 | public SqliteConsoleBaseEntity cmdExecForConsole(String cmd) { 597 | SqliteConsoleBaseEntity consoleResult = new SqliteConsoleBaseEntity(); 598 | try { 599 | SqliteLogUtils.info("执行非查询语句==> " + cmd); 600 | String result = this.cmdExec(cmd); 601 | SqliteLogUtils.info("执行非查询语句影响行数==> " + result); 602 | consoleResult.setCmdResult(result); 603 | consoleResult.setInfactLine(0); 604 | } catch (Exception e) { 605 | e.printStackTrace(); 606 | consoleResult.setHasException(true); 607 | consoleResult.setException(e); 608 | } 609 | return consoleResult; 610 | } 611 | 612 | /** 613 | * 非查询语句执行,无参数 614 | * 615 | * @param sql 616 | * @return 617 | */ 618 | public int execute(String sql) { 619 | Connection connection = null; 620 | try { 621 | // create a database connection 622 | connection = getConnection(); 623 | Statement statement = connection.createStatement(); 624 | statement.setQueryTimeout(30); // set timeout to 30 sec. 625 | SqliteLogUtils.info("执行非查询语句==> " + sql); 626 | int result = statement.executeUpdate(sql); 627 | SqliteLogUtils.info("执行非查询语句影响行数==> " + result); 628 | return result; 629 | } catch (SQLException e) { 630 | e.printStackTrace(); 631 | return -1; 632 | } finally { 633 | try { 634 | if (connection != null) connection.close(); 635 | } catch (SQLException e) { 636 | e.printStackTrace(); 637 | } 638 | } 639 | } 640 | 641 | /** 642 | * 非查询语句执行,带参数的 643 | * 644 | * @param sql 645 | * @param param 646 | * @return 647 | */ 648 | public int execute(String sql, List param) { 649 | Connection connection = null; 650 | try { 651 | // create a database connection 652 | connection = getConnection(); 653 | SqliteLogUtils.info("执行非查询语句==> " + sql); 654 | PreparedStatement prep = connection.prepareStatement(sql); 655 | prep.setQueryTimeout(30); 656 | if (SqliteUtils.isNotEmpty(param)) { 657 | int count = 1; 658 | for (Object o : param) { 659 | prep.setObject(count++, o); 660 | } 661 | } 662 | int result = prep.executeUpdate(); 663 | SqliteLogUtils.info("执行非查询语句影响行数==> " + result); 664 | return result; 665 | } catch (SQLException e) { 666 | e.printStackTrace(); 667 | return -1; 668 | } finally { 669 | try { 670 | if (connection != null) connection.close(); 671 | } catch (SQLException e) { 672 | e.printStackTrace(); 673 | } 674 | } 675 | } 676 | 677 | /** 678 | * 非查询语句批量执行Sql语句 679 | * 680 | * @param sqlList 681 | * @return 682 | */ 683 | public int batchExecuteSql(List sqlList) { 684 | return this.batchExecuteSql(sqlList, SqliteConstant.DEFAULT_BATCH_COUNT); 685 | } 686 | 687 | /** 688 | * 非查询语句批量执行Sql语句 689 | * 690 | * @param sqlList 691 | * @param batchCount 692 | * @return 693 | */ 694 | public int batchExecuteSql(List sqlList, int batchCount) { 695 | Connection connection = null; 696 | try { 697 | int result = 0; 698 | if (SqliteUtils.isNotEmpty(sqlList)) { 699 | if (batchCount <= 0) {//默认批量提交粒度100条 700 | batchCount = SqliteConstant.DEFAULT_BATCH_COUNT; 701 | } 702 | // create a database connection 703 | connection = this.getConnection(); 704 | connection.setAutoCommit(false);//单次执行不自动提交 705 | Statement statement = connection.createStatement(); 706 | for (String sql : sqlList) { 707 | if (!SqliteUtils.isBlank(sql)) { 708 | statement.addBatch(sql); 709 | result++; 710 | } 711 | if (result % batchCount == 0) { 712 | statement.executeBatch(); 713 | connection.commit();// 提交 714 | if (null == connection || connection.isClosed()) { 715 | //如果连接关闭了 就在创建一个 为什么要这样 原因是 connection.commit()后可能conn被关闭 716 | connection = this.getConnection(); 717 | connection.setAutoCommit(false); 718 | statement = connection.createStatement(); 719 | } 720 | } 721 | } 722 | statement.executeBatch(); 723 | statement.close(); 724 | connection.commit();// 提交 725 | connection.setAutoCommit(true); 726 | } 727 | return result; 728 | } catch (SQLException e) { 729 | e.printStackTrace(); 730 | return -1; 731 | } finally { 732 | try { 733 | if (connection != null) connection.close(); 734 | } catch (SQLException e) { 735 | e.printStackTrace(); 736 | } 737 | } 738 | } 739 | 740 | /** 741 | * 非查询语句批量执行Sql语句 742 | * 743 | * @param sqlWithParamList 744 | * @return 745 | */ 746 | public int batchExecute(List sqlWithParamList) { 747 | return this.batchExecute(sqlWithParamList, SqliteConstant.DEFAULT_BATCH_COUNT); 748 | } 749 | 750 | /** 751 | * 非查询语句批量执行Sql语句 752 | * 753 | * @param sqlWithParamList 754 | * @param batchCount 755 | * @return 756 | */ 757 | public int batchExecute(List sqlWithParamList, int batchCount) { 758 | Connection connection = null; 759 | try { 760 | int result = 0; 761 | if (SqliteUtils.isNotEmpty(sqlWithParamList)) { 762 | if (batchCount <= 0) {//默认批量提交粒度100条 763 | batchCount = SqliteConstant.DEFAULT_BATCH_COUNT; 764 | } 765 | // create a database connection 766 | connection = getConnection(); 767 | connection.setAutoCommit(false);//单次执行不自动提交 768 | PreparedStatement prep = null; 769 | String preSql = null; 770 | int currCount = 0; 771 | for (T sqlAndParam : sqlWithParamList) { 772 | if (SqliteUtils.isBlank(sqlAndParam.getCurrentSql())) { 773 | continue; 774 | } 775 | if (!SqliteUtils.equals(preSql, sqlAndParam.getCurrentSql()) || currCount % batchCount == 0) { 776 | if(currCount > 0) { 777 | currCount = 0; 778 | prep.executeBatch(); 779 | connection.commit();// 提交 780 | if (null == connection || connection.isClosed()) { 781 | //如果连接关闭了 就在创建一个 为什么要这样 原因是 connection.commit()后可能conn被关闭 782 | connection = this.getConnection(); 783 | connection.setAutoCommit(false); 784 | } 785 | } 786 | prep = connection.prepareStatement(sqlAndParam.getCurrentSql()); 787 | } 788 | if (SqliteUtils.isNotEmpty(sqlAndParam.getCurrentParam())) { 789 | int count = 1; 790 | for (Object o : sqlAndParam.getCurrentParam()) { 791 | prep.setObject(count++, o); 792 | } 793 | } 794 | prep.addBatch(); 795 | result++; 796 | currCount++; 797 | preSql = sqlAndParam.getCurrentSql(); 798 | } 799 | prep.executeBatch(); 800 | connection.commit();// 提交 801 | connection.setAutoCommit(true); 802 | } 803 | return result; 804 | } catch (SQLException e) { 805 | e.printStackTrace(); 806 | return -1; 807 | } finally { 808 | try { 809 | if (connection != null) connection.close(); 810 | } catch (SQLException e) { 811 | e.printStackTrace(); 812 | } 813 | } 814 | } 815 | 816 | /** 817 | * 非查询语句批量执行Sql语句 818 | * 819 | * @param idParamSql 820 | * @param idList 821 | * @param batchCount 822 | * @return 823 | */ 824 | public int batchExecuteByIdList(String idParamSql, List idList, int batchCount) { 825 | Connection connection = null; 826 | try { 827 | int result = 0; 828 | if (SqliteUtils.isNotEmpty(idList)) { 829 | if (batchCount <= 0) {//默认批量提交粒度100条 830 | batchCount = SqliteConstant.DEFAULT_BATCH_COUNT; 831 | } 832 | // create a database connection 833 | connection = getConnection(); 834 | connection.setAutoCommit(false);//单次执行不自动提交 835 | PreparedStatement prep = null; 836 | prep = connection.prepareStatement(idParamSql); 837 | for (Object id : idList) { 838 | if (null == id) { 839 | continue; 840 | } 841 | prep.setObject(1, id); 842 | prep.addBatch(); 843 | result++; 844 | if (result % batchCount == 0) { 845 | prep.executeBatch(); 846 | connection.commit();// 提交 847 | if (null == connection || connection.isClosed()) { //如果连接关闭了 就在创建一个 为什么要这样 原因是 connection.commit()后可能conn被关闭 848 | connection = this.getConnection(); 849 | connection.setAutoCommit(false); 850 | } 851 | } 852 | } 853 | prep.executeBatch(); 854 | prep.close(); 855 | connection.commit();// 提交 856 | connection.setAutoCommit(true); 857 | } 858 | return result; 859 | } catch (SQLException e) { 860 | e.printStackTrace(); 861 | return -1; 862 | } finally { 863 | try { 864 | if (connection != null) connection.close(); 865 | } catch (SQLException e) { 866 | e.printStackTrace(); 867 | } 868 | } 869 | } 870 | 871 | /** 872 | * 根据结果集返回数据json 873 | * 874 | * @param rs 875 | * @return 876 | * @throws SQLException 877 | */ 878 | public String getDataJson(ResultSet rs) throws SQLException { 879 | String[] nameArr = null; 880 | List> result = new ArrayList>(); 881 | int rows = 1; 882 | while (rs.next()) { 883 | if (rows++ == 1) { 884 | nameArr = getNameArr(rs);// 获取列名 885 | } 886 | 887 | Map one = new LinkedHashMap(); 888 | for (int i = 0; i < nameArr.length; i++) { 889 | String nameKey = nameArr[i]; 890 | one.put(nameKey, rs.getObject(i + 1)); 891 | } 892 | result.add(one); 893 | } 894 | String dataStr = SqliteUtils.getJson(result); 895 | SqliteLogUtils.info("执行查询语句结果==> " + dataStr); 896 | return dataStr; 897 | } 898 | 899 | /** 900 | * 根据结果集返回数据json 901 | * 902 | * @param rs 903 | * @return 904 | * @throws SQLException 905 | */ 906 | public String getDataJson(ResultSet rs, Map columnMap) throws SQLException { 907 | String[] nameArr = null; 908 | List> result = new ArrayList>(); 909 | int rows = 1; 910 | while (rs.next()) { 911 | if (rows++ == 1) { 912 | nameArr = getNameArr(rs);// 获取列名 913 | } 914 | 915 | Map one = new LinkedHashMap(); 916 | for (int i = 0; i < nameArr.length; i++) { 917 | String nameKey = null == columnMap ? nameArr[i] : columnMap.get(nameArr[i]); 918 | nameKey = null == nameKey ? nameArr[i] : nameKey; 919 | one.put(nameKey, rs.getObject(i + 1)); 920 | } 921 | result.add(one); 922 | } 923 | String dataStr = SqliteUtils.getJson(result); 924 | SqliteLogUtils.info("执行查询语句结果==> " + dataStr); 925 | return dataStr; 926 | } 927 | 928 | /** 929 | * 根据结果集返回数据json 930 | * 931 | * @param rs 932 | * @return 933 | * @throws SQLException 934 | */ 935 | public List> getListMap(ResultSet rs) throws SQLException { 936 | String[] nameArr = null; 937 | List> result = new ArrayList>(); 938 | int rows = 1; 939 | while (rs.next()) { 940 | if (rows++ == 1) { 941 | nameArr = getNameArr(rs);// 获取列名 942 | } 943 | 944 | Map one = new LinkedHashMap(); 945 | for (int i = 0; i < nameArr.length; i++) { 946 | String nameKey = nameArr[i]; 947 | one.put(nameKey, rs.getObject(i + 1)); 948 | } 949 | result.add(one); 950 | } 951 | return result; 952 | } 953 | 954 | /** 955 | * 执行cmd命令 956 | * 957 | * @param cmd 958 | */ 959 | public String cmdExec(String cmd) { 960 | StringBuffer cmdConnect = new StringBuffer("sqlite3 ").append(this.dbPath).append("\n"); 961 | cmdConnect.append(cmd).append("\n"); 962 | Runtime rt = Runtime.getRuntime(); 963 | InputStream isNormal = null; 964 | InputStream isError = null; 965 | Process process = null; 966 | ByteArrayOutputStream baos = null; 967 | try { 968 | process = rt.exec(cmdConnect.toString()); 969 | baos = new ByteArrayOutputStream(); 970 | int i; 971 | isNormal = process.getInputStream(); 972 | if (null != isNormal) { 973 | while ((i = isNormal.read()) != -1) { 974 | baos.write(i); 975 | } 976 | } 977 | isError = process.getErrorStream(); 978 | if (null != isError) { 979 | while ((i = isError.read()) != -1) { 980 | baos.write(i); 981 | } 982 | } 983 | String str = baos.toString(); 984 | SqliteLogUtils.info("执行cmd命令[" + cmd + "]==> " + str); 985 | return str; 986 | } catch (IOException e) { 987 | e.printStackTrace(); 988 | return "Exception"; 989 | } finally { 990 | try { 991 | if (null != isNormal) { 992 | isNormal.close(); 993 | } 994 | if (null != isError) { 995 | isError.close(); 996 | } 997 | if (null != baos) { 998 | baos.close(); 999 | } 1000 | } catch (IOException e) { 1001 | e.printStackTrace(); 1002 | } 1003 | } 1004 | } 1005 | 1006 | /** 1007 | * 根据结果集返回列集合 1008 | * 1009 | * @param rs 1010 | * @return 1011 | * @throws SQLException 1012 | */ 1013 | public String[] getNameArr(ResultSet rs) throws SQLException { 1014 | ResultSetMetaData rsmd = rs.getMetaData(); 1015 | int count = rsmd.getColumnCount(); 1016 | String[] nameArr = new String[count]; 1017 | for (int i = 0; i < count; i++) { 1018 | nameArr[i] = rsmd.getColumnName(i + 1); 1019 | nameArr[i] = null == nameArr[i] ? "null" : nameArr[i].toLowerCase(); 1020 | } 1021 | return nameArr; 1022 | } 1023 | 1024 | /** 1025 | * 获取数据库里面的表名 1026 | * 1027 | * @return 1028 | */ 1029 | public String[] getTableNameArr() { 1030 | String result = this.cmdExec(".tables"); 1031 | if (!SqliteUtils.isBlank(result) && !result.startsWith("Error:") && !"Exception".equals(result)) { 1032 | result = result.replaceAll("\r", " "); 1033 | result = result.replaceAll("\n", " "); 1034 | while (result.indexOf(" ") > 0) { 1035 | result = result.replaceAll(" ", " "); 1036 | } 1037 | String[] arr = result.split(" "); 1038 | return arr; 1039 | } 1040 | return null; 1041 | } 1042 | 1043 | /** 1044 | * 数据库连接获取 1045 | * 1046 | * @return 1047 | */ 1048 | private Connection getConnection() throws SQLException { 1049 | String currDbPath = getCurrDbPath(); 1050 | return SqliteConnectionUtils.getConnection(currDbPath); 1051 | } 1052 | 1053 | /** 1054 | * 获取当前数据库名(分库) 1055 | * @return 1056 | */ 1057 | public String getCurrDbPath(){ 1058 | if(SqliteConstant.DB_TYPE_DEFAULT == this.dbType){ 1059 | return this.dbPath; 1060 | } 1061 | StringBuffer currentDbPathSb = new StringBuffer(this.dbPath); 1062 | switch (this.dbType) { 1063 | case SqliteConstant.DB_TYPE_BY_MINUTE: 1064 | currentDbPathSb.append(SqliteUtils.nowFormatStr("yyyyMMddHHmm")).append(".db"); 1065 | break; 1066 | case SqliteConstant.DB_TYPE_BY_HOUR: 1067 | currentDbPathSb.append(SqliteUtils.nowFormatStr("yyyyMMddHH")).append(".db"); 1068 | break; 1069 | case SqliteConstant.DB_TYPE_BY_DAY: 1070 | currentDbPathSb.append(SqliteUtils.nowFormatStr("yyyyMMdd")).append(".db"); 1071 | break; 1072 | case SqliteConstant.DB_TYPE_BY_MOUTH: 1073 | currentDbPathSb.append(SqliteUtils.nowFormatStr("yyyyMM")).append(".db"); 1074 | break; 1075 | case SqliteConstant.DB_TYPE_BY_YEAR: 1076 | currentDbPathSb.append(SqliteUtils.nowFormatStr("yyyy")).append(".db"); 1077 | break; 1078 | default: 1079 | break; 1080 | } 1081 | String currDbPath = currentDbPathSb.toString(); 1082 | return currDbPath; 1083 | } 1084 | } 1085 | -------------------------------------------------------------------------------- /src/main/java/my/sqlite/utils/SqliteJsonUtils.java: -------------------------------------------------------------------------------- 1 | package my.sqlite.utils; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import com.alibaba.fastjson.JSONArray; 5 | import com.alibaba.fastjson.JSONObject; 6 | import com.alibaba.fastjson.TypeReference; 7 | 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | import java.util.Map; 11 | 12 | /** 13 | * fastjson封装的json工具类 14 | * 15 | * @author 欧阳洁 16 | */ 17 | public class SqliteJsonUtils { 18 | /** 19 | * 对象转字符串 20 | * @param object 21 | * @param prettyFormat 是否美化Json字符串 22 | * @return 23 | */ 24 | public static final String toJSONString(Object object, boolean prettyFormat) { 25 | return JSON.toJSONString(object, prettyFormat); 26 | } 27 | 28 | /** 29 | * 对象转字符串 30 | * @param object 31 | * @return 32 | */ 33 | public static final String toJSONString(Object object) { 34 | return JSON.toJSONString(object, false); 35 | } 36 | 37 | /** 38 | * @param 39 | * @param json 40 | * @param clazz 41 | * @return 42 | */ 43 | public static final T getObject(String json, Class clazz) { 44 | T t = null; 45 | try { 46 | t = JSON.parseObject(json, clazz); 47 | } catch (Exception e) { 48 | System.out.println("json字符串转换失败!" + json); 49 | e.printStackTrace(); 50 | } 51 | return t; 52 | } 53 | 54 | /** 55 | * @param 56 | * @param json 57 | * @param objKey 58 | * @param clazz 59 | * @return -> T 60 | */ 61 | public static final T getObject(String json, String objKey, Class clazz) { 62 | JSONObject jsonobj = JSON.parseObject(json); 63 | if (jsonobj == null) { 64 | return null; 65 | } 66 | Object obj = jsonobj.get(objKey); 67 | if (obj == null) { 68 | return null; 69 | } 70 | if (obj instanceof JSONObject) { 71 | return jsonobj.getObject(objKey, clazz); 72 | } else { 73 | System.out.println("json字符串格式不对!"); 74 | } 75 | 76 | return null; 77 | } 78 | 79 | /** 80 | * @param jsonStr json字符串 81 | * @param clazz class名称 82 | * @return 83 | * @Description: json字符串转成为List 84 | */ 85 | public static List getList(String jsonStr, Class clazz) { 86 | List list = new ArrayList(); 87 | try { 88 | list = JSON.parseArray(jsonStr, clazz); 89 | } catch (Exception e) { 90 | System.out.println("json字符串转List失败!" + jsonStr); 91 | e.printStackTrace(); 92 | } 93 | return list; 94 | } 95 | 96 | /** 97 | * @param json 98 | * @param listKey 99 | * @param clazz 100 | * @param 101 | * @return 102 | */ 103 | public static final List getList(String json, String listKey, Class clazz) { 104 | JSONObject jsonobj = JSON.parseObject(json); 105 | if (jsonobj == null) { 106 | return null; 107 | } 108 | Object obj = jsonobj.get(listKey); 109 | if (obj == null) { 110 | return null; 111 | } 112 | if (obj instanceof JSONArray) { 113 | JSONArray jsonarr = (JSONArray) obj; 114 | List list = new ArrayList(); 115 | for (int i = 0; i < jsonarr.size(); i++) { 116 | list.add(jsonarr.getObject(i, clazz)); 117 | } 118 | return list; 119 | } 120 | return null; 121 | } 122 | 123 | /** 124 | * @param jsonString json字符串 125 | * @return 126 | * @Description: json字符串转换成list 127 | */ 128 | public static List> listKeyMaps(String jsonString) { 129 | List> list = new ArrayList>(); 130 | try { 131 | list = JSON.parseObject(jsonString, new TypeReference>>() {}); 132 | } catch (Exception e) { 133 | System.out.println("json字符串转map失败"); 134 | e.printStackTrace(); 135 | } 136 | return list; 137 | } 138 | 139 | /** 140 | * @param jsonStr json字符串 141 | * @return 142 | * @Description: json字符串转换为Map 143 | */ 144 | public static Map json2Map(String jsonStr) { 145 | try { 146 | return JSON.parseObject(jsonStr, Map.class); 147 | } catch (Exception e) { 148 | System.out.println("json字符串转换失败!" + jsonStr); 149 | e.printStackTrace(); 150 | } 151 | return null; 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /src/main/java/my/sqlite/utils/SqliteLogUtils.java: -------------------------------------------------------------------------------- 1 | package my.sqlite.utils; 2 | 3 | import java.util.Date; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | 7 | public class SqliteLogUtils { 8 | /** 9 | * info日志打印 10 | * @param messagePattern 11 | * @param argArray 12 | */ 13 | public static final void info(String messagePattern, Object... argArray) { 14 | StringBuffer info = new StringBuffer("[sqlite-oop]-[info]"); 15 | Date msgDatetime = new Date(); 16 | info.append("-[").append(msgDatetime).append("]"); 17 | // 待处理: 代理获取调用类的类名信息、方法名信息等等 18 | String msgBodyStr = parseMsg(messagePattern,argArray); 19 | info.append("-[").append(msgBodyStr).append("]"); 20 | // 待处理: 这些info信息可以转储到其他地方,形成服务日志 21 | System.out.println(info.toString()); 22 | } 23 | /** 24 | * error日志打印 25 | * @param messagePattern 26 | * @param argArray 27 | */ 28 | public static final void error(String messagePattern, Object... argArray) { 29 | StringBuffer info = new StringBuffer("[sqlite-oop]-[error]"); 30 | Date msgDatetime = new Date(); 31 | info.append("-[").append(msgDatetime).append("]"); 32 | // 待处理: 代理获取调用类的类名信息、方法名信息等等 33 | String msgBodyStr = parseMsg(messagePattern,argArray); 34 | info.append("-[").append(msgBodyStr).append("]"); 35 | // 待处理: 这些info信息可以转储到其他地方,形成服务日志 36 | System.out.println(info.toString()); 37 | } 38 | /** 39 | * error日志打印 40 | * @param messagePattern 41 | * @param argArray 42 | */ 43 | public static final void warn(String messagePattern, Object... argArray) { 44 | StringBuffer info = new StringBuffer("[sqlite-oop]-[warn]"); 45 | Date msgDatetime = new Date(); 46 | info.append("-[").append(msgDatetime).append("]"); 47 | // 待处理: 代理获取调用类的类名信息、方法名信息等等 48 | String msgBodyStr = parseMsg(messagePattern,argArray); 49 | info.append("-[").append(msgBodyStr).append("]"); 50 | // 待处理: 这些info信息可以转储到其他地方,形成服务日志 51 | System.out.println(info.toString()); 52 | } 53 | /** 54 | * debug日志打印 55 | * @param messagePattern 56 | * @param argArray 57 | */ 58 | public static final void debug(String messagePattern, Object... argArray) { 59 | StringBuffer info = new StringBuffer("[sqlite-oop]-[debug]"); 60 | Date msgDatetime = new Date(); 61 | info.append("-[").append(msgDatetime).append("]"); 62 | // 待处理: 代理获取调用类的类名信息、方法名信息等等 63 | String msgBodyStr = parseMsg(messagePattern,argArray); 64 | info.append("-[").append(msgBodyStr).append("]"); 65 | // 待处理: 这些info信息可以转储到其他地方,形成服务日志 66 | System.out.println(info.toString()); 67 | } 68 | /** 69 | * 打印日志信息 70 | * @param messagePattern 71 | * @param argArray 72 | * @return 73 | */ 74 | private static final String parseMsg(String messagePattern, Object[] argArray) { 75 | StringBuilder sbuf = new StringBuilder(messagePattern.length() + 50); 76 | Throwable throwableCandidate = getThrowableCandidate(argArray); 77 | Object[] args = argArray; 78 | if (throwableCandidate != null) { 79 | args = trimmedCopy(argArray); 80 | } 81 | 82 | if (argArray == null && messagePattern != null) { 83 | sbuf.append(messagePattern); 84 | } else { 85 | int i = 0; 86 | for(int L = 0; L < argArray.length; ++L) { 87 | int j = messagePattern.indexOf("{}", i); 88 | if (j == -1) { 89 | break; 90 | } 91 | 92 | if (isEscapedDelimeter(messagePattern, j)) { 93 | if (!isDoubleEscaped(messagePattern, j)) { 94 | --L; 95 | sbuf.append(messagePattern, i, j - 1); 96 | sbuf.append('{'); 97 | i = j + 1; 98 | } else { 99 | sbuf.append(messagePattern, i, j - 1); 100 | deeplyAppendParameter(sbuf, argArray[L], new HashMap()); 101 | i = j + 2; 102 | } 103 | } else { 104 | sbuf.append(messagePattern, i, j); 105 | deeplyAppendParameter(sbuf, argArray[L], new HashMap()); 106 | i = j + 2; 107 | } 108 | } 109 | sbuf.append(messagePattern, i, messagePattern.length()); 110 | } 111 | if(null != throwableCandidate){ 112 | //throwableCandidate.printStackTrace(); 113 | sbuf.append(throwableCandidate.getLocalizedMessage()); 114 | } 115 | return sbuf.toString(); 116 | } 117 | 118 | static final Throwable getThrowableCandidate(Object[] argArray) { 119 | if (argArray != null && argArray.length != 0) { 120 | Object lastEntry = argArray[argArray.length - 1]; 121 | return lastEntry instanceof Throwable ? (Throwable)lastEntry : null; 122 | } else { 123 | return null; 124 | } 125 | } 126 | private static Object[] trimmedCopy(Object[] argArray) { 127 | if (argArray != null && argArray.length != 0) { 128 | int trimemdLen = argArray.length - 1; 129 | Object[] trimmed = new Object[trimemdLen]; 130 | System.arraycopy(argArray, 0, trimmed, 0, trimemdLen); 131 | return trimmed; 132 | } else { 133 | throw new IllegalStateException("non-sensical empty or null argument array"); 134 | } 135 | } 136 | static final boolean isEscapedDelimeter(String messagePattern, int delimeterStartIndex) { 137 | if (delimeterStartIndex == 0) { 138 | return false; 139 | } else { 140 | char potentialEscape = messagePattern.charAt(delimeterStartIndex - 1); 141 | return potentialEscape == '\\'; 142 | } 143 | } 144 | static final boolean isDoubleEscaped(String messagePattern, int delimeterStartIndex) { 145 | return delimeterStartIndex >= 2 && messagePattern.charAt(delimeterStartIndex - 2) == '\\'; 146 | } 147 | private static void deeplyAppendParameter(StringBuilder sbuf, Object o, Map seenMap) { 148 | if (o == null) { 149 | sbuf.append("null"); 150 | } else { 151 | if (!o.getClass().isArray()) { 152 | safeObjectAppend(sbuf, o); 153 | } else if (o instanceof boolean[]) { 154 | booleanArrayAppend(sbuf, (boolean[])((boolean[])o)); 155 | } else if (o instanceof byte[]) { 156 | byteArrayAppend(sbuf, (byte[])((byte[])o)); 157 | } else if (o instanceof char[]) { 158 | charArrayAppend(sbuf, (char[])((char[])o)); 159 | } else if (o instanceof short[]) { 160 | shortArrayAppend(sbuf, (short[])((short[])o)); 161 | } else if (o instanceof int[]) { 162 | intArrayAppend(sbuf, (int[])((int[])o)); 163 | } else if (o instanceof long[]) { 164 | longArrayAppend(sbuf, (long[])((long[])o)); 165 | } else if (o instanceof float[]) { 166 | floatArrayAppend(sbuf, (float[])((float[])o)); 167 | } else if (o instanceof double[]) { 168 | doubleArrayAppend(sbuf, (double[])((double[])o)); 169 | } else { 170 | objectArrayAppend(sbuf, (Object[])((Object[])o), seenMap); 171 | } 172 | 173 | } 174 | } 175 | private static void safeObjectAppend(StringBuilder sbuf, Object o) { 176 | try { 177 | String oAsString = o.toString(); 178 | sbuf.append(oAsString); 179 | } catch (Throwable var3) { 180 | System.out.println("SqliteLogUtils: Failed toString() invocation on an object of type [" + o.getClass().getName() + "]"); 181 | sbuf.append("[FAILED toString()]"); 182 | } 183 | 184 | } 185 | 186 | private static void objectArrayAppend(StringBuilder sbuf, Object[] a, Map seenMap) { 187 | sbuf.append('['); 188 | if (!seenMap.containsKey(a)) { 189 | seenMap.put(a, (Object)null); 190 | int len = a.length; 191 | 192 | for(int i = 0; i < len; ++i) { 193 | deeplyAppendParameter(sbuf, a[i], seenMap); 194 | if (i != len - 1) { 195 | sbuf.append(", "); 196 | } 197 | } 198 | 199 | seenMap.remove(a); 200 | } else { 201 | sbuf.append("..."); 202 | } 203 | 204 | sbuf.append(']'); 205 | } 206 | 207 | private static void booleanArrayAppend(StringBuilder sbuf, boolean[] a) { 208 | sbuf.append('['); 209 | int len = a.length; 210 | 211 | for(int i = 0; i < len; ++i) { 212 | sbuf.append(a[i]); 213 | if (i != len - 1) { 214 | sbuf.append(", "); 215 | } 216 | } 217 | 218 | sbuf.append(']'); 219 | } 220 | 221 | private static void byteArrayAppend(StringBuilder sbuf, byte[] a) { 222 | sbuf.append('['); 223 | int len = a.length; 224 | 225 | for(int i = 0; i < len; ++i) { 226 | sbuf.append(a[i]); 227 | if (i != len - 1) { 228 | sbuf.append(", "); 229 | } 230 | } 231 | 232 | sbuf.append(']'); 233 | } 234 | 235 | private static void charArrayAppend(StringBuilder sbuf, char[] a) { 236 | sbuf.append('['); 237 | int len = a.length; 238 | 239 | for(int i = 0; i < len; ++i) { 240 | sbuf.append(a[i]); 241 | if (i != len - 1) { 242 | sbuf.append(", "); 243 | } 244 | } 245 | 246 | sbuf.append(']'); 247 | } 248 | 249 | private static void shortArrayAppend(StringBuilder sbuf, short[] a) { 250 | sbuf.append('['); 251 | int len = a.length; 252 | 253 | for(int i = 0; i < len; ++i) { 254 | sbuf.append(a[i]); 255 | if (i != len - 1) { 256 | sbuf.append(", "); 257 | } 258 | } 259 | 260 | sbuf.append(']'); 261 | } 262 | 263 | private static void intArrayAppend(StringBuilder sbuf, int[] a) { 264 | sbuf.append('['); 265 | int len = a.length; 266 | 267 | for(int i = 0; i < len; ++i) { 268 | sbuf.append(a[i]); 269 | if (i != len - 1) { 270 | sbuf.append(", "); 271 | } 272 | } 273 | 274 | sbuf.append(']'); 275 | } 276 | 277 | private static void longArrayAppend(StringBuilder sbuf, long[] a) { 278 | sbuf.append('['); 279 | int len = a.length; 280 | 281 | for(int i = 0; i < len; ++i) { 282 | sbuf.append(a[i]); 283 | if (i != len - 1) { 284 | sbuf.append(", "); 285 | } 286 | } 287 | 288 | sbuf.append(']'); 289 | } 290 | 291 | private static void floatArrayAppend(StringBuilder sbuf, float[] a) { 292 | sbuf.append('['); 293 | int len = a.length; 294 | 295 | for(int i = 0; i < len; ++i) { 296 | sbuf.append(a[i]); 297 | if (i != len - 1) { 298 | sbuf.append(", "); 299 | } 300 | } 301 | 302 | sbuf.append(']'); 303 | } 304 | 305 | private static void doubleArrayAppend(StringBuilder sbuf, double[] a) { 306 | sbuf.append('['); 307 | int len = a.length; 308 | 309 | for(int i = 0; i < len; ++i) { 310 | sbuf.append(a[i]); 311 | if (i != len - 1) { 312 | sbuf.append(", "); 313 | } 314 | } 315 | 316 | sbuf.append(']'); 317 | } 318 | } 319 | -------------------------------------------------------------------------------- /src/main/java/my/sqlite/utils/SqliteSqlHelper.java: -------------------------------------------------------------------------------- 1 | package my.sqlite.utils; 2 | 3 | import my.sqlite.annotation.SqliteColumn; 4 | import my.sqlite.annotation.SqliteID; 5 | import my.sqlite.annotation.SqliteSql; 6 | import my.sqlite.annotation.SqliteTable; 7 | import my.sqlite.annotation.SqliteTableSplit; 8 | import my.sqlite.annotation.SqliteTransient; 9 | import my.sqlite.base.SqliteBaseEntity; 10 | 11 | import java.lang.reflect.Field; 12 | import java.lang.reflect.Method; 13 | import java.lang.reflect.Modifier; 14 | import java.util.HashMap; 15 | import java.util.List; 16 | import java.util.Map; 17 | import java.util.Vector; 18 | 19 | /** 20 | * 实体类T的信息收集器 21 | * Sqlite的Sql语句生成器 22 | * 23 | * @author 欧阳洁 24 | * @create 2017-09-30 10:56 25 | **/ 26 | public class SqliteSqlHelper { 27 | private Class targetClass;//实体类 28 | private String tableName;//表名 29 | private String idName;//主键名 30 | private Field idField;//主键变量属性 31 | List columnFields;//表列名对应的变量属性集合 32 | Field tableSplitField;//分表变量属性 33 | Map columnMap;//表列名和字段映射map 34 | 35 | /** 36 | * 构造函数 37 | * 38 | * @param targetClass 39 | */ 40 | public SqliteSqlHelper(Class targetClass) { 41 | this.tableName = this.getTableNameForClass(targetClass); 42 | this.targetClass = targetClass; 43 | this.columnFields = new Vector(); 44 | this.columnMap = new HashMap(); 45 | this.getColumnFields();//收集表列名对应的变量属性相关信息,包括表列名和字段映射 46 | } 47 | 48 | /** 49 | * 创建创建表的sql语句 50 | * 51 | * @return 52 | */ 53 | public String createTableSql() { 54 | return this.createTableSql(null); 55 | } 56 | 57 | /** 58 | * 创建创建表的sql语句 59 | * 60 | * @param tableName 61 | * @return 62 | */ 63 | public String createTableSql(String tableName) { 64 | StringBuffer sql = new StringBuffer("create table if not exists "); 65 | if (SqliteUtils.isBlank(tableName)) { 66 | sql.append(this.getTableName()).append("("); 67 | } else { 68 | sql.append(tableName).append("("); 69 | } 70 | boolean useCumma = false; 71 | for (Field field : this.columnFields) { 72 | if (useCumma) { 73 | sql.append(",");//第一次不用逗号 74 | } else { 75 | useCumma = true; 76 | } 77 | String columnName = field.getName(); 78 | String columnType = "char(20)"; 79 | String notNull = ""; 80 | SqliteID id = field.getAnnotation(SqliteID.class); 81 | if (id != null) { 82 | columnName = SqliteUtils.isBlank(id.name()) ? field.getName() : id.name(); 83 | columnType = id.type(); 84 | //主键默认不为空,如果自增长默认自增长 85 | notNull = id.autoincrement() ? " primary key autoincrement not null" : " primary key not null"; 86 | } else { 87 | SqliteColumn column = field.getAnnotation(SqliteColumn.class); 88 | if (null != column) { 89 | columnName = SqliteUtils.isBlank(column.name()) ? field.getName() : column.name(); 90 | columnType = column.type(); 91 | notNull = column.notNull() ? " not null" : ""; 92 | } 93 | } 94 | sql.append(columnName.toLowerCase()).append(" ").append(columnType.toLowerCase()).append(" ").append(notNull); 95 | } 96 | sql.append(")"); 97 | return sql.toString(); 98 | } 99 | 100 | /** 101 | * 创建删除语句 102 | */ 103 | public void createDelete(T target) { 104 | List param = new Vector(); 105 | StringBuffer sqlBuffer = new StringBuffer(); 106 | sqlBuffer.append("DELETE FROM ").append(this.getTableName(target)); 107 | finishWhereOfAnd(sqlBuffer, param, target);//完成where条件 108 | 109 | target.setCurrentSql(sqlBuffer.toString()); 110 | target.setCurrentParam(param); 111 | } 112 | 113 | /** 114 | * 根据Id删除Sql 115 | * 116 | */ 117 | public String createDeleteById() { 118 | return createDeleteById(null); 119 | } 120 | /** 121 | * 根据Id删除Sql 122 | * 123 | * @param tableExt 124 | */ 125 | public String createDeleteById(String tableExt) { 126 | StringBuffer sqlBuffer = new StringBuffer(); 127 | sqlBuffer.append("DELETE FROM ").append(this.getTableName(tableExt)).append(" WHERE "); 128 | sqlBuffer.append(this.idName).append("=?"); 129 | 130 | return sqlBuffer.toString(); 131 | } 132 | 133 | /** 134 | * 创建更新语句 135 | */ 136 | public void createUpdate(T target) { 137 | List param = new Vector(); 138 | StringBuffer sqlBuffer = new StringBuffer(); 139 | sqlBuffer.append("UPDATE ").append(this.getTableName(target)).append(" SET "); 140 | int count = 0; 141 | for (Field field : this.columnFields) { 142 | if (!Modifier.isStatic(field.getModifiers())) { 143 | Object value = readField(field, target); 144 | if (null == value) {//为空不做更新考虑 145 | continue; 146 | } 147 | SqliteID id = field.getAnnotation(SqliteID.class); 148 | if (id == null) { 149 | if (count > 0) sqlBuffer.append(","); 150 | String columnName = field.getName(); 151 | SqliteColumn sqliteColumn = field.getAnnotation(SqliteColumn.class); 152 | if (null != sqliteColumn) { 153 | columnName = SqliteUtils.isBlank(sqliteColumn.name()) ? field.getName() : sqliteColumn.name(); 154 | } 155 | sqlBuffer.append(columnName.toLowerCase()).append("=?"); 156 | param.add(value); 157 | count++; 158 | } 159 | } 160 | } 161 | finishWhereOfAnd(sqlBuffer, param, target);//完成where条件 162 | 163 | target.setCurrentSql(sqlBuffer.toString()); 164 | target.setCurrentParam(param); 165 | } 166 | 167 | /** 168 | * 创建插入语句 169 | */ 170 | public void createInsert(T target) { 171 | List param = new Vector(); 172 | StringBuffer sqlBuffer = new StringBuffer(); 173 | sqlBuffer.append("INSERT INTO ").append(this.getTableName(target,true)).append("("); 174 | for (Field field : this.columnFields) { 175 | if (!Modifier.isStatic(field.getModifiers())) { 176 | SqliteID id = field.getAnnotation(SqliteID.class); 177 | if (id == null) { 178 | String columnName = field.getName(); 179 | SqliteColumn sqliteColumn = field.getAnnotation(SqliteColumn.class); 180 | if (null != sqliteColumn) { 181 | columnName = SqliteUtils.isBlank(sqliteColumn.name()) ? field.getName() : sqliteColumn.name(); 182 | } 183 | sqlBuffer.append(columnName.toLowerCase()).append(","); 184 | param.add(readField(field, target)); 185 | } 186 | } 187 | } 188 | int length = sqlBuffer.length(); 189 | sqlBuffer.delete(length - 1, length).append(")values("); 190 | int size = param.size(); 191 | for (int x = 0; x < size; x++) { 192 | if (x != 0) { 193 | sqlBuffer.append(","); 194 | } 195 | sqlBuffer.append("?"); 196 | } 197 | sqlBuffer.append(")"); 198 | 199 | target.setCurrentSql(sqlBuffer.toString()); 200 | target.setCurrentParam(param); 201 | } 202 | 203 | /** 204 | * 创建查询语句 205 | */ 206 | public void createSelect(T target) { 207 | List param = new Vector(); 208 | StringBuffer sqlBuffer = new StringBuffer(); 209 | sqlBuffer.append("SELECT * FROM ").append(this.getTableName(target)); 210 | finishWhereOfAnd(sqlBuffer, param, target); 211 | 212 | target.setCurrentSql(sqlBuffer.toString()); 213 | target.setCurrentParam(param); 214 | } 215 | 216 | /** 217 | * 创建查询语句 218 | * @param target 219 | */ 220 | public void createCount(T target) { 221 | List param = new Vector(); 222 | StringBuffer sqlBuffer = new StringBuffer(); 223 | sqlBuffer.append("SELECT COUNT(1) FROM ").append(this.getTableName(target)); 224 | finishWhereOfAnd(sqlBuffer, param, target); 225 | 226 | target.setCurrentSql(sqlBuffer.toString()); 227 | target.setCurrentParam(param); 228 | } 229 | 230 | /** 231 | * 创建查询语句 232 | * @param id 233 | * @return 234 | */ 235 | public String createSelectById(Object id) { 236 | return this.createSelectById(id,null); 237 | } 238 | 239 | /** 240 | * 创建查询语句 241 | * @param id 242 | * @param tableExt 243 | * @return 244 | */ 245 | public String createSelectById(Object id,String tableExt) { 246 | StringBuffer sqlBuffer = new StringBuffer(); 247 | sqlBuffer.append("SELECT * FROM ").append(this.getTableName(tableExt)).append(" WHERE "); 248 | sqlBuffer.append(this.idName).append("=?"); 249 | 250 | return sqlBuffer.toString(); 251 | } 252 | 253 | /** 254 | * 创建自定义查询语句 255 | * @param daoMethodInfo 256 | * @param target 257 | */ 258 | public void convertSelfSql(StackTraceElement daoMethodInfo, T target) { 259 | if (null == daoMethodInfo) {//为空用默认的查询语句 260 | createSelect(target); 261 | return; 262 | } 263 | Method method = getMethod(daoMethodInfo.getClassName(), daoMethodInfo.getMethodName(), target.getClass()); 264 | if (null == method) {//为空用默认的查询语句 265 | createSelect(target); 266 | return; 267 | } 268 | SqliteSql sqliteSql = method.getAnnotation(SqliteSql.class); 269 | if (null != sqliteSql) { 270 | List param = new Vector(); 271 | String[] paramNameArr = sqliteSql.params(); 272 | if (null != paramNameArr && paramNameArr.length > 0) { 273 | Field[] fieldArray = this.targetClass.getDeclaredFields(); 274 | for (String paramName : paramNameArr) { 275 | Object value = null; 276 | for (Field field : fieldArray) { 277 | if (paramName.equalsIgnoreCase(field.getName())) { 278 | value = readField(field, target); 279 | break; 280 | } 281 | } 282 | param.add(value); 283 | } 284 | 285 | } 286 | String sql = SqliteUtils.replace(sqliteSql.sql(), "this.tableName", this.getTableName()); 287 | //待处理:此处可以读取自定义SQL的辅助注解,像上面提到的SqliteSqlWhereIf注解,实现动态SQL 288 | target.setCurrentSql(sql); 289 | target.setCurrentParam(param); 290 | } 291 | } 292 | 293 | /** 294 | * 创建自定义查询语句,参数随机 295 | * 296 | * @param daoMethodInfo 297 | * @param params 298 | * @return 299 | */ 300 | public String convertSelfSql(StackTraceElement daoMethodInfo, Object... params) { 301 | if (null == daoMethodInfo) {//为空不做处理 302 | System.out.println("未获取到自定义的语句!"); 303 | return null; 304 | } 305 | Class[] classArr = null; 306 | if (null != params && params.length > 0) { 307 | classArr = new Class[params.length]; 308 | for (int i = 0; i < params.length; i++) { 309 | classArr[i] = params[i].getClass(); 310 | } 311 | } 312 | Method method = getMethod(daoMethodInfo.getClassName(), daoMethodInfo.getMethodName(), classArr); 313 | if (null == method) {//为空不做处理 314 | System.out.println("未获取到自定义的语句!"); 315 | return null; 316 | } 317 | SqliteSql sqliteSql = method.getAnnotation(SqliteSql.class); 318 | String sql = SqliteUtils.replace(sqliteSql.sql(), "this.tableName", this.getTableName()); 319 | //待处理:此处可以读取自定义SQL的辅助注解,像上面提到的SqliteSqlWhereIf注解,实现动态SQL 320 | return sql; 321 | } 322 | 323 | /** 324 | * 通过类名、方法名和参数类型定位到具体的方法 325 | * 326 | * @param className 327 | * @param methodName 328 | * @param parameterTypes 329 | * @return 330 | */ 331 | protected Method getMethod(String className, String methodName, Class... parameterTypes) { 332 | try { 333 | Class clazz = Class.forName(className); 334 | Method method = clazz.getMethod(methodName, parameterTypes); 335 | return method; 336 | } catch (ClassNotFoundException e) { 337 | e.printStackTrace(); 338 | return null; 339 | } catch (NoSuchMethodException e) { 340 | e.printStackTrace(); 341 | return null; 342 | } 343 | } 344 | 345 | /** 346 | * 获取列属性集合(过滤调非表字段属性) 347 | */ 348 | protected void getColumnFields() { 349 | Field[] fieldArray = this.targetClass.getDeclaredFields(); 350 | if (null == fieldArray || fieldArray.length == 0) { 351 | return; 352 | } 353 | for (Field field : fieldArray) { 354 | String columnName = field.getName(); 355 | if (this.tableSplitField == null && field.isAnnotationPresent(SqliteTableSplit.class)) { 356 | //动态分表功能,记录分表字段 357 | this.tableSplitField = field; 358 | } 359 | if (field.isAnnotationPresent(SqliteTransient.class)) { 360 | // 有SqliteTransient注解的属性不记录,但是值的映射填充可以添加 361 | SqliteColumn column = field.getAnnotation(SqliteColumn.class); 362 | if (null != column) { 363 | columnName = SqliteUtils.isBlank(column.name()) ? field.getName() : column.name(); 364 | } 365 | this.columnMap.put(columnName.toLowerCase(), field.getName()); 366 | continue;//如果为非表字段的属性,则不做表字段记录 367 | } 368 | this.columnFields.add(field); 369 | SqliteID id = field.getAnnotation(SqliteID.class); 370 | if (id != null) { 371 | columnName = SqliteUtils.isBlank(id.name()) ? field.getName() : id.name(); 372 | this.idName = columnName.toLowerCase(); 373 | this.idField = field; 374 | } else { 375 | SqliteColumn column = field.getAnnotation(SqliteColumn.class); 376 | if (null != column) { 377 | columnName = SqliteUtils.isBlank(column.name()) ? field.getName() : column.name(); 378 | } 379 | } 380 | this.columnMap.put(columnName.toLowerCase(), field.getName()); 381 | } 382 | //getColumnFields(clazz.getSuperclass()); 383 | } 384 | 385 | /** 386 | * 根据注解获取表名 387 | */ 388 | public String getTableName() { 389 | if (SqliteUtils.isBlank(this.tableName)) { 390 | this.tableName = this.getTableNameForClass(this.targetClass); 391 | } 392 | return this.tableName; 393 | } 394 | 395 | /** 396 | * 根据注解获取表名 397 | * 398 | * @param target 399 | * @return 400 | */ 401 | public String getTableName(T target) { 402 | return this.getTableName(target,false); 403 | } 404 | 405 | /** 406 | * 根据注解获取表名 407 | * @param target 408 | * @param needCreateTable 是否需要判断并自动创建表 409 | * @return 410 | */ 411 | public String getTableName(T target,boolean needCreateTable) { 412 | if (SqliteUtils.isBlank(this.tableName)) { 413 | this.tableName = this.getTableNameForClass(this.targetClass); 414 | } 415 | //启用分表功能后,动态获取表名,并生成建表SQL 416 | if (null != this.tableSplitField) { 417 | String fieldValue = (String) this.readField(this.tableSplitField, target); 418 | if (!SqliteUtils.isBlank(fieldValue)) { 419 | String joinStr = "_"; 420 | SqliteTableSplit splitAnnotation = this.tableSplitField.getAnnotation(SqliteTableSplit.class); 421 | if (null != splitAnnotation) { 422 | joinStr = splitAnnotation.joinStr(); 423 | } 424 | String currentTableName = new StringBuffer(this.tableName).append(joinStr).append(fieldValue).toString(); 425 | if(needCreateTable) { 426 | String creatTableSql = this.createTableSql(currentTableName); 427 | target.setNeedCreateBefSql(creatTableSql); 428 | } 429 | return currentTableName; 430 | } 431 | } 432 | return this.tableName; 433 | } 434 | 435 | /** 436 | * 根据注解获取表名 437 | * 438 | * @param tableExt 439 | * @return 440 | */ 441 | public String getTableName(String tableExt) { 442 | if (SqliteUtils.isBlank(this.tableName)) { 443 | this.tableName = this.getTableNameForClass(this.targetClass); 444 | } 445 | if (!SqliteUtils.isBlank(tableExt) && null != this.tableSplitField) { 446 | String joinStr = "_"; 447 | SqliteTableSplit splitAnnotation = this.tableSplitField.getAnnotation(SqliteTableSplit.class); 448 | if (null != splitAnnotation) { 449 | joinStr = splitAnnotation.joinStr(); 450 | } 451 | String currentTableName = new StringBuffer(this.tableName).append(joinStr).append(tableExt).toString(); 452 | return currentTableName; 453 | } 454 | return this.tableName; 455 | } 456 | 457 | /** 458 | * 获取注解表名 459 | * 460 | * @param clazz 461 | * @return 462 | */ 463 | public String getTableNameForClass(Class clazz) { 464 | if (!SqliteUtils.isBlank(this.tableName)) { 465 | return this.tableName.toLowerCase(); 466 | } 467 | SqliteTable table = clazz.getAnnotation(SqliteTable.class); 468 | if (null != table) { 469 | this.tableName = table.name(); 470 | if (SqliteUtils.isBlank(this.tableName)) { 471 | this.tableName = clazz.getSimpleName(); 472 | } 473 | } else { 474 | this.tableName = clazz.getSimpleName(); 475 | } 476 | return this.tableName.toLowerCase(); 477 | } 478 | 479 | /** 480 | * 读取属性的值 481 | * 482 | * @param field 483 | * @return 484 | */ 485 | protected Object readField(Field field, T target) { 486 | try { 487 | return SqliteUtils.readField(field, target, true); 488 | } catch (Exception e) { 489 | throw new RuntimeException(e); 490 | } 491 | } 492 | 493 | /** 494 | * 补全用and连接的sql语句 495 | * 496 | * @param sqlBuffer 497 | * @param param 498 | * @param target 499 | */ 500 | private void finishWhereOfAnd(StringBuffer sqlBuffer, List param, T target) { 501 | sqlBuffer.append(" WHERE 1=1 "); 502 | Object idValue = null; 503 | if (null != this.idField) { 504 | idValue = readField(this.idField, target); 505 | } 506 | if (idValue != null) { 507 | sqlBuffer.append(" and ").append(this.idName).append("=?"); 508 | param.add(idValue); 509 | } else { 510 | for (Field field : this.columnFields) { 511 | if (!Modifier.isStatic(field.getModifiers())) { 512 | Object currentValue = readField(field, target); 513 | if (null != currentValue && !SqliteUtils.equals(this.idName, field.getName())) { 514 | String columnName = field.getName(); 515 | SqliteColumn sqliteColumn = field.getAnnotation(SqliteColumn.class); 516 | if (null != sqliteColumn) { 517 | columnName = SqliteUtils.isBlank(sqliteColumn.name()) ? field.getName() : sqliteColumn.name(); 518 | } 519 | sqlBuffer.append(" and ").append(columnName.toLowerCase()).append("=?"); 520 | param.add(currentValue); 521 | } 522 | } 523 | } 524 | } 525 | } 526 | 527 | public Class getTargetClass() { 528 | return targetClass; 529 | } 530 | 531 | public void setTargetClass(Class targetClass) { 532 | this.targetClass = targetClass; 533 | } 534 | 535 | public void setTableName(String tableName) { 536 | this.tableName = tableName; 537 | } 538 | 539 | public String getIdName() { 540 | return idName; 541 | } 542 | 543 | public void setIdName(String idName) { 544 | this.idName = idName; 545 | } 546 | 547 | public Field getIdField() { 548 | return idField; 549 | } 550 | 551 | public void setIdField(Field idField) { 552 | this.idField = idField; 553 | } 554 | 555 | public void setColumnFields(List columnFields) { 556 | this.columnFields = columnFields; 557 | } 558 | 559 | public Map getColumnMap() { 560 | return columnMap; 561 | } 562 | 563 | public void setColumnMap(Map columnMap) { 564 | this.columnMap = columnMap; 565 | } 566 | } 567 | 568 | -------------------------------------------------------------------------------- /src/main/java/my/sqlite/utils/SqliteUtils.java: -------------------------------------------------------------------------------- 1 | package my.sqlite.utils; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import com.alibaba.fastjson.JSONArray; 5 | import com.alibaba.fastjson.JSONObject; 6 | 7 | import java.lang.reflect.AccessibleObject; 8 | import java.lang.reflect.Constructor; 9 | import java.lang.reflect.Field; 10 | import java.lang.reflect.InvocationTargetException; 11 | import java.lang.reflect.Member; 12 | import java.lang.reflect.Modifier; 13 | import java.text.SimpleDateFormat; 14 | import java.util.ArrayList; 15 | import java.util.Collection; 16 | import java.util.Date; 17 | import java.util.List; 18 | 19 | public class SqliteUtils { 20 | private static final String osName = System.getProperty("os.name").toLowerCase(); 21 | 22 | /** 23 | * 获取class目录下单文件绝对路径 24 | * 25 | * @param path 26 | * @return 27 | */ 28 | public static String getClassRootPath(String path) { 29 | path = SqliteUtils.trimToEmpty(path); 30 | String filePath = SqliteUtils.class.getResource("/").getPath().toString(); 31 | if (filePath == null) return null; 32 | String p = ""; 33 | if (path.startsWith("/")) { 34 | p = filePath + path.substring(1); 35 | } else { 36 | p = filePath + path; 37 | } 38 | return p; 39 | } 40 | 41 | /** 42 | * 替换字符串,非正则匹配 43 | * 44 | * @param text 45 | * @param searchString 46 | * @param replacement 47 | * @return 48 | */ 49 | public static String replace(String text, String searchString, String replacement) { 50 | return replace(text, searchString, replacement, -1); 51 | } 52 | 53 | /** 54 | * 替换字符串,非正则匹配 55 | * 56 | * @param text 57 | * @param searchString 58 | * @param replacement 59 | * @param max 60 | * @return 61 | */ 62 | public static String replace(String text, String searchString, String replacement, int max) { 63 | if (!isBlank(text) && !isBlank(searchString) && replacement != null && max != 0) { 64 | int start = 0; 65 | int end = text.indexOf(searchString, start); 66 | if (end == -1) { 67 | return text; 68 | } else { 69 | int replLength = searchString.length(); 70 | int increase = replacement.length() - replLength; 71 | increase = increase < 0 ? 0 : increase; 72 | increase *= max < 0 ? 16 : (max > 64 ? 64 : max); 73 | 74 | StringBuffer buf; 75 | for (buf = new StringBuffer(text.length() + increase); end != -1; end = text.indexOf(searchString, start)) { 76 | buf.append(text.substring(start, end)).append(replacement); 77 | start = end + replLength; 78 | --max; 79 | if (max == 0) { 80 | break; 81 | } 82 | } 83 | 84 | buf.append(text.substring(start)); 85 | return buf.toString(); 86 | } 87 | } else { 88 | return text; 89 | } 90 | } 91 | 92 | /** 93 | * 去除字符串两边空格,为空就转成空字符串 94 | * 95 | * @param str 96 | * @return 97 | */ 98 | public static String trimToEmpty(final String str) { 99 | return str == null ? "" : str.trim(); 100 | } 101 | 102 | /** 103 | * 是否为windows系统 104 | * 105 | * @return 106 | */ 107 | public static boolean isWindows() { 108 | return osName.indexOf("windows") >= 0; 109 | } 110 | 111 | 112 | /** 113 | * 判断集合是否为空 114 | * 115 | * @param coll 116 | * @return 117 | */ 118 | public static boolean isEmpty(Collection coll) { 119 | return coll == null || coll.isEmpty(); 120 | } 121 | 122 | /** 123 | * 判断集合是否不为空 124 | * 125 | * @param coll 126 | * @return 127 | */ 128 | public static boolean isNotEmpty(Collection coll) { 129 | return !isEmpty(coll); 130 | } 131 | 132 | /** 133 | * 对象转字符串 134 | * 135 | * @param obj 136 | * @return 137 | */ 138 | public static String toString(Object obj) { 139 | return obj == null ? "" : obj.toString(); 140 | } 141 | 142 | /** 143 | * 判断字符串是否为空 144 | * 145 | * @param str 146 | * @return 147 | */ 148 | public static boolean isBlank(String str) { 149 | int strLen; 150 | if (str != null && (strLen = str.length()) != 0) { 151 | for (int i = 0; i < strLen; ++i) { 152 | if (!Character.isWhitespace(str.charAt(i))) { 153 | return false; 154 | } 155 | } 156 | 157 | return true; 158 | } else { 159 | return true; 160 | } 161 | } 162 | 163 | /** 164 | * 判断字符串是否相等 165 | * 166 | * @param str1 167 | * @param str2 168 | * @return 169 | */ 170 | public static boolean equals(String str1, String str2) { 171 | return str1 == null ? str2 == null : str1.equals(str2); 172 | } 173 | 174 | /** 175 | * 去除字符串两边空格 176 | * 177 | * @param str 178 | * @return 179 | */ 180 | public static String trim(String str) { 181 | return str == null ? null : str.trim(); 182 | } 183 | 184 | /** 185 | * 读取对象的某个注解属性值 186 | * 187 | * @param field 188 | * @param target 189 | * @param forceAccess 190 | * @return 191 | * @throws IllegalAccessException 192 | */ 193 | public static Object readField(final Field field, final Object target, final boolean forceAccess) throws IllegalAccessException { 194 | if (field == null) { 195 | return null; 196 | } 197 | if (forceAccess && !field.isAccessible()) { 198 | field.setAccessible(true); 199 | } else { 200 | SqliteUtils.setAccessibleWorkaround(field); 201 | } 202 | return field.get(target); 203 | } 204 | 205 | static boolean setAccessibleWorkaround(final AccessibleObject o) { 206 | if (o == null || o.isAccessible()) { 207 | return false; 208 | } 209 | final Member m = (Member) o; 210 | if (!o.isAccessible() && Modifier.isPublic(m.getModifiers()) && isPackageAccess(m.getDeclaringClass().getModifiers())) { 211 | try { 212 | o.setAccessible(true); 213 | return true; 214 | } catch (final SecurityException e) { // NOPMD 215 | // ignore in favor of subsequent IllegalAccessException 216 | } 217 | } 218 | return false; 219 | } 220 | 221 | private static final int ACCESS_TEST = Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE; 222 | 223 | static boolean isPackageAccess(final int modifiers) { 224 | return (modifiers & ACCESS_TEST) == 0; 225 | } 226 | 227 | /** 228 | * Object转化为json字符串 229 | * <功能详细描述> 230 | * 231 | * @param object 232 | * @return String [返回类型说明] 233 | * @throws throws [违例类型] [违例说明] 234 | * @see [类、类#方法、类#成员] 235 | */ 236 | public static String getJson(Object object) { 237 | try { 238 | return SqliteJsonUtils.toJSONString(object); 239 | } catch (Exception e) { 240 | e.printStackTrace(); 241 | return null; 242 | } 243 | } 244 | 245 | /** 246 | * 转换 List 为 Json字符串 247 | * 248 | * @param list 249 | * @return 250 | */ 251 | public static String getJson(List list) { 252 | if (list == null) return "[]"; 253 | return SqliteJsonUtils.toJSONString(list); 254 | } 255 | 256 | /** 257 | * 将日期时间对象转为 指定格式的字符串 258 | * 259 | * @param format 260 | * @return string 261 | */ 262 | public static String nowFormatStr(String format) { 263 | SimpleDateFormat formatter = new SimpleDateFormat(format); 264 | Date currentTime = new Date(); 265 | String dateString = formatter.format(currentTime); 266 | return dateString; 267 | } 268 | 269 | /** 270 | * 根据用户传入的时间表示格式,返回当前时间的格式 如果是yyyyMMdd,注意字母y不能大写。 271 | * 272 | * @param sformat yyyyMMddHHmmss 273 | * @return 274 | */ 275 | public static String getUserDate(String sformat) { 276 | Date currentTime = new Date(); 277 | SimpleDateFormat formatter = new SimpleDateFormat(sformat); 278 | String dateString = formatter.format(currentTime); 279 | return dateString; 280 | } 281 | 282 | /** 283 | * 获取现在日期时间 284 | * 285 | * @return 返回字符串格式 yyyy-MM-dd HH:mm:ss 286 | */ 287 | public static String getStringDate() { 288 | return getUserDate("yyyy-MM-dd HH:mm:ss"); 289 | } 290 | 291 | /** 292 | * 根据类路径名,无参的构造实例化 293 | * 294 | * @param fileClass 295 | * @return 296 | */ 297 | public static T getInstance(Class fileClass) { 298 | T result = null; 299 | try { 300 | // 要创建的类的构造器 301 | //Class fileClass = Class.forName(beanClassName); 302 | 303 | // 调用pType为变量的getConstructor(),获得一个专属ctor 304 | Constructor ctor = null; 305 | try { 306 | ctor = fileClass.getConstructor(); 307 | } catch (NoSuchMethodException e) { 308 | e.printStackTrace(); 309 | } 310 | 311 | // 调用上述专属ctor的newInstance() 312 | try { 313 | result = (T) ctor.newInstance(); 314 | } catch (InvocationTargetException e) { 315 | System.out.println("构造参数有误!"); 316 | e.printStackTrace(); 317 | } 318 | } catch (InstantiationException e) { 319 | System.out.println("构造实例化失败!" + e.getMessage()); 320 | e.printStackTrace(); 321 | } catch (IllegalAccessException e) { 322 | System.out.println("构造实例化内存分配失败!" + e.getMessage()); 323 | e.printStackTrace(); 324 | } 325 | return result; 326 | } 327 | 328 | /** 329 | * <一句话功能简述> 330 | * <功能详细描述> 331 | * 332 | * @param jsonString json字符串 333 | * @param clazz 对象class,如果要转化为List 传入ObjectA.class 334 | * @return Object [返回类型说明] 335 | * @see [类、类#方法、类#成员]T 336 | */ 337 | public static T getInstance(String jsonString, Class clazz) { 338 | if (SqliteUtils.isBlank(jsonString)) return null; 339 | if ("[]".equals(SqliteUtils.trim(jsonString))) return null; 340 | Object obj = JSON.parse(jsonString); 341 | if (obj == null) { 342 | return null; 343 | } 344 | if (obj instanceof JSONArray) { 345 | JSONArray jsonarr = (JSONArray) obj; 346 | List list = new ArrayList(); 347 | //如果集合不为null则是返回成功,则需要修改数据的时间 348 | //创建转换json的需要转换的集合类型 [{},{}] 349 | for (int i = 0; i < jsonarr.size(); i++) { 350 | list.add(jsonarr.getObject(i, clazz)); 351 | } 352 | return (T)list; 353 | }else if(obj instanceof JSONObject){ 354 | JSONObject jsonObject = (JSONObject) obj; 355 | return (T)jsonObject.toJavaObject(clazz); 356 | }else { 357 | return null; 358 | } 359 | } 360 | 361 | /** 362 | * 字符转数字 363 | * @param intStr 364 | * @return 365 | */ 366 | public static int parseInt(String intStr){ 367 | return parseInt(intStr,0); 368 | } 369 | /** 370 | * 字符转数字 371 | * @param intStr 372 | * @param defaultValue 373 | * @return 374 | */ 375 | public static int parseInt(String intStr,int defaultValue){ 376 | if(isBlank(intStr)){ 377 | return defaultValue; 378 | }else { 379 | try { 380 | return Integer.parseInt(intStr); 381 | }catch (Exception e){ 382 | return defaultValue; 383 | } 384 | } 385 | } 386 | 387 | /** 388 | * 获取当前时间戳 389 | * @return 390 | */ 391 | public static long getNowStamp(){ 392 | return new Date().getTime(); 393 | } 394 | } 395 | 396 | 397 | 398 | -------------------------------------------------------------------------------- /src/main/resources/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/petterobam/sqlite-oop/947ba926a449d3d75b04782e74e38f637e3ad5aa/src/main/resources/README.md -------------------------------------------------------------------------------- /src/main/resources/config/sqlite.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/petterobam/sqlite-oop/947ba926a449d3d75b04782e74e38f637e3ad5aa/src/main/resources/config/sqlite.properties -------------------------------------------------------------------------------- /src/main/resources/database/readme.md: -------------------------------------------------------------------------------- 1 | # 新建数据库 2 | 3 | sqlite3 file_parse.db 4 | 5 | # 建表 6 | 7 | create table t_test_table( 8 | id integer primary key autoincrement not null, 9 | name char(100) not null, 10 | author char(100) not null, 11 | article text, 12 | create_time char(20) not null 13 | ); 14 | 15 | # 新增 16 | 17 | insert into t_test_table(name,author, artitcle,create_time) 18 | values ("test11","petter","article1","2017-09-29 17:01:22"); 19 | 20 | # 查询 21 | 22 | select * from t_test_table; 23 | select * from t_test_table where id=1; 24 | 25 | # 修改 26 | 27 | update t_test_table 28 | set name = "test11_修改", article = "article1_修改", create_time = "2017-09-29 17:01:27" 29 | where id=1; 30 | select * from t_test_table where id = 1; 31 | 32 | # 删除 33 | 34 | delete from t_test_table where id = 1; 35 | select count(1) from t_test_table where id = 1; 36 | 37 | -------------------------------------------------------------------------------- /src/main/resources/database/test.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/petterobam/sqlite-oop/947ba926a449d3d75b04782e74e38f637e3ad5aa/src/main/resources/database/test.db -------------------------------------------------------------------------------- /src/test/java/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/petterobam/sqlite-oop/947ba926a449d3d75b04782e74e38f637e3ad5aa/src/test/java/README.md -------------------------------------------------------------------------------- /src/test/java/my/test/sqlite/SqliteBatchTest.java: -------------------------------------------------------------------------------- 1 | package my.test.sqlite; 2 | 3 | import my.sqlite.utils.SqliteLogUtils; 4 | import my.sqlite.utils.SqliteUtils; 5 | import my.test.sqlite.entity.TestTable; 6 | import my.test.sqlite.service.TestTableService; 7 | import org.junit.Test; 8 | 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | 12 | /** 13 | * Sqlite批量操作测试 14 | * 15 | * @author 欧阳洁 16 | * @since 2018-05-14 16:47 17 | */ 18 | public class SqliteBatchTest { 19 | @Test 20 | public void test() throws ClassNotFoundException { 21 | TestTableService sqliteService = new TestTableService();//没有使用spring注入,暂时自己构建 22 | 23 | sqliteService.delete("delete from t_test_table"); 24 | SqliteLogUtils.info("===数据总条数:{}",sqliteService.count(new TestTable())); 25 | 26 | List batchList = new ArrayList(); 27 | TestTable entity = new TestTable(); 28 | entity.setName("test1"); 29 | entity.setAuthor("petter"); 30 | entity.setArticle("article1"); 31 | entity.setCreateTime(SqliteUtils.getStringDate()); 32 | batchList.add(entity); 33 | 34 | entity = new TestTable(); 35 | entity.setName("test2"); 36 | entity.setAuthor("petter"); 37 | entity.setArticle("article1"); 38 | entity.setCreateTime(SqliteUtils.getStringDate()); 39 | batchList.add(entity); 40 | 41 | entity = new TestTable(); 42 | entity.setName("title4"); 43 | entity.setAuthor("bob"); 44 | entity.setArticle("article2"); 45 | entity.setCreateTime(SqliteUtils.getStringDate()); 46 | batchList.add(entity); 47 | 48 | SqliteLogUtils.info("--开始执行批量插入操作!"); 49 | sqliteService.batchInsert(batchList); 50 | SqliteLogUtils.info("--结束执行批量插入操作!"); 51 | 52 | SqliteLogUtils.info("===数据总条数:{}",sqliteService.count(new TestTable())); 53 | List tableList = sqliteService.query(new TestTable()); 54 | 55 | if(SqliteUtils.isNotEmpty(tableList)){ 56 | tableList.remove(0); 57 | } 58 | 59 | for (TestTable testTable : tableList) { 60 | testTable.setName("Update"); 61 | } 62 | 63 | SqliteLogUtils.info("--开始执行批量修改操作!"); 64 | sqliteService.batchUpdate(tableList); 65 | SqliteLogUtils.info("--结束执行批量修改操作!"); 66 | 67 | SqliteLogUtils.info("===数据总条数:{}",sqliteService.count(new TestTable())); 68 | sqliteService.query(new TestTable()); 69 | 70 | SqliteLogUtils.info("--开始执行批量删除操作!"); 71 | sqliteService.batchDelete(tableList); 72 | SqliteLogUtils.info("--结束执行批量删除操作!"); 73 | 74 | SqliteLogUtils.info("===数据总条数:{}",sqliteService.count(new TestTable())); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/test/java/my/test/sqlite/SqliteCmdTest.java: -------------------------------------------------------------------------------- 1 | package my.test.sqlite; 2 | 3 | import my.sqlite.utils.SqliteHelper; 4 | import my.sqlite.utils.SqliteUtils; 5 | import org.junit.Test; 6 | 7 | public class SqliteCmdTest { 8 | @Test 9 | public void test7(){ 10 | SqliteHelper sqliteHelper = new SqliteHelper("database/test.db",false); 11 | sqliteHelper.queryJsonResult("select * from person"); 12 | sqliteHelper.cmdExec(".dd"); 13 | String result = sqliteHelper.cmdExec(".tables"); 14 | if(!SqliteUtils.isBlank(result)) { 15 | result = result.replaceAll("\r", " "); 16 | result = result.replaceAll("\n", " "); 17 | while (result.indexOf(" ") > 0) { 18 | result = result.replaceAll(" ", " "); 19 | } 20 | String[] arr = result.split(" "); 21 | if(null != arr){ 22 | for (String s : arr) { 23 | System.out.println(s); 24 | } 25 | } 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/test/java/my/test/sqlite/SqliteConnectionPoolTest.java: -------------------------------------------------------------------------------- 1 | package my.test.sqlite; 2 | 3 | import my.sqlite.connection.SqliteConnectionPool; 4 | import my.sqlite.thread.SqliteThreadUtils; 5 | import org.junit.Test; 6 | 7 | import java.sql.SQLException; 8 | 9 | /** 10 | * Sqlite线程连接池测试 11 | * 12 | * @author 欧阳洁 13 | * @since 2018-05-03 18:27 14 | */ 15 | public class SqliteConnectionPoolTest { 16 | @Test 17 | public void test() throws ClassNotFoundException { 18 | // 初始化连接池线程 19 | SqliteConnectionPool.initConnectPoolThreads(); 20 | // 检查连接池线程 21 | SqliteConnectionPool.checkTreadActiveStatus(); 22 | try { 23 | // 取两个连接,观察十秒看线程执行打印日志 24 | SqliteConnectionPool.getConnection(); 25 | SqliteConnectionPool.getConnection(); 26 | SqliteThreadUtils.sleep(10000); 27 | // 取三个连接,观察十秒看线程执行打印日志 28 | SqliteConnectionPool.getConnection(); 29 | SqliteConnectionPool.getConnection(); 30 | SqliteConnectionPool.getConnection(); 31 | SqliteThreadUtils.sleep(10000); 32 | // 关闭所有连接池线程,观察十秒看线程执行打印日志 33 | SqliteConnectionPool.switchPool(false); 34 | SqliteThreadUtils.sleep(10000); 35 | } catch (InterruptedException e) { 36 | e.printStackTrace(); 37 | } catch (SQLException e) { 38 | e.printStackTrace(); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/test/java/my/test/sqlite/SqliteSplitTest.java: -------------------------------------------------------------------------------- 1 | package my.test.sqlite; 2 | 3 | import my.sqlite.utils.SqliteUtils; 4 | import my.test.sqlite.entity.TestSqliteSplit; 5 | import my.test.sqlite.service.TestSqliteSplitService; 6 | import org.junit.Test; 7 | 8 | public class SqliteSplitTest { 9 | @Test 10 | public void test5() { 11 | TestSqliteSplitService sqliteService = new TestSqliteSplitService();//没有使用spring注入,暂时自己构建 12 | TestSqliteSplit entity = new TestSqliteSplit(); 13 | entity.setName("test1"); 14 | entity.setAuthor("petter"); 15 | entity.setArticle("article1"); 16 | entity.setCreateTime(SqliteUtils.getStringDate()); 17 | sqliteService.insert(entity); 18 | entity.setName("title2"); 19 | entity.setAuthor("bob"); 20 | entity.setArticle("article2"); 21 | entity.setCreateTime(SqliteUtils.getStringDate()); 22 | sqliteService.insert(entity); 23 | 24 | TestSqliteSplit queryEntity = new TestSqliteSplit(); 25 | sqliteService.query(queryEntity); 26 | queryEntity.setAuthor("petter"); 27 | sqliteService.query(queryEntity); 28 | queryEntity.setName("test"); 29 | sqliteService.query(queryEntity); 30 | queryEntity.setId(1); 31 | sqliteService.query(queryEntity); 32 | } 33 | 34 | @Test 35 | public void test6() { 36 | TestSqliteSplitService sqliteService = new TestSqliteSplitService();//没有使用spring注入,暂时自己构建 37 | sqliteService.getByName("test"); 38 | sqliteService.getByNameOrId("title", 1); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/test/java/my/test/sqlite/SqliteTableSplitTest.java: -------------------------------------------------------------------------------- 1 | package my.test.sqlite; 2 | 3 | import my.sqlite.utils.SqliteUtils; 4 | import my.test.sqlite.entity.TestTableSplit; 5 | import my.test.sqlite.service.TestTableSplitService; 6 | import org.junit.Test; 7 | 8 | public class SqliteTableSplitTest { 9 | @Test 10 | public void test2() { 11 | TestTableSplitService sqliteService = new TestTableSplitService();//没有使用spring注入,暂时自己构建 12 | TestTableSplit entity = new TestTableSplit(); 13 | entity.setType("t1");//分表字段 14 | 15 | entity.setName("test1-1"); 16 | entity.setAuthor("petter"); 17 | entity.setArticle("article1"); 18 | entity.setCreateTime(SqliteUtils.getStringDate()); 19 | sqliteService.insert(entity); 20 | entity.setName("test1-2"); 21 | entity.setAuthor("bob"); 22 | entity.setArticle("article2"); 23 | entity.setCreateTime(SqliteUtils.getStringDate()); 24 | sqliteService.insert(entity); 25 | 26 | 27 | entity.setType("t2");//分表字段 28 | 29 | entity.setName("test2-1"); 30 | entity.setAuthor("petter"); 31 | entity.setArticle("article1"); 32 | entity.setCreateTime(SqliteUtils.getStringDate()); 33 | sqliteService.insert(entity); 34 | entity.setName("test2-2"); 35 | entity.setAuthor("bob"); 36 | entity.setArticle("article2"); 37 | entity.setCreateTime(SqliteUtils.getStringDate()); 38 | sqliteService.insert(entity); 39 | 40 | TestTableSplit queryEntity = new TestTableSplit(); 41 | sqliteService.query(queryEntity); 42 | queryEntity.setType("t1"); 43 | sqliteService.query(queryEntity); 44 | queryEntity.setType("t2"); 45 | sqliteService.query(queryEntity); 46 | queryEntity.setType("t3"); 47 | sqliteService.query(queryEntity); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/test/java/my/test/sqlite/SqliteTest.java: -------------------------------------------------------------------------------- 1 | package my.test.sqlite; 2 | 3 | import my.sqlite.config.SqliteConfig; 4 | import my.sqlite.constant.SqliteConstant; 5 | import my.sqlite.utils.SqliteUtils; 6 | import my.test.sqlite.entity.TestTable; 7 | import my.test.sqlite.service.TestTableService; 8 | import org.junit.Test; 9 | 10 | import java.sql.Connection; 11 | import java.sql.DriverManager; 12 | import java.sql.PreparedStatement; 13 | import java.sql.ResultSet; 14 | import java.sql.ResultSetMetaData; 15 | import java.sql.SQLException; 16 | import java.sql.Statement; 17 | import java.util.ArrayList; 18 | import java.util.LinkedHashMap; 19 | import java.util.List; 20 | import java.util.Map; 21 | 22 | /** 23 | * sqlite测试 24 | * 25 | * @author 欧阳洁 26 | * @create 2017-09-29 18:10 27 | **/ 28 | public class SqliteTest { 29 | @Test 30 | public void test() throws ClassNotFoundException { 31 | System.out.println(SqliteConfig.getUri()); 32 | } 33 | @Test 34 | public void test1() throws ClassNotFoundException { 35 | Connection connection = null; 36 | try { 37 | String TEST_DB_PATH = SqliteUtils.getClassRootPath(SqliteConstant.TEST_DB_PATH); 38 | // create a database connection 39 | String JDBC = "jdbc:sqlite:/" + TEST_DB_PATH; 40 | if (SqliteUtils.isWindows()) { 41 | TEST_DB_PATH = TEST_DB_PATH.toLowerCase(); 42 | JDBC = "jdbc:sqlite:/" + TEST_DB_PATH; 43 | } 44 | connection = DriverManager.getConnection(JDBC); 45 | Statement statement = connection.createStatement(); 46 | statement.setQueryTimeout(30); // set timeout to 30 sec. 47 | statement.executeUpdate("create table if not exists person (id integer, name string)"); 48 | statement.executeUpdate("insert into person values(1, 'leo')"); 49 | statement.executeUpdate("insert into person values(2, 'yui')"); 50 | ResultSet rs = statement.executeQuery("select * from person"); 51 | ResultSetMetaData rsmd = rs.getMetaData(); 52 | int count = rsmd.getColumnCount(); 53 | String[] name = new String[count]; 54 | for (int i = 0; i < count; i++) { 55 | name[i] = rsmd.getColumnName(i + 1); 56 | } 57 | List> result = new ArrayList>(); 58 | 59 | while (rs.next()) { 60 | Map one = new LinkedHashMap(); 61 | 62 | for (int i = 0; i < name.length; i++) { 63 | Object value = rs.getObject(i + 1); 64 | System.out.println(name[i] + ":" + value); 65 | one.put(name[i], value); 66 | } 67 | result.add(one); 68 | } 69 | String dataRes = SqliteUtils.getJson(result); 70 | System.out.println(dataRes); 71 | 72 | PreparedStatement prep = connection.prepareStatement( 73 | "insert into person values (?, ?)"); 74 | prep.setObject(1, 5); 75 | prep.setObject(2, "asdfasdfas"); 76 | prep.execute(); 77 | prep = connection.prepareStatement( 78 | "select * from person where id=?"); 79 | prep.setObject(1, 5); 80 | rs = prep.executeQuery(); 81 | while (rs.next()) { 82 | System.out.println("id = " + rs.getString("id")); 83 | System.out.println("name = " + rs.getString("name")); 84 | } 85 | } catch (SQLException e) { 86 | e.printStackTrace(); 87 | } finally { 88 | try { 89 | if (connection != null) connection.close(); 90 | } catch (SQLException e) { 91 | e.printStackTrace(); 92 | } 93 | } 94 | } 95 | 96 | @Test 97 | public void test2() { 98 | TestTableService sqliteService = new TestTableService();//没有使用spring注入,暂时自己构建 99 | TestTable entity = new TestTable(); 100 | entity.setName("test1"); 101 | entity.setAuthor("petter"); 102 | entity.setArticle("article1"); 103 | entity.setCreateTime(SqliteUtils.getStringDate()); 104 | sqliteService.insert(entity); 105 | entity.setName("title2"); 106 | entity.setAuthor("bob"); 107 | entity.setArticle("article2"); 108 | entity.setCreateTime(SqliteUtils.getStringDate()); 109 | sqliteService.insert(entity); 110 | 111 | TestTable queryEntity = new TestTable(); 112 | sqliteService.query(queryEntity); 113 | queryEntity.setAuthor("petter"); 114 | sqliteService.query(queryEntity); 115 | queryEntity.setName("test"); 116 | sqliteService.query(queryEntity); 117 | queryEntity.setId(1); 118 | sqliteService.query(queryEntity); 119 | } 120 | 121 | @Test 122 | public void test3() { 123 | TestTableService sqliteService = new TestTableService();//没有使用spring注入,暂时自己构建 124 | List list = sqliteService.getByName("test"); 125 | } 126 | 127 | @Test 128 | public void test4() { 129 | TestTableService sqliteService = new TestTableService();//没有使用spring注入,暂时自己构建 130 | List list = sqliteService.getByNameOrId("title", 1); 131 | } 132 | 133 | @Test 134 | public void test8(){ 135 | TestTableService sqliteService = new TestTableService();//没有使用spring注入,暂时自己构建 136 | int count1 = sqliteService.count("select count(1) from t_test_table"); 137 | System.out.println(count1); 138 | TestTable query = new TestTable(); 139 | //query.setName("petter"); 140 | int count = sqliteService.count(query); 141 | System.out.println(count); 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /src/test/java/my/test/sqlite/dao/TestSqliteSplitDao.java: -------------------------------------------------------------------------------- 1 | package my.test.sqlite.dao; 2 | 3 | import my.sqlite.annotation.SqliteSql; 4 | import my.sqlite.base.SqliteBaseDao; 5 | import my.test.sqlite.entity.TestSqliteSplit; 6 | 7 | import java.util.List; 8 | 9 | /** 10 | * Sqlite[test_table]的dao 11 | * 12 | * @author 欧阳洁 13 | * @create 2017-09-29 17:17 14 | **/ 15 | public class TestSqliteSplitDao extends SqliteBaseDao { 16 | /** 17 | * 构造函数 18 | */ 19 | public TestSqliteSplitDao() {// 必须要对应实现父类的构造方法 20 | super(TestSqliteSplit.class);// 表实体对应类 21 | } 22 | 23 | /** 24 | * 根据名称模糊查找数据 25 | * 26 | * @param entity 27 | * @return 28 | */ 29 | @SqliteSql(sql = "select t.create_time publish_time,t.* from this.tableName t where name like '%'||?||'%'", params = {"name"}) 30 | public List getByName(TestSqliteSplit entity) { 31 | //List super.excuteQuery(T entity),通过params上的参数顺序在entity中获取,并依次填充占位符 32 | return super.excuteQuery(entity); 33 | } 34 | 35 | /** 36 | * 根据名称模糊查找数据并包含id查找 37 | * 38 | * @param name 39 | * @param id 40 | * @return 41 | */ 42 | @SqliteSql(sql = "select * from this.tableName where name like '%'||?||'%' or id=?") 43 | public List getByNameOrId(String name, Integer id) { 44 | //List super.excuteQuery(Object... params),这里的参数顺序对应自定义的SQL的占位符顺序 45 | return super.excuteQuery(name, id); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/test/java/my/test/sqlite/dao/TestTableDao.java: -------------------------------------------------------------------------------- 1 | package my.test.sqlite.dao; 2 | 3 | import my.sqlite.annotation.SqliteSql; 4 | import my.sqlite.base.SqliteBaseDao; 5 | import my.test.sqlite.entity.TestTable; 6 | 7 | import java.util.List; 8 | 9 | /** 10 | * Sqlite[test_table]的dao 11 | * 12 | * @author 欧阳洁 13 | * @create 2017-09-29 17:17 14 | **/ 15 | public class TestTableDao extends SqliteBaseDao { 16 | /** 17 | * 构造函数 18 | */ 19 | public TestTableDao() {// 必须要对应实现父类的构造方法 20 | super(TestTable.class);// 表实体对应类 21 | } 22 | 23 | /** 24 | * 根据名称模糊查找数据 25 | * 26 | * @param entity 27 | * @return 28 | */ 29 | @SqliteSql(sql = "select t.create_time publish_time,t.* from this.tableName t where name like '%'||?||'%'", params = {"name"}) 30 | public List getByName(TestTable entity) { 31 | //List super.excuteQuery(T entity),通过params上的参数顺序在entity中获取,并依次填充占位符 32 | return super.excuteQuery(entity); 33 | } 34 | 35 | /** 36 | * 根据名称模糊查找数据并包含id查找 37 | * 38 | * @param name 39 | * @param id 40 | * @return 41 | */ 42 | @SqliteSql(sql = "select * from this.tableName where name like '%'||?||'%' or id=?") 43 | public List getByNameOrId(String name, Integer id) { 44 | //List super.excuteQuery(Object... params),这里的参数顺序对应自定义的SQL的占位符顺序 45 | return super.excuteQuery(name, id); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/test/java/my/test/sqlite/dao/TestTableSplitDao.java: -------------------------------------------------------------------------------- 1 | package my.test.sqlite.dao; 2 | 3 | 4 | import my.sqlite.base.SqliteBaseDao; 5 | import my.test.sqlite.entity.TestTableSplit; 6 | 7 | /** 8 | * Sqlite[test_table]的dao 9 | * 10 | * @author 欧阳洁 11 | * @create 2017-09-29 17:17 12 | **/ 13 | public class TestTableSplitDao extends SqliteBaseDao { 14 | /** 15 | * 构造函数 16 | */ 17 | public TestTableSplitDao() {// 必须要对应实现父类的构造方法 18 | super(TestTableSplit.class);// 表实体对应类 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/test/java/my/test/sqlite/entity/TestSqliteSplit.java: -------------------------------------------------------------------------------- 1 | package my.test.sqlite.entity; 2 | 3 | import my.sqlite.base.SqliteBaseEntity; 4 | import my.sqlite.annotation.SqliteColumn; 5 | import my.sqlite.annotation.SqliteID; 6 | import my.sqlite.annotation.SqliteTable; 7 | import my.sqlite.annotation.SqliteTransient; 8 | import my.sqlite.constant.SqliteConstant; 9 | 10 | /** 11 | * 测试分库表对应实体类 12 | * 13 | * @author 欧阳洁 14 | * @create 2017-09-30 9:44 15 | **/ 16 | @SqliteTable(name = "t_test_splite_sqlite",dbPath = "database/t_test_splite_",dbType = SqliteConstant.DB_TYPE_BY_DAY) 17 | public class TestSqliteSplit extends SqliteBaseEntity { 18 | /** 19 | * 主键 20 | */ 21 | @SqliteID 22 | private Integer id; 23 | /** 24 | * 名称 25 | */ 26 | @SqliteColumn(type = "char(100)", notNull = true) 27 | private String name; 28 | /** 29 | * 作者 30 | */ 31 | @SqliteColumn(notNull = true) 32 | private String author; 33 | /** 34 | * 正文 35 | */ 36 | @SqliteColumn(type = "text") 37 | private String article; 38 | /** 39 | * 创建时间 40 | */ 41 | @SqliteColumn(name = "create_time",type = "char(20)", notNull = true) 42 | private String createTime; 43 | /** 44 | * 查询类型 (非表字段) 45 | */ 46 | @SqliteTransient 47 | private String searchType; 48 | /** 49 | * 发布时间 (非表字段) 50 | * 注:这里不使用SqliteColumn主键,默认的列名为publishtime 51 | */ 52 | @SqliteTransient 53 | @SqliteColumn(name = "publish_time") 54 | private String publishTime; 55 | 56 | public Integer getId() { 57 | return id; 58 | } 59 | 60 | public void setId(Integer id) { 61 | this.id = id; 62 | } 63 | 64 | public String getName() { 65 | return name; 66 | } 67 | 68 | public void setName(String name) { 69 | this.name = name; 70 | } 71 | 72 | public String getArticle() { 73 | return article; 74 | } 75 | 76 | public void setArticle(String article) { 77 | this.article = article; 78 | } 79 | 80 | public String getAuthor() { 81 | return author; 82 | } 83 | 84 | public void setAuthor(String author) { 85 | this.author = author; 86 | } 87 | 88 | public String getCreateTime() { 89 | return createTime; 90 | } 91 | 92 | public void setCreateTime(String createTime) { 93 | this.createTime = createTime; 94 | } 95 | 96 | public String getSearchType() { 97 | return searchType; 98 | } 99 | 100 | public void setSearchType(String searchType) { 101 | this.searchType = searchType; 102 | } 103 | 104 | public String getPublishTime() { 105 | return publishTime; 106 | } 107 | 108 | public void setPublishTime(String publishTime) { 109 | this.publishTime = publishTime; 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /src/test/java/my/test/sqlite/entity/TestTable.java: -------------------------------------------------------------------------------- 1 | package my.test.sqlite.entity; 2 | 3 | import my.sqlite.annotation.SqliteColumn; 4 | import my.sqlite.annotation.SqliteID; 5 | import my.sqlite.annotation.SqliteTable; 6 | import my.sqlite.annotation.SqliteTransient; 7 | import my.sqlite.base.SqliteBaseEntity; 8 | 9 | /** 10 | * 测试表对应实体类 11 | * 12 | * @author 欧阳洁 13 | * @create 2017-09-30 9:44 14 | **/ 15 | @SqliteTable(name = "t_test_table") 16 | public class TestTable extends SqliteBaseEntity { 17 | /** 18 | * 主键 19 | */ 20 | @SqliteID 21 | private Integer id; 22 | /** 23 | * 名称 24 | */ 25 | @SqliteColumn(type = "char(100)", notNull = true) 26 | private String name; 27 | /** 28 | * 作者 29 | */ 30 | @SqliteColumn(notNull = true) 31 | private String author; 32 | /** 33 | * 正文 34 | */ 35 | @SqliteColumn(type = "text") 36 | private String article; 37 | /** 38 | * 创建时间 39 | */ 40 | @SqliteColumn(name = "create_time",type = "char(20)", notNull = true) 41 | private String createTime; 42 | /** 43 | * 查询类型 (非表字段) 44 | */ 45 | @SqliteTransient 46 | private String searchType; 47 | /** 48 | * 发布时间 (非表字段) 49 | * 注:这里不使用SqliteColumn主键,默认的列名为publishtime 50 | */ 51 | @SqliteTransient 52 | @SqliteColumn(name = "publish_time") 53 | private String publishTime; 54 | 55 | public Integer getId() { 56 | return id; 57 | } 58 | 59 | public void setId(Integer id) { 60 | this.id = id; 61 | } 62 | 63 | public String getName() { 64 | return name; 65 | } 66 | 67 | public void setName(String name) { 68 | this.name = name; 69 | } 70 | 71 | public String getArticle() { 72 | return article; 73 | } 74 | 75 | public void setArticle(String article) { 76 | this.article = article; 77 | } 78 | 79 | public String getAuthor() { 80 | return author; 81 | } 82 | 83 | public void setAuthor(String author) { 84 | this.author = author; 85 | } 86 | 87 | public String getCreateTime() { 88 | return createTime; 89 | } 90 | 91 | public void setCreateTime(String createTime) { 92 | this.createTime = createTime; 93 | } 94 | 95 | public String getSearchType() { 96 | return searchType; 97 | } 98 | 99 | public void setSearchType(String searchType) { 100 | this.searchType = searchType; 101 | } 102 | 103 | public String getPublishTime() { 104 | return publishTime; 105 | } 106 | 107 | public void setPublishTime(String publishTime) { 108 | this.publishTime = publishTime; 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /src/test/java/my/test/sqlite/entity/TestTableSplit.java: -------------------------------------------------------------------------------- 1 | package my.test.sqlite.entity; 2 | 3 | 4 | import my.sqlite.annotation.SqliteColumn; 5 | import my.sqlite.annotation.SqliteID; 6 | import my.sqlite.annotation.SqliteTable; 7 | import my.sqlite.annotation.SqliteTableSplit; 8 | import my.sqlite.annotation.SqliteTransient; 9 | import my.sqlite.base.SqliteBaseEntity; 10 | 11 | /** 12 | * 测试分表对应实体类 13 | * 14 | * @author 欧阳洁 15 | * @create 2017-09-30 9:44 16 | **/ 17 | @SqliteTable(name = "t_test_split_table") 18 | public class TestTableSplit extends SqliteBaseEntity { 19 | /** 20 | * 主键 21 | */ 22 | @SqliteID 23 | private Integer id; 24 | /** 25 | * 类型,分表字段 26 | */ 27 | @SqliteColumn(notNull = true) 28 | @SqliteTableSplit 29 | private String type; 30 | /** 31 | * 名称 32 | */ 33 | @SqliteColumn(type = "char(100)", notNull = true) 34 | private String name; 35 | /** 36 | * 作者 37 | */ 38 | @SqliteColumn(notNull = true) 39 | private String author; 40 | /** 41 | * 正文 42 | */ 43 | @SqliteColumn(type = "text") 44 | private String article; 45 | /** 46 | * 创建时间 47 | */ 48 | @SqliteColumn(name = "create_time",type = "char(20)", notNull = true) 49 | private String createTime; 50 | /** 51 | * 查询类型 (非表字段) 52 | */ 53 | @SqliteTransient 54 | private String searchType; 55 | /** 56 | * 发布时间 (非表字段) 57 | * 注:这里不使用SqliteColumn主键,默认的列名为publishtime 58 | */ 59 | @SqliteTransient 60 | @SqliteColumn(name = "publish_time") 61 | private String publishTime; 62 | 63 | public Integer getId() { 64 | return id; 65 | } 66 | 67 | public void setId(Integer id) { 68 | this.id = id; 69 | } 70 | 71 | public String getType() { 72 | return type; 73 | } 74 | 75 | public void setType(String type) { 76 | this.type = type; 77 | } 78 | 79 | public String getName() { 80 | return name; 81 | } 82 | 83 | public void setName(String name) { 84 | this.name = name; 85 | } 86 | 87 | public String getArticle() { 88 | return article; 89 | } 90 | 91 | public void setArticle(String article) { 92 | this.article = article; 93 | } 94 | 95 | public String getAuthor() { 96 | return author; 97 | } 98 | 99 | public void setAuthor(String author) { 100 | this.author = author; 101 | } 102 | 103 | public String getCreateTime() { 104 | return createTime; 105 | } 106 | 107 | public void setCreateTime(String createTime) { 108 | this.createTime = createTime; 109 | } 110 | 111 | public String getSearchType() { 112 | return searchType; 113 | } 114 | 115 | public void setSearchType(String searchType) { 116 | this.searchType = searchType; 117 | } 118 | 119 | public String getPublishTime() { 120 | return publishTime; 121 | } 122 | 123 | public void setPublishTime(String publishTime) { 124 | this.publishTime = publishTime; 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /src/test/java/my/test/sqlite/service/TestSqliteSplitService.java: -------------------------------------------------------------------------------- 1 | package my.test.sqlite.service; 2 | 3 | import my.sqlite.base.SqliteBaseService; 4 | import my.test.sqlite.entity.TestSqliteSplit; 5 | import my.test.sqlite.dao.TestSqliteSplitDao; 6 | 7 | import java.util.List; 8 | 9 | /** 10 | * Sqlite[test_table]的service 11 | * 12 | * @author 欧阳洁 13 | * @create 2017-09-30 15:16 14 | **/ 15 | public class TestSqliteSplitService extends SqliteBaseService { 16 | public TestSqliteSplitService() {// 必须要对应实现父类的构造方法 17 | super(TestSqliteSplitDao.class);// 对应的Dao类 18 | } 19 | 20 | public List getByName(String name) { 21 | TestSqliteSplit entity = new TestSqliteSplit(); 22 | entity.setName(name); 23 | return this.getBaseDao().getByName(entity); 24 | } 25 | 26 | public List getByNameOrId(String name, Integer id) { 27 | return this.getBaseDao().getByNameOrId(name, id); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/test/java/my/test/sqlite/service/TestTableService.java: -------------------------------------------------------------------------------- 1 | package my.test.sqlite.service; 2 | 3 | import my.sqlite.base.SqliteBaseService; 4 | import my.test.sqlite.dao.TestTableDao; 5 | import my.test.sqlite.entity.TestTable; 6 | 7 | import java.util.List; 8 | 9 | /** 10 | * Sqlite[test_table]的service 11 | * 12 | * @author 欧阳洁 13 | * @create 2017-09-30 15:16 14 | **/ 15 | public class TestTableService extends SqliteBaseService { 16 | public TestTableService() {// 必须要对应实现父类的构造方法 17 | super(TestTableDao.class);// 对应的Dao类 18 | } 19 | 20 | public List getByName(String name) { 21 | TestTable entity = new TestTable(); 22 | entity.setName(name); 23 | return this.getBaseDao().getByName(entity); 24 | } 25 | 26 | public List getByNameOrId(String name, Integer id) { 27 | return this.getBaseDao().getByNameOrId(name, id); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/test/java/my/test/sqlite/service/TestTableSplitService.java: -------------------------------------------------------------------------------- 1 | package my.test.sqlite.service; 2 | 3 | 4 | import my.sqlite.base.SqliteBaseService; 5 | import my.test.sqlite.entity.TestTableSplit; 6 | import my.test.sqlite.dao.TestTableSplitDao; 7 | 8 | /** 9 | * Sqlite[test_table]的service 10 | * 11 | * @author 欧阳洁 12 | * @create 2017-09-30 15:16 13 | **/ 14 | public class TestTableSplitService extends SqliteBaseService { 15 | public TestTableSplitService() {// 必须要对应实现父类的构造方法 16 | super(TestTableSplitDao.class);// 对应的Dao类 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/test/resources/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/petterobam/sqlite-oop/947ba926a449d3d75b04782e74e38f637e3ad5aa/src/test/resources/README.md -------------------------------------------------------------------------------- /src/test/resources/database/test.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/petterobam/sqlite-oop/947ba926a449d3d75b04782e74e38f637e3ad5aa/src/test/resources/database/test.db --------------------------------------------------------------------------------