Spring Boot 揭秘与实战(二) 数据存储篇 - JPA整合
文章目录
本文讲解 Spring Boot 基础下,如何整合 JPA 框架,编写数据访问。
环境依赖
修改 POM 文件,添加 spring-boot-starter-data-jpa 依赖。
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-jpa</artifactId>
- </dependency>
添加 mysql 依赖。
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <version>5.1.35</version>
- </dependency>
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>druid</artifactId>
- <version>1.0.14</version>
- </dependency>
数据源
使用 Spring Boot 默认配置, 在 src/main/resources/application.properties 中配置数据源信息。
- spring.datasource.driver-class-name=com.mysql.jdbc.Driver
- spring.datasource.url=jdbc:mysql://localhost:3306/springboot_db
- spring.datasource.username=root
- spring.datasource.password=root
通过 Java Config 方式配置。
- @Configuration
- @EnableJpaRepositories("com.lianggzone.springboot.action.data.jpa")
- @EntityScan("com.lianggzone.springboot.action.data.jpa.entity")
- public class JPAConfig {}
脚本初始化
先初始化需要用到的SQL脚本。
- CREATE DATABASE /*!32312 IF NOT EXISTS*/`springboot_db` /*!40100 DEFAULT CHARACTER SET utf8 */;
- USE `springboot_db`;
- DROP TABLE IF EXISTS `t_author`;
- CREATE TABLE `t_author` (
- `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '用户ID',
- `real_name` varchar(32) NOT NULL COMMENT '用户名称',
- `nick_name` varchar(32) NOT NULL COMMENT '用户匿名',
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
JPA 整合方案一 通过继承 JpaRepository 接口
实体对象
创建一个 Author 实体,真实的表名是 t_author,包含 id(自增主键)、 realName、 nickname 字段。
- @Entity
- @Table(name = "t_author")
- public class Author{
- @Id
- @GeneratedValue(strategy = GenerationType.AUTO)
- private Long id;
- @Column(name="real_name")
- private String realName;
- @Column(name="nick_name")
- private String nickName;
- // SET和GET方法
- }
DAO相关
数据访问层,通过编写一个继承自 JpaRepository 的接口就能完成数据访问。值得注意的是,这个的 from 对象名,而不是具体的表名。
- public interface AuthorRepository extends JpaRepository<Author, Long> {
- List<Author> findAll();
- @Query("from Author where id = :id")
- Author findAuthor(@Param("id") Long id);
- }
Service相关
简单的调用 DAO 相关方法。
- @Service("jpa.authorService")
- public class AuthorService {
- @Autowired
- private AuthorRepository authorRepository;
- public List<Author> findAll() {
- return this.authorRepository.findAll();
- }
- public Author findAuthor(Long id){
- return this.authorRepository.findAuthor(id);
- }
- }
Controller相关
为了展现效果,我们先定义一组简单的 RESTful API 接口进行测试。
- @RestController("jpa.authorController")
- @RequestMapping(value = "/data/jpa/author")
- public class AuthorController {
- @Autowired
- private AuthorService authorService;
- /**
- * 查询用户列表
- */
- @RequestMapping(method = RequestMethod.GET)
- public Map<String, Object> getAuthorList(HttpServletRequest request) {
- List<Author> authorList = this.authorService.findAll();
- Map<String, Object> param = new HashMap<String, Object>();
- param.put("total", authorList.size());
- param.put("rows", authorList);
- return param;
- }
- /**
- * 查询用户信息
- */
- @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.GET)
- public Author getAuthor(@PathVariable Long userId, HttpServletRequest request) {
- Author author = this.authorService.findAuthor(userId);
- if (author == null) {
- throw new RuntimeException("查询错误");
- }
- return author;
- }
- }
JPA 整合方案二 通过调用 EntityManager 类方法
实体对象
- @Entity
- @Table(name = "t_author")
- public class Author{
- @Id
- @GeneratedValue(strategy = GenerationType.AUTO)
- private Long id;
- @Column(name="real_name")
- private String realName;
- @Column(name="nick_name")
- private String nickName;
- // SET和GET方法
- }
DAO相关
数据访问层,通过编写一个调用EntityManager 类方法。值得注意的是,这个的 from 对象名,而不是具体的表名。
- public interface AuthorDao {
- List<Author> findAll();
- Author findAuthor(Long id);
- }
- @Repository
- public class AuthorDaoImpl implements AuthorDao {
- @PersistenceContext
- private EntityManager entityManager;
- @Override
- public List<Author> findAll() {
- return this.entityManager
- .createQuery("select t from Author t", Author.class)
- .getResultList();
- }
- @Override
- public Author findAuthor(Long id){
- return this.entityManager
- .createQuery("select t from Author t where id = ?", Author.class)
- .setParameter(1, id)
- .getSingleResult();
- }
- }
Service相关
简单的调用 DAO 相关方法。
- @Service("jpa.authorService2")
- public class AuthorService2 {
- @Autowired
- private AuthorDao authorDao;
- public List<Author> findAll() {
- return this.authorDao.findAll();
- }
- public Author findAuthor(Long id){
- return this.authorDao.findAuthor(id);
- }
- }
Controller相关
为了展现效果,我们先定义一组简单的 RESTful API 接口进行测试。
- @RestController("jpa.authorController2")
- @RequestMapping(value = "/data/jpa/author2")
- public class AuthorController2 {
- @Autowired
- private AuthorService2 authorService;
- /**
- * 查询用户列表
- */
- @RequestMapping(method = RequestMethod.GET)
- public Map<String, Object> getAuthorList(HttpServletRequest request) {
- List<Author> authorList = this.authorService.findAll();
- Map<String, Object> param = new HashMap<String, Object>();
- param.put("total", authorList.size());
- param.put("rows", authorList);
- return param;
- }
- /**
- * 查询用户信息
- */
- @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.GET)
- public Author getAuthor(@PathVariable Long userId, HttpServletRequest request) {
- Author author = this.authorService.findAuthor(userId);
- if (author == null) {
- throw new RuntimeException("查询错误");
- }
- return author;
- }
- }
源代码
相关示例完整代码: springboot-action
(完)

分类:
SpringBoot
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 百万级群聊的设计实践
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期