Spring Boot 集成 Xerial/SQLite-JDBC 和 Druid 的详细指南
简介
在现代 Java 应用开发中,Spring Boot 提供了一个轻量级且功能强大的框架,用于快速构建和部署应用程序。SQLite 是一个轻量级的嵌入式关系数据库,因其无需单独安装数据库服务器且易于使用而广受欢迎。与此同时,Druid 是阿里巴巴开源的高性能数据库连接池,具备强大的监控、性能优化和 SQL 防注入功能。将 Xerial 的 SQLite-JDBC 驱动 与 Druid 集成到 Spring Boot 项目中,可以实现高效的数据库连接管理和全面的监控,为开发者提供稳定且性能卓越的应用环境。
环境准备
系统要求
- Java Development Kit (JDK) 8 或更高版本
- Maven 或 Gradle 用于项目构建和依赖管理
- Spring Boot 项目结构
- 一个 SQLite 数据库文件(可创建新的数据库文件或使用现有文件)
添加项目依赖
使用 Maven
在项目的 pom.xml 文件中添加以下依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.41.2.1</version> <!-- 请根据需要选择最新版本 -->
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
使用 Gradle
如果您使用的是 Gradle,可以在 build.gradle 文件中添加以下内容:
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
implementation 'org.xerial:sqlite-jdbc:3.41.2.1'
implementation 'com.alibaba:druid-spring-boot-starter:1.2.16'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa' <!-- 可选 -->
}
配置数据源
使用 application.yml
在 src/main/resources/application.yml 文件中添加以下配置:
spring:
datasource:
url: jdbc:sqlite:./db/mydatabase.db
driver-class-name: org.sqlite.JDBC
username: "" # SQLite 不需要用户名
password: "" # SQLite 不需要密码
druid:
initial-size: 5
min-idle: 5
max-active: 20
max-wait: 60000
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
validation-query: SELECT 1
test-while-idle: true
test-on-borrow: false
test-on-return: false
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
filters: stat,wall,log4j
connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
jpa:
hibernate:
ddl-auto: update
show-sql: true
server:
port: 8080
使用 application.properties
如果您更偏好使用 application.properties,可以添加以下配置:
spring.datasource.url=jdbc:sqlite:./db/mydatabase.db
spring.datasource.driver-class-name=org.sqlite.JDBC
spring.datasource.username=
spring.datasource.password=
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# Druid 配置
spring.datasource.druid.initial-size=5
spring.datasource.druid.min-idle=5
spring.datasource.druid.max-active=20
spring.datasource.druid.max-wait=60000
spring.datasource.druid.time-between-eviction-runs-millis=60000
spring.datasource.druid.min-evictable-idle-time-millis=300000
spring.datasource.druid.validation-query=SELECT 1
spring.datasource.druid.test-while-idle=true
spring.datasource.druid.test-on-borrow=false
spring.datasource.druid.test-on-return=false
spring.datasource.druid.pool-prepared-statements=true
spring.datasource.druid.max-pool-prepared-statement-per-connection-size=20
spring.datasource.druid.filters=stat,wall,log4j
spring.datasource.druid.connection-properties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# JPA 配置
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
# 服务器端口
server.port=8080
配置 Druid 监控
创建 Druid 配置类
在 src/main/java/com/example/config 目录下创建一个名为 DruidConfig.java 的配置类,用于设置 Druid 的监控页面和过滤器:
package com.example.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class DruidConfig {
/**
* 配置 Druid 数据源
*/
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
return new DruidDataSource();
}
/**
* 注册 Druid 监控的 StatViewServlet
*/
@Bean
public ServletRegistrationBean statViewServlet() {
ServletRegistrationBean bean =
new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
Map initParams = new HashMap<>();
initParams.put("loginUsername", "admin"); // 监控页面登录用户名
initParams.put("loginPassword", "admin"); // 监控页面登录密码
initParams.put("allow", ""); // 默认允许所有访问
// initParams.put("deny", "192.168.1.100"); // 拒绝特定 IP 访问
bean.setInitParameters(initParams);
return bean;
}
/**
* 注册 Druid 监控的 WebStatFilter
*/
@Bean
public FilterRegistrationBean webStatFilter() {
FilterRegistrationBean bean =
new FilterRegistrationBean<>(new WebStatFilter());
Map initParams = new HashMap<>();
initParams.put("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); // 排除过滤的路径
bean.setInitParameters(initParams);
bean.addUrlPatterns("/*");
return bean;
}
}
通过上述配置,您可以访问 Druid 监控页面,并使用配置的用户名和密码(如 admin/admin)登录,查看数据库连接池的状态和 SQL 执行统计。
实现数据库操作
使用 JdbcTemplate
Spring Boot 提供了 JdbcTemplate 以简化数据库操作。以下是一个示例,展示如何使用 JdbcTemplate 进行基本的 CRUD 操作:
package com.example.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
@Service
public class DatabaseService {
@Autowired
private JdbcTemplate jdbcTemplate;
public void createTable() {
String sql = "CREATE TABLE IF NOT EXISTS users (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"name TEXT NOT NULL, " +
"age INTEGER)";
jdbcTemplate.execute(sql);
}
public void insertUser(String name, int age) {
String sql = "INSERT INTO users (name, age) VALUES (?, ?)";
jdbcTemplate.update(sql, name, age);
}
public List> getAllUsers() {
String sql = "SELECT * FROM users";
return jdbcTemplate.queryForList(sql);
}
public void updateUserAge(int id, int newAge) {
String sql = "UPDATE users SET age = ? WHERE id = ?";
jdbcTemplate.update(sql, newAge, id);
}
public void deleteUser(int id) {
String sql = "DELETE FROM users WHERE id = ?";
jdbcTemplate.update(sql, id);
}
}
使用 JPA(可选)
如果您更喜欢使用 JPA 进行对象关系映射,可以按照以下步骤配置:
创建实体类
package com.example.entity;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private int age;
// Getters and Setters
public Long getId() {
return id;
}
// 其他 getter 和 setter 方法
}
创建 Repository 接口
package com.example.repository;
import com.example.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
创建服务层
package com.example.service;
import com.example.entity.User;
import com.example.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User saveUser(User user) {
return userRepository.save(user);
}
public List<User> findAllUsers() {
return userRepository.findAll();
}
// 其他 CRUD 方法
}
创建控制器
package com.example.controller;
import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@PostMapping
public User createUser(@RequestBody User user) {
return userService.saveUser(user);
}
@GetMapping
public List<User> getAllUsers() {
return userService.findAllUsers();
}
// 其他 CRUD API
}
启动项目并测试
运行 Spring Boot 应用
确保所有配置和代码均正确无误后,可以通过以下方式启动应用:
package com.example;
import com.example.service.DatabaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
@Autowired
private DatabaseService databaseService;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
// 可选:使用 CommandLineRunner 初始化数据
}
访问 Druid 监控页面
启动应用后,打开浏览器访问 http://localhost:8080/druid,使用配置的用户名和密码(如 admin/admin)登录,即可查看 Druid 提供的监控信息,包括数据库连接池状态、SQL 执行情况等。
测试 CRUD 操作
使用工具如 Postman 或 cURL 对 API 进行测试:
- 创建用户:
POST /api/users HTTP/1.1 Host: localhost:8080 Content-Type: application/json { "name": "张三", "age": 25 } - 获取所有用户:
GET /api/users HTTP/1.1 Host: localhost:8080
常见问题及解决方案
1. SQLite 数据库文件不存在
如果在启动应用时遇到类似于 java.sql.SQLException: no such table 或 java.sql.SQLException: path to 'mydatabase.db' 的错误,可能是因为 SQLite 数据库文件不存在或路径错误。解决方法如下:
- 确保配置的数据库路径正确。例如,
jdbc:sqlite:./db/mydatabase.db表示数据库文件位于项目的db目录下。 - 手动创建数据库文件或通过应用启动时自动创建。
可以在应用启动时添加初始化代码来自动创建表:
package com.example;
import com.example.service.DatabaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class DemoApplication {
@Autowired
private DatabaseService databaseService;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public CommandLineRunner init() {
return args -> {
databaseService.createTable();
};
}
}
2. Druid 监控页面无法访问
如果无法访问 Druid 监控页面,请检查以下几点:
-
确保
DruidConfig类中的ServletRegistrationBean和FilterRegistrationBean配置正确。 -
检查 Spring Boot 应用的端口号配置是否正确。
-
如果使用了 Spring Security,确保对
/druid/*路径的访问权限已正确配置。
示例:在 Spring Security 中允许访问 Druid 监控页面
package com.example.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/druid/**").permitAll() <!-- 允许访问 Druid 监控页面 -->
.anyRequest().authenticated()
.and()
.formLogin().permitAll()
.and()
.logout().permitAll();
}
}
3. 数据库连接问题
确保 SQLite JDBC 驱动版本与项目兼容,且数据库文件路径正确。如果仍有问题,请查看应用日志以获取详细错误信息。
总结
通过将 Xerial 的 SQLite-JDBC 驱动 与 Druid 集成到 Spring Boot 项目中,开发者可以实现高效且稳定的数据库连接管理,同时享受到 Druid 提供的强大监控和性能优化功能。这种组合特别适合小型应用程序、开发测试环境以及需要快速开发的场景。通过本文的详细步骤,您应该能够顺利完成集成,并构建出性能卓越的 Spring Boot 应用。
参考资料
通过以上内容,您可以在 Spring Boot 项目中成功集成 Xerial/SQLite-JDBC 和 Druid 数据源,并充分利用它们的优势来提升应用性能和管理效率。
Last updated January 5, 2025