SpringBoot + Druid + Sqlite 文件数据库初体验

打印 上一主题 下一主题

主题 859|帖子 859|积分 2577

一次以外的机遇接触到了SQLite这样一个轻量型的嵌入式数据库组件,对于日常使用的大概都是传统RDBMS,大概当下更为流行NoSQL和大数据存储。
对于这样一个自包含的,无服务器的,零配置的,事务性的 SQL 数据库引擎,主要是面向嵌入式大概终端类的使用场景,大概是说开箱即用、小型项目的场景。


  • 关于SQLite - 天下上装机量最多的数据库?

    • 关于Druid
    • 关于SpringBoot
    • 整合并查询

      • 创建DB文件
      • 初始化一个SpringBoot步伐
      • 导入Maven依赖
      • 配置服务毗连参数
      • 书写一个JPA步伐完成一次查询


关于SQLite - 天下上装机量最多的数据库?



  • 使用C语言开发,使得它小巧风雅而高效,·直接采用偏底层的语言,使用文件的逻辑,实现SQL数据库的逻辑;
  • 使用方:包罗但不限于 Python、Java、C# 等;
  • 无服务器的,零配置的,真的轻量;
  • 遵守ACID的关系型数据库管理体系,让了解Mysql等数据库的人极易上手;
  • SQLite 是一个自包含的步伐如果你使用的是 Linux 大概 MacOS,那么 SQLite 很大概已经预装了,真的开箱即用;
  1. :~$ sqlite3
  2. SQLite version 3.28.0 2019-04-15 14:49:49
  3. Enter ".help" for usage hints.
  4. Connected to a transient in-memory database.
  5. Use ".open FILENAME" to reopen on a persistent database.
  6. sqlite>
复制代码
它固然支持了增删改查以及事务等特性,但是它为什么是在嵌入式方向使用,而不是大范围使用呢,主要照旧不面向复杂的处置处罚逻辑、大数量的存储与查询,所以照旧要将对的东西用在对的方面。
关于Druid

Alibaba/Druid 想必各人肯定不陌生,一个国内使用率比力高的一个数据库毗连池,其他的还有:HikariCP, tomcat-jdbc, c3p0, dbcp,用的人多也就迭代和丰富了很多功能。
定位为:为监控而生的数据库毗连池,接入了一个高性能的数据库毗连池,还送了一套数据库利用的监控,肯定会让民气动。
它也黑白常自大的与其他数据库毗连池做了比对。
支持的数据库种类繁多,可以适配国内数据库。
关于SpringBoot

这个不用多说,Java开发者应该无人不知无人不晓。
整合并查询

创建DB文件

首先登录检察利用指南,必要记住命令都是"."开头,.help展示帮助指令,.open filename创建一个数据库, .quit 退出命令行
  1. :~$ sqlite3
  2. SQLite version 3.28.0 2019-04-15 14:49:49
  3. Enter ".help" for usage hints.
  4. Connected to a transient in-memory database.
  5. Use ".open FILENAME" to reopen on a persistent database.
  6. sqlite>
  7. .help.auth ON|OFF             Show authorizer callbacks.backup ?DB? FILE        Backup DB (default "main") to FILE.bail on|off             Stop after hitting an error.  Default OFF.binary on|off           Turn binary output on or off.  Default OFF.cd DIRECTORY            Change the working directory to DIRECTORY.changes on|off          Show number of rows changed by SQL.check GLOB              Fail if output since .testcase does not match.clone NEWDB             Clone data into NEWDB from the existing database.databases               List names and files of attached databases.dbconfig ?op? ?val?     List or change sqlite3_db_config() options.dbinfo ?DB?             Show status information about the database.dump ?TABLE? ...        Render all database content as SQL.echo on|off             Turn command echo on or off.eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN.excel                   Display the output of next command in a spreadsheet.exit ?CODE?             Exit this program with return-code CODE.expert                  EXPERIMENTAL. Suggest indexes for specified queries.fullschema ?--indent?   Show schema and the content of sqlite_stat tables.headers on|off          Turn display of headers on or off.help ?-all? ?PATTERN?   Show help text for PATTERN.import FILE TABLE       Import data from FILE into TABLE.imposter INDEX TABLE    Create imposter table TABLE on index INDEX.indexes ?TABLE?         Show names of indexes.limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT.lint OPTIONS            Report potential schema issues..log FILE|off            Turn logging on or off.  FILE can be stderr/stdout.mode MODE ?TABLE?       Set output mode.nullvalue STRING        Use STRING in place of NULL values.once (-e|-x|FILE)       Output for the next SQL command only to FILE.open ?OPTIONS? ?FILE?   Close existing database and reopen FILE.output ?FILE?           Send output to FILE or stdout if FILE is omitted.parameter CMD ...       Manage SQL parameter bindings.print STRING...         Print literal STRING.progress N              Invoke progress handler after every N opcodes.prompt MAIN CONTINUE    Replace the standard prompts.quit                    Exit this program.read FILE               Read input from FILE.restore ?DB? FILE       Restore content of DB (default "main") from FILE.save FILE               Write in-memory database into FILE.scanstats on|off        Turn sqlite3_stmt_scanstatus() metrics on or off.schema ?PATTERN?        Show the CREATE statements matching PATTERN.selftest ?OPTIONS?      Run tests defined in the SELFTEST table.separator COL ?ROW?     Change the column and row separators.session ?NAME? CMD ...  Create or control sessions.sha3sum ...             Compute a SHA3 hash of database content.shell CMD ARGS...       Run CMD ARGS... in a system shell.show                    Show the current values for various settings.stats ?on|off?          Show stats or turn stats on or off.system CMD ARGS...      Run CMD ARGS... in a system shell.tables ?TABLE?          List names of tables matching LIKE pattern TABLE.testcase NAME           Begin redirecting output to 'testcase-out.txt'.timeout MS              Try opening locked tables for MS milliseconds.timer on|off            Turn SQL timer on or off.trace ?OPTIONS?         Output each SQL statement as it is run.vfsinfo ?AUX?           Information about the top-level VFS.vfslist                 List all available VFSes.vfsname ?AUX?           Print the name of the VFS stack.width NUM1 NUM2 ...     Set column widths for "column" modesqlite>
复制代码
创建一个mydb
  1. sqlite> .open mydb
  2. sqlite> .databases
  3. main: /Users/xxx/mydb
复制代码
非常简朴地创建了一个DB文件
初始化一个SpringBoot步伐

使用start.spring.io 大概其他的初始化方式,建立一个简朴的SpringBoot项目。
导入Maven依赖

maven里面主要必要,springboot-jpa、druid、sqlite-jdbc、sqlite-dialect(RDBMS 方言)。


  • springboot-jpa: 这个如果使用mybatis/mybatis-plus等ORM框架,都是可以的;
  • druid: 这边使用druid-spring-boot-starter,主要为了便捷,单用druid自己手动去配置也是可以的;
  • sqlite-jdbc:sqlite对于毗连的实现,必须;
  • sqlite-dialect:是团结JPA所需的,对于Hibernate的方言,这边采用maven库中2023年更新的依赖包;
以上的配置,最关键的就是版本的依赖关系,Hibernete5?Hibernete6 + SpringBoot。
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3.          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4.     <modelVersion>4.0.0</modelVersion>
  5.     <groupId>com.example</groupId>
  6.     <artifactId>sqlitedemo</artifactId>
  7.     <version>0.0.1-SNAPSHOT</version>
  8.     <name>sqlitedemo</name>
  9.     <description>sqlitedemo</description>
  10.     <properties>
  11.         <java.version>17</java.version>
  12.         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  13.         <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  14.         <spring-boot.version>2.6.13</spring-boot.version>
  15.     </properties>
  16.     <dependencies>
  17.         <dependency>
  18.             <groupId>org.springframework.boot</groupId>
  19.             <artifactId>spring-boot-starter</artifactId>
  20.         </dependency>
  21.         <dependency>
  22.             <groupId>org.springframework.boot</groupId>
  23.             <artifactId>spring-boot-starter-web</artifactId>
  24.         </dependency>
  25.         <dependency>
  26.             <groupId>org.springframework.boot</groupId>
  27.             <artifactId>spring-boot-starter-test</artifactId>
  28.             <scope>test</scope>
  29.         </dependency>
  30.         <dependency>
  31.             <groupId>org.springframework.boot</groupId>
  32.             <artifactId>spring-boot-starter-log4j2</artifactId>
  33.         </dependency>
  34.         <dependency>
  35.             <groupId>org.projectlombok</groupId>
  36.             <artifactId>lombok</artifactId>
  37.             <version>1.18.20</version>
  38.         </dependency>
  39.         <dependency>
  40.             <groupId>org.xerial</groupId>
  41.             <artifactId>sqlite-jdbc</artifactId>
  42.             <version>3.42.0.0</version>
  43.         </dependency>
  44.         <dependency>
  45.             <groupId>org.springframework.boot</groupId>
  46.             <artifactId>spring-boot-starter-data-jpa</artifactId>
  47.         </dependency>
  48.         <dependency>
  49.             <groupId>com.alibaba</groupId>
  50.             <artifactId>druid-spring-boot-starter</artifactId>
  51.             <version>1.2.19</version>
  52.         </dependency>
  53.         <dependency>
  54.             <groupId>com.github.gwenn</groupId>
  55.             <artifactId>sqlite-dialect</artifactId>
  56.             <version>0.1.4</version>
  57.         </dependency>
  58. <!--        <dependency>-->
  59. <!--            <groupId>com.zsoltfabok</groupId>-->
  60. <!--            <artifactId>sqlite-dialect</artifactId>-->
  61. <!--            <version>1.0</version>-->
  62. <!--        </dependency>-->
  63.     </dependencies>
  64.     <dependencyManagement>
  65.         <dependencies>
  66.             <dependency>
  67.                 <groupId>org.springframework.boot</groupId>
  68.                 <artifactId>spring-boot-dependencies</artifactId>
  69.                 <version>${spring-boot.version}</version>
  70.                 <type>pom</type>
  71.                 <scope>import</scope>
  72.             </dependency>
  73.         </dependencies>
  74.     </dependencyManagement>
  75.     <build>
  76.         <plugins>
  77.             <plugin>
  78.                 <groupId>org.apache.maven.plugins</groupId>
  79.                 <artifactId>maven-compiler-plugin</artifactId>
  80.                 <version>3.8.1</version>
  81.                 <configuration>
  82.                     <source>17</source>
  83.                     <target>17</target>
  84.                     <encoding>UTF-8</encoding>
  85.                 </configuration>
  86.             </plugin>
  87.             <plugin>
  88.                 <groupId>org.springframework.boot</groupId>
  89.                 <artifactId>spring-boot-maven-plugin</artifactId>
  90.                 <version>${spring-boot.version}</version>
  91.                 <configuration>
  92.                     <mainClass>com.example.sqlitedemo.SqlitedemoApplication</mainClass>
  93.                     <skip>true</skip>
  94.                 </configuration>
  95.                 <executions>
  96.                     <execution>
  97.                         <id>repackage</id>
  98.                         <goals>
  99.                             <goal>repackage</goal>
  100.                         </goals>
  101.                     </execution>
  102.                 </executions>
  103.             </plugin>
  104.         </plugins>
  105.     </build>
  106. </project>
复制代码
配置服务毗连参数

application.properties
  1. server.port=8080
  2. spring.application.name=sqlite-test
  3. spring.datasource.druid.url=jdbc:sqlite::resource:db/sqlite.db
  4. spring.datasource.druid.username=
  5. spring.datasource.druid.password=
  6. spring.datasource.druid.driver-class-name=org.sqlite.JDBC
  7. spring.datasource.druid.initial-size=5
  8. spring.datasource.druid.min-idle=5
  9. spring.datasource.druid.max-active=20
  10. spring.datasource.druid.max-wait=60000
  11. spring.datasource.druid.pool-prepared-statements=false
  12. spring.datasource.druid.max-pool-prepared-statement-per-connection-size=-1
  13. spring.datasource.druid.validation-query=SELECT '1' from sqlite_master
  14. spring.datasource.druid.validation-query-timeout=3
  15. spring.datasource.druid.test-on-borrow=true
  16. spring.datasource.druid.test-on-return=false
  17. spring.datasource.druid.test-while-idle=true
  18. spring.datasource.druid.time-between-eviction-runs-millis=60000
  19. spring.datasource.druid.min-evictable-idle-time-millis=300000
  20. spring.datasource.druid.filters= stat
  21. # WebStatFilter
  22. spring.datasource.druid.web-stat-filter.enabled=false
  23. spring.datasource.druid.web-stat-filter.url-pattern=/*
  24. spring.datasource.druid.web-stat-filter.exclusions=*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*
  25. spring.datasource.druid.web-stat-filter.session-stat-enable=true
  26. spring.datasource.druid.web-stat-filter.session-stat-max-count=1000
  27. spring.datasource.druid.web-stat-filter.principal-session-name=
  28. spring.datasource.druid.web-stat-filter.principal-cookie-name=
  29. spring.datasource.druid.web-stat-filter.profile-enable=
  30. # StatViewServlet
  31. spring.datasource.druid.stat-view-servlet.enabled=false
  32. spring.datasource.druid.stat-view-servlet.url-pattern=/druid/*
  33. spring.datasource.druid.stat-view-servlet.reset-enable=false
  34. spring.datasource.druid.stat-view-servlet.login-username=admin
  35. spring.datasource.druid.stat-view-servlet.login-password=123456
  36. spring.datasource.druid.stat-view-servlet.allow=
  37. spring.datasource.druid.stat-view-servlet.deny=
  38. # Spring
  39. spring.datasource.druid.aop-patterns= com.*.service.*
  40. # Dialect(com.github.gwenn.sqlite-dialect)
  41. spring.jpa.database-platform=org.sqlite.hibernate.dialect.SQLiteDialect
  42. spring.jpa.show-sql=true
  43. spring.jpa.hibernate.ddl-auto=none
  44. spring.jpa.hibernate.naming.strategy=org.hibernate.cfg.ImprovedNamingStrategy
  45. spring.jpa.properties.hibernate.dialect=org.sqlite.hibernate.dialect.SQLiteDialect
  46. spring.jpa.properties.hibernate.event.merge.entity_copy_observer=allow
  47. spring.aop.proxy-target-class=true
复制代码
注意这里配置的DB的所在,与你刚才新建的DB所在要一致。
书写一个JPA步伐完成一次查询



  • 通过命令行创建一个table
  1. sqlite> CREATE TABLE user
  2.    ...> (
  3.    ...>   id    VARCHAR(8),
  4.    ...>   name    VARCHAR(30)
  5.    ...> );
  6. sqlite>
复制代码


  • 界说domain
  1. @Entity
  2. @Table(name = "user", schema = "main", catalog = "")
  3. public class User {
  4.     private String id;
  5.     private String name;
  6.     private String age;
  7.     @Id
  8.     @Column(name = "id", nullable = true, length = 8)
  9.     public String getId() {
  10.         return id;
  11.     }
  12.     public void setId(String id) {
  13.         this.id = id;
  14.     }
  15.     @Basic
  16.     @Column(name = "name", nullable = true, length = 30)
  17.     public String getName() {
  18.         return stationId;
  19.     }
  20.     public void setName(String name) {
  21.         this.name = name;
  22.     }
  23. }
复制代码


  • 界说service
  1. public interface UserService {
  2.     List<User> findList();
  3. }
  4. @Service
  5. public class UserServiceImpl implements UserService {
  6.     @Autowired
  7.     private UserRepo userRepo;
  8.     @Override
  9.     public List<User> findList() {
  10.         return userRepo.findAllByNameNotNull();
  11.     }
  12. }
复制代码


  • 界说dao
  1. public interface UserRepo extends JpaRepository<User,String> {
  2.     List<User> findAllByNameNotNull();
  3. }
复制代码


  • 测试
启动服务,书写接口测试
  1.   .   ____          _            __ _ _
  2. /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
  3. ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
  4. \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  5.   '  |____| .__|_| |_|_| |_\__, | / / / /
  6. =========|_|==============|___/=/_/_/_/
  7. :: Spring Boot ::               (v2.6.13)
  8. 2024-05-10 10:29:41.354  INFO 49697 --- [           main] c.e.sqlitedemo.SqlitedemoApplication     : Starting SqlitedemoApplication using Java 17.0.8
  9. 2024-05-10 10:29:41.357  INFO 49697 --- [           main] c.e.sqlitedemo.SqlitedemoApplication     : No active profile set, falling back to 1 default profile: "default"
  10. 2024-05-10 10:29:42.630  INFO 49697 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
  11. 2024-05-10 10:29:42.736  INFO 49697 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 81 ms. Found 1 JPA repository interfaces.
  12. 2024-05-10 10:29:43.141  INFO 49697 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'com.alibaba.druid.spring.boot.autoconfigure.stat.DruidSpringAopConfiguration' of type [com.alibaba.druid.spring.boot.autoconfigure.stat.DruidSpringAopConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
  13. 2024-05-10 10:29:43.176  INFO 49697 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'spring.datasource.druid-com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties' of type [com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
  14. 2024-05-10 10:29:43.186  INFO 49697 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'advisor' of type [org.springframework.aop.support.RegexpMethodPointcutAdvisor] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
  15. 2024-05-10 10:29:43.570  INFO 49697 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8081 (http)
  16. 2024-05-10 10:29:43.582  INFO 49697 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
  17. 2024-05-10 10:29:43.582  INFO 49697 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.68]
  18. 2024-05-10 10:29:43.752  INFO 49697 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
  19. 2024-05-10 10:29:43.752  INFO 49697 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2317 ms
  20. 2024-05-10 10:29:43.843  INFO 49697 --- [           main] c.a.d.s.b.a.DruidDataSourceAutoConfigure : Init DruidDataSource
  21. 2024-05-10 10:29:44.533  INFO 49697 --- [           main] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} inited
  22. 2024-05-10 10:29:44.750  INFO 49697 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
  23. 2024-05-10 10:29:44.873  INFO 49697 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.6.12.Final
  24. 2024-05-10 10:29:45.276  INFO 49697 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
  25. 2024-05-10 10:29:45.563  INFO 49697 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.sqlite.hibernate.dialect.SQLiteDialect
  26. 2024-05-10 10:29:45.667  INFO 49697 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.sqlite.hibernate.dialect.SQLiteDialect
  27. 2024-05-10 10:29:46.753  INFO 49697 --- [           main] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
  28. 2024-05-10 10:29:46.771  INFO 49697 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
  29. 2024-05-10 10:29:47.403  WARN 49697 --- [           main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
  30. 2024-05-10 10:29:47.746  INFO 49697 --- [           main] o.s.b.a.w.s.WelcomePageHandlerMapping    : Adding welcome page: class path resource [static/index.html]
  31. 2024-05-10 10:29:48.028  INFO 49697 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8081 (http) with context path ''
  32. 2024-05-10 10:29:48.040  INFO 49697 --- [           main] c.e.sqlitedemo.SqlitedemoApplication     : Started SqlitedemoApplication in 7.664 seconds (JVM running for 11.35)
  33. 2024-05-10 10:30:12.802  INFO 49697 --- [nio-8081-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
  34. 2024-05-10 10:30:12.802  INFO 49697 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
  35. 2024-05-10 10:30:12.804  INFO 49697 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 2 ms
  36. Hibernate: select user0_.id as u_1_0_, user0_.name as name2_0_ from user user0_ where user0_.name is not null
复制代码
可以或许正常访问
以上SQLite初体验到此结束~~

如果喜欢我的文章的话,可以去GitHub上给一个免费的关注吗?

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

曂沅仴駦

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表