使用Spring Boot快速构建基于SQLite数据源的应用

为了提供一个单包易部署的服务器应用,考虑使用Spring Boot,因为其集成了Apache Tomcat,易于运行,免去绝大部分了服务器配置的步骤。

项目初始化

首先从mvn archetype:generate中选择 com.github.mkspcd:simple-webapp(或其他webapp模版) 模版生成项目结构。

更多关于maven请移步Maven - Users Centre

pom.xml中添加parent来获取Spring Boot所需的最小依赖。

<project
        xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.github.hwding.example</groupId>
    <artifactId>example</artifactId>
    <packaging>jar</packaging>
    <version>0.0.1</version>
    <name>an example</name>
    <url>https://github.com/hwding</url>

    <!-- 添加Spring的Repository以便于添加相关组件 -->
    <repositories>
        <repository>
            <url>http://repo.spring.io/milestone/</url>
            <id>repo-spring</id>
        </repository>
    </repositories>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.6.RELEASE</version>
    </parent>

    <build>
        <finalName>example</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

            <!-- 编译级别,可选 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <!-- 用于Hibernate4的SQLite3 Dialect -->
        <dependency>
            <groupId>com.enigmabridge</groupId>
            <artifactId>hibernate4-sqlite-dialect</artifactId>
            <version>0.1.2</version>
        </dependency>

        <!-- 用于配置数据源 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <version>2.1.1</version>
        </dependency>

        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>javax.persistence</artifactId>
            <version>2.2.0-RC1</version>
        </dependency>

        <!-- SQLite3 驱动 -->
        <dependency>
            <groupId>org.xerial</groupId>
            <artifactId>sqlite-jdbc</artifactId>
            <version>3.20.0</version>
        </dependency>
    </dependencies>

</project>

pom中同时添加了Hibernate以及Spring JPA等相关组件。

配置数据源

@Configuration
public class DataSourceConfiguration {

    @Bean(destroyMethod = "", name = "EmbeddeddataSource")
    public DataSource dataSource() {
        DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
        dataSourceBuilder.driverClassName("org.sqlite.JDBC");
        dataSourceBuilder.url("jdbc:sqlite:" + "example.db");
        dataSourceBuilder.type(SQLiteDataSource.class);
        return dataSourceBuilder.build();
    }
}

这里设置了该Bean的destroyMethod = ""是为了防止停止服务器时容器管理器两次销毁导致的异常,name = "EmbeddeddataSource"用于在自动装配Bean时与其他dataSource加以区分。

为了使该独立服务易部署易分发,使用SQLite3作为数据存取的源,值得注意的是,该场景非常少见。

配置Spring Data JPA

@Configuration
@EnableJpaRepositories(
        basePackages = "com.github.hwding.example.data.repository",
        transactionManagerRef = "jpaTransactionManager",
        entityManagerFactoryRef = "localContainerEntityManagerFactoryBean"
)
@EnableTransactionManagement
public class JpaConfiguration {

    @Autowired
    @Bean
    public JpaTransactionManager jpaTransactionManager(@Qualifier(value = "EmbeddeddataSource") DataSource dataSource, EntityManagerFactory entityManagerFactory) {
        JpaTransactionManager jpaTransactionManager
                = new JpaTransactionManager();
        jpaTransactionManager.setEntityManagerFactory(entityManagerFactory);
        jpaTransactionManager.setDataSource(dataSource);

        return jpaTransactionManager;
    }

    @Autowired
    @Bean
    LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean(@Qualifier(value = "EmbeddeddataSource") DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) {
        LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean
                = new LocalContainerEntityManagerFactoryBean();
        localContainerEntityManagerFactoryBean.setDataSource(dataSource);
        localContainerEntityManagerFactoryBean.setPackagesToScan("com.github.hwding.example.data.model.local");
        localContainerEntityManagerFactoryBean.setJpaVendorAdapter(jpaVendorAdapter);
        return localContainerEntityManagerFactoryBean;
    }

    @Bean
    public JpaVendorAdapter jpaVendorAdapter() {
        HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
        hibernateJpaVendorAdapter.setGenerateDdl(true);
        hibernateJpaVendorAdapter.setShowSql(true);
        hibernateJpaVendorAdapter.setDatabasePlatform("com.enigmabridge.hibernate.dialect.SQLiteDialect");
        return hibernateJpaVendorAdapter;
    }
}

注意Repository和Entity扫描的包路径需要根据实际进行调整。

hibernateJpaVendorAdapter.setGenerateDdl(true);能够在初次运行时自动根据Entity的定义生成DDL并自动创建SQLite3的 .db 数据文件,在本例中是 example.db ,DDL会最小程度的满足Entity的定义;如果该文件已经存在,则并不会对其进行覆盖。

由于Hibernate并不对SQLite3提供支持,所以需要提供第三方Dialect给它:hibernateJpaVendorAdapter.setDatabasePlatform("com.enigmabridge.hibernate.dialect.SQLiteDialect");,这个类我们已经在pom中引入了。

配置入口

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }
}

Spring Boot能够从JAR包的入口直接启动整个应用程序。

Spring Boot 是一种用于快速创建 Spring 应用程序的开发框架,而 SQLite 是一款轻量级的嵌入式数据库,它的数据库文件默认为非加密状态。如何将两者相结合并实现 SQLite 加密功能呢? 首先,我们需要在 Spring Boot 中引入 SQLite 的依赖包。在 pom.xml 文件中加入以下代码: ```xml <dependency> <groupId>org.xerial</groupId> <artifactId>sqlite-jdbc</artifactId> <version>3.36.0.3</version> </dependency> ``` 然后,在项目中创建 SQLite 数据库文件,并设置密码。这可以通过在 SQLite 的连接字符串中指定 `PRAGMA key='your_password';` 来实现。 接下来,我们需要在 Spring Boot 中配置 SQLite数据源。在 `application.properties` 文件中加入以下配置: ```properties spring.datasource.url=jdbc:sqlite:your_db_file_path spring.datasource.driverClassName=org.sqlite.JDBC spring.datasource.username= spring.datasource.password= ``` 其中,`your_db_file_path` 为 SQLite 数据库文件的路径,`org.sqlite.JDBC` 是 SQLite 的 JDBC 驱动类。由于 SQLite 加密功能由 SQLite 自身实现,因此在数据源配置中不需要设置密码。 最后,在 Spring Boot 代码中,我们需要使用 SQLite JDBC 驱动来连接 SQLite 数据库,并执行加密相关的 SQL 语句。以下是一个示例代码: ```java import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; import javax.sql.DataSource; public class SQLiteEncryptor { private static final String DB_FILE_PATH = "your_db_file_path"; private static final String DB_PASSWORD = "your_password"; public static void main(String[] args) { // 创建数据源 DataSource dataSource = createDataSource(DB_FILE_PATH); // 执行加密相关的 SQL 语句 JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.execute("PRAGMA key='" + DB_PASSWORD + "';"); jdbcTemplate.execute("PRAGMA cipher_compatibility = 3;"); jdbcTemplate.execute("PRAGMA cipher_use_hmac = OFF;"); jdbcTemplate.execute("PRAGMA kdf_iter = 64000;"); // 其它操作... } private static DataSource createDataSource(String dbFilePath) { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("org.sqlite.JDBC"); dataSource.setUrl("jdbc:sqlite:" + dbFilePath); dataSource.setUsername(""); dataSource.setPassword(""); return dataSource; } } ``` 在以上代码中,`createDataSource()` 方法用于创建 SQLite 数据源,而 `main()` 方法中则通过 `JdbcTemplate` 来执行加密相关的 SQL 语句。其中,`PRAGMA key='your_password';` 用于设置密码,`PRAGMA cipher_compatibility = 3;` 和 `PRAGMA cipher_use_hmac = OFF;` 用于指定加密算法和哈希算法,`PRAGMA kdf_iter = 64000;` 则用于指定迭代次数。 综上,通过以上步骤,我们就可以在 Spring Boot 中实现 SQLite 数据库的加密功能。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值