SpringBoot 作为轻量级的 Java 开发框架,凭借自动配置、快速开发的特性,极大简化了企业级应用的开发流程。其中数据层开发是后端开发的核心环节,本文将从 SpringBoot 数据源自动管理、主流数据源配置、持久层框架整合入手,一步步实现一个完整的企业信息管理系统,涵盖从环境搭建到页面交互的全流程,让你快速掌握 SpringBoot 数据层开发的核心技能。
一、SpringBoot 数据层核心开发
1.1 数据源自动管理
SpringBoot 提供了强大的数据源自动配置能力,无需复杂的配置即可实现数据库连接池的管理,核心是引入对应的 JDBC 和数据库驱动依赖,再通过配置文件指定数据库信息。
1.1.1 引入核心依赖
需要引入 SpringBoot 的 JDBC 启动器、数据库连接池(以 commons-dbcp2 为例)和 MySQL 驱动依赖,Maven 配置如下:
XML
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
1.1.2 配置数据源信息
使用 YAML 格式的application.yaml配置文件指定数据库连接信息,SpringBoot 默认会自动识别并配置连接池,优先级为HikariDataSource > Commons DBCP2 ,也可以通过type属性手动指定数据源:
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/boot_demo
driver-class-name: com.mysql.jdbc.Driver
# 手动指定数据源,Hikari为SpringBoot默认推荐
type: com.zaxxer.hikari.HikariDataSource
# 也可指定DBCP2:type: org.apache.commons.dbcp2.BasicDataSource
1.2 配置阿里 Druid 数据源
Hikari 和 DBCP2 是 SpringBoot 默认支持的数据源,而阿里的 Druid 数据源提供了监控、统计、防火墙等丰富的附加功能,是企业开发中的主流选择,需要手动引入依赖并配置。
1.2.1 引入 Druid 依赖
同时引入 log4j 依赖,支持 Druid 的日志监控功能:
XML
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.9</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
</dependency>
1.2.2 配置 Druid 数据源参数
在application.yaml中修改数据源类型为 Druid,并配置连接池的核心参数(初始化连接数、最大活跃数、监控过滤等):
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/boot_demo
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
# Druid连接池参数
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
1.2.3 编写 Druid 配置类
创建配置类将 Druid 数据源注入 Spring 容器,并配置运行期监控的 Servlet 和 Filter,实现 Druid 的可视化监控功能:
java
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.Arrays;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class DruidConfig {
// 注入Druid数据源,绑定配置文件中的spring.datasource参数
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource dataSource(){
return new DruidDataSource();
}
// 配置Druid监控页面的Servlet
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
Map<String,String> initParams = new HashMap<>();
initParams.put("loginUsername","root"); // 监控页面登录用户名
initParams.put("loginPassword","root"); // 监控页面登录密码
initParams.put("allow",""); // 允许所有IP访问
initParams.put("deny","192.168.15.21"); // 禁止指定IP访问
bean.setInitParameters(initParams);
return bean;
}
// 配置Web监控的Filter,排除静态资源和监控页面
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
Map<String,String> initParams = new HashMap<>();
initParams.put("exclusions","*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}
配置完成后,启动项目访问http://localhost:8080/druid,输入配置的用户名和密码,即可进入 Druid 的可视化监控页面,查看数据源、SQL 执行、Web 请求等信息。
1.3 整合 JdbcTemplate
SpringBoot 提供了JdbcTemplateAutoConfiguration自动配置类,引入 JDBC 启动器后可直接注入JdbcTemplate使用,简化原生 JDBC 的 CRUD 操作。
1.3.1 数据库建表
首先在boot_demo数据库中创建测试表tx_user:
sql
SET FOREIGN_KEY_CHECKS=0;
DROP TABLE IF EXISTS `tx_user`;
CREATE TABLE `tx_user` (
`username` varchar(10) DEFAULT NULL,
`userId` int(10) NOT NULL,
`password` varchar(10) DEFAULT NULL,
PRIMARY KEY (`userId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1.3.2 编写测试接口
直接注入JdbcTemplate,调用其方法实现数据库查询,无需手动管理连接:
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
import java.util.Map;
@Controller
public class TestController {
@Autowired
JdbcTemplate jdbcTemplate;
@ResponseBody
@RequestMapping("/query")
public List<Map<String, Object>> query(){
// 执行查询,返回结果为Map集合
List<Map<String, Object>> maps = jdbcTemplate.queryForList("SELECT * FROM tx_user");
return maps;
}
}
启动项目访问http://localhost:8080/query,即可获取数据库中的用户数据。
1.4 整合 MyBatis(注解版)
JdbcTemplate 适合简单的数据库操作,而 MyBatis 是企业开发中主流的持久层框架,SpringBoot 整合 MyBatis 注解版无需编写 XML 映射文件,通过注解即可实现 SQL 操作,开发效率更高。
1.4.1 引入 MyBatis 启动器依赖
XML
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
1.4.2 核心开发步骤
- 复用 Druid 数据源配置:直接使用上文配置的 Druid 数据源,无需额外修改;
- 数据库建表 :创建
tx_person表(含主键、姓名、地址、性别、生日字段); - 创建 JavaBean:对应数据库表的实体类,注意字段名与数据库的映射;
- 创建 Mapper 接口 :添加
@Mapper注解,通过 MyBatis 注解编写 SQL:
java
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface TxPersonMapper {
// 查询所有用户
@Select("select * from tx_person")
public List<TxPerson> getPersons();
// 根据ID查询用户
@Select("select * from tx_person t where t.pid = #{id}")
public TxPerson getPersonById(int id);
// 新增用户,自动生成主键
@Options(useGeneratedKeys =true, keyProperty = "pid")
@Insert("insert into tx_person(pid, pname, addr,gender, birth) values(#{pid}, #{pname}, #{addr},#{gender}, #{birth})")
public void insert(TxPerson person);
// 根据ID删除用户
@Delete("delete from tx_person where pid = #{id}")
public void delete(int id);
}
1.4.3 解决驼峰命名映射问题
数据库表中常用下划线命名(如p_addr),而 JavaBean 常用驼峰命名(如pAddr),需要配置 MyBatis 自动开启驼峰命名映射:
java
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MybatisConfig {
@Bean
public ConfigurationCustomizer getCustomizer(){
return new ConfigurationCustomizer() {
@Override
public void customize(org.apache.ibatis.session.Configuration configuration) {
// 开启下划线到驼峰的自动映射
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}
1.4.4 替代 @Mapper 注解:包扫描
如果有多个 Mapper 接口,无需逐个添加@Mapper注解,可在配置类上添加@MapperScan("cn.tx.mapper")注解,扫描指定包下的所有 Mapper 接口,简化配置。
1.5 整合 MyBatis(配置文件版)
对于复杂的 SQL 操作(如多表联查、动态 SQL),注解版不够灵活,可使用 MyBatis 配置文件版,将 SQL 写在 XML 文件中,解耦代码与 SQL。
-
创建 MyBatis 核心配置文件 :
sqlMapConfig.xml,存放全局配置; -
创建 Mapper 映射文件 :
PersonMapper.xml,编写 SQL 语句,指定 namespace 对应 Mapper 接口; -
在 application.yaml 中配置 MyBatis:指定配置文件路径、映射文件路径和实体类别名包:
mybatis:
config-location: classpath:mybatis/sqlMapConfig.xml
mapper-locations: classpath:mybatis/mapper/*.xml
type-aliases-package: cn.tx.springboot.jdbc_demo1
二、SpringBoot 开发企业信息管理系统
基于上文的 SpringBoot 数据层开发基础,我们开发一个完整的企业信息管理系统 ,实现用户的登录、新增、查询、修改、删除功能,整合 Thymeleaf 模板引擎实现前端页面交互,打造前后端一体化的企业级应用。
2.1 项目环境搭建
2.1.1 引入所有核心依赖
整合 Web、Thymeleaf、MyBatis、Druid、MySQL、热部署等依赖,一次引入完成环境搭建:
XML
<!-- Web核心 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 测试 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 热部署 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<!-- Thymeleaf模板引擎 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- jQuery -->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.3.1</version>
</dependency>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<!-- Druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.9</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
</dependency>
<!-- MySQL驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
2.1.2 引入页面原型
将企业信息管理系统的前端页面(登录页、首页、新增页、修改页)放入resources/templates目录(Thymeleaf 默认模板目录),静态资源(CSS、JS、图片)放入resources/static目录。
2.2 Thymeleaf 模板与 MVC 配置
Thymeleaf 是 SpringBoot 推荐的模板引擎,支持 HTML 原生语法,通过命名空间xmlns:th="http://www.thymeleaf.org"实现前后端数据绑定,同时需要配置 MVC 实现页面跳转和登录拦截。
2.2.1 编写 MVC 配置类
实现WebMvcConfigurer接口,配置页面跳转 和登录拦截器,排除静态资源和登录页的拦截:
java
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.ArrayList;
import java.util.List;
@Configuration
@MapperScan("cn.tx.springboot.mapper") // 扫描Mapper接口
public class TxMvcConfig implements WebMvcConfigurer{
// 配置页面跳转,无需编写Controller
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/toLogin").setViewName("login");
registry.addViewController("/header").setViewName("header");
registry.addViewController("/index").setViewName("index");
registry.addViewController("/menu").setViewName("menu");
registry.addViewController("/add").setViewName("add");
}
// 配置登录拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
List<String> excludePatterns = new ArrayList<String>();
// 排除静态资源和登录相关页面
excludePatterns.add("/css/**");
excludePatterns.add("/images/**");
excludePatterns.add("/toLogin");
excludePatterns.add("/login");
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/**") // 拦截所有请求
.excludePathPatterns(excludePatterns); // 排除指定请求
}
}
2.3 数据库与数据源配置
2.3.1 创建业务表
创建系统的核心用户表my_user,包含用户 ID、用户名、密码、地址、性别、生日字段,并插入测试数据:
sql
SET FOREIGN_KEY_CHECKS=0;
DROP TABLE IF EXISTS `my_user`;
CREATE TABLE `my_user` (
`pid` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`p_addr` varchar(255) DEFAULT NULL,
`gender` int(11) DEFAULT NULL,
`birth` date DEFAULT NULL,
PRIMARY KEY (`pid`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- 插入测试数据
INSERT INTO `my_user` VALUES ('1', 'zhangsan', '123', '北京', '1', '2020-06-14');
2.3.2 复用 Druid 数据源配置
直接使用上文的 Druid 数据源配置(配置文件 + 配置类),无需额外修改,实现数据库连接和监控。
2.4 编写数据层与业务层
2.4.1 数据层:MyUserMapper
创建 Mapper 接口,通过 MyBatis 注解实现用户的增删改查和登录验证:
java
import org.apache.ibatis.annotations.*;
import java.util.List;
import java.util.Map;
public interface MyUserMapper {
// 新增用户
@Options(useGeneratedKeys = true, keyProperty = "pid")
@Insert("insert into my_user(pid, username, password, p_addr, gender, birth)values(#{pid}, #{username}, #{password}, #{pAddr}, #{gender}, #{birth})")
public void insert(MyUser user) ;
// 查询所有用户
@Select("select * from my_user")
public List<MyUser> selectUsers();
// 登录验证:根据用户名和密码查询
@Select("select * from my_user t where t.username = #{username} and t.password = #{password}")
public MyUser selectUsersById(Map<String, String> map);
// 根据ID查询用户
@Select("select * from my_user t where t.pid = #{pid}")
public MyUser selectUsersById1(int userId);
// 修改用户
@Update("update my_user set username = #{username},password=#{password}, p_addr= #{pAddr}, gender=#{gender}, birth=#{birth} where pid = #{pid}")
public void update(MyUser user) ;
// 删除用户
@Delete("delete from my_user where pid = #{pid}")
public void delete(int pid) ;
}
2.4.2 业务层:Service 接口与实现
创建MyUserService接口定义业务方法,再编写实现类MyUserServiceImpl,注入 Mapper 接口实现业务逻辑(此处省略实现类,核心为调用 Mapper 的方法)。
2.5 页面交互与 Controller 编写
2.5.1 核心页面处理
- 首页 :使用 frameset 分栏,包含头部、菜单和主内容区,通过 Thymeleaf 的
th:src实现动态跳转; - 用户列表页 :通过
th:each遍历用户数据,th:text绑定字段,实现增删改查的按钮跳转; - 新增页 :通过表单提交用户信息,
th:action指定提交地址,后台接收参数并调用 Service 新增; - 修改页 :回显用户原有信息,
th:value绑定字段,提交后更新数据库; - 登录页:通过表单提交用户名和密码,后台验证后将用户信息存入 Session,实现登录状态保持。
2.5.2 登录功能 Controller
核心实现用户名密码验证、Session 存储、登录失败提示:
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
@Controller
public class LoginController {
@Autowired
private MyUserService userService;
@PostMapping("/login")
public String login(HttpSession session, String username, String password, Model model) {
Map<String, String> map = new HashMap<String, String>();
map.put("username", username);
map.put("password", password);
// 调用业务层验证登录
MyUser user = userService.selectUsersById(map);
if (user != null){
// 登录成功,将用户存入Session
session.setAttribute("user", user);
return "redirect:index";
}else{
// 登录失败,返回提示信息
model.addAttribute("tip","用户名或者密码错误");
return "login";
}
}
}
2.5.3 头部页面动态显示登录状态
通过 Thymeleaf 的条件判断th:if,根据 Session 中是否有用户信息,动态显示用户名或登录链接:
<div id="welcome">
欢迎你回来
<span th:text="${session.user.username}" th:if="${not #strings.isEmpty(session.user)}"></span>
<a target="_top" th:text="请登录" th:href="@{/toLogin}" th:if="${#strings.isEmpty(session.user)}"></a>
<img src="images/clock.gif" /> 学习是最好的投资
</div>
三、项目核心亮点与总结
3.1 项目核心亮点
- 自动配置简化开发:SpringBoot 的自动配置特性让数据源、JdbcTemplate、MyBatis 无需复杂配置,开箱即用;
- 主流技术栈整合:整合 Druid(数据源)、MyBatis(持久层)、Thymeleaf(视图层),贴合企业开发实际;
- 功能完整:实现了企业信息管理系统的核心功能(登录、增删改查),包含登录拦截、状态保持、前后端数据绑定;
- 可监控可扩展:Druid 数据源提供可视化监控,MyBatis 支持注解和配置文件两种方式,方便后续扩展复杂业务;
- 规范的分层开发 :遵循Controller(控制层)→ Service(业务层)→ Mapper(数据层) 的分层架构,解耦代码,便于维护。
3.2 开发总结
SpringBoot 数据层开发的核心是数据源配置 和持久层框架整合,掌握 Druid 的配置和监控、MyBatis 的注解与 XML 两种使用方式,是开发企业级应用的基础。本次实战从基础的数据源管理入手,一步步整合到完整的企业信息管理系统,覆盖了从环境搭建到页面交互的全流程,让我们体会到 SpringBoot "约定大于配置" 的魅力,极大提升了开发效率。
在实际开发中,可在此基础上扩展分页、模糊查询、权限控制、异常处理等功能,同时结合 Spring Security 实现更安全的登录验证,结合 PageHelper 实现 MyBatis 分页,让系统更贴合企业的实际开发需求。