SpringBoot整合SpringDataJPA的示例

 更新时间:2023年06月16日 10:18:34   作者:Java劝退师、  
本文主要介绍了SpringBoot整合SpringDataJPA的示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

1.JPA是什么

首先,我们说说JPA是什么?

JPA(java persistence api),它并不是一个框架,而是一组规范。我觉得对于任何一个开发人员来说,理解“规范”这个词应该不在话下。其中,Hibernate就实现了这个规范,而且那是相当成功的(其实TopLink和OpenJPA也都实现了JPA规范,不过它们被Hinernate的光环笼罩了)。所以呢,当我们说到JPA的时候,好多人首先想到的就是Hibernate。

2.SpringBootData JPA是什么

SpringData:其实SpringData就是Spring提供了一个操作数据的框架。而SpringData JPA只是SpringData框架下的一个基于JPA标准操作数据的模块。
SpringData JPA:基于JPA的标准数据进行操作。简化操作持久层的代码。只需要编写接口就可以。

废话不多说了,直接开始

3.环境/版本一览

  • 开发工具:Intellij IDEA 2020.2.3
  • springboot:2.3.7.RELEASE
  • jdk:1.8.0_211
  • maven: 3.6.3

4.工程结构 

5.开始搭建

创建数据库

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for sys_user
-- ----------------------------
DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `pwd` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of sys_user
-- ----------------------------
BEGIN;
INSERT INTO `sys_user` VALUES (1, 'test', '123');
COMMIT;
SET FOREIGN_KEY_CHECKS = 1;

新建项目

pom.xml依赖配置

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.niu</groupId>
    <artifactId>datasource</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <name>datasource</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <!-- alibaba的druid数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.9</version>
        </dependency>
        <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>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.39</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

创建配置文件 application.yml

server:
  port: 8080
spring:
  datasource:
    name: main_db
    type: com.alibaba.druid.pool.DruidDataSource
    #druid相关配置
    druid:
      #监控统计拦截的filters
      filters: stat
      driver-class-name: com.mysql.jdbc.Driver
      #基本属性
      url: jdbc:mysql://127.0.0.1:3306/t_user_db?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
      username: root
      password: Abcdef@123456
      #配置初始化大小/最小/最大
      initial-size: 1
      min-idle: 1
      max-active: 20
      #获取连接等待超时时间
      max-wait: 60000
      #间隔多久进行一次检测,检测需要关闭的空闲连接
      time-between-eviction-runs-millis: 60000
      #一个连接在池中最小生存的时间
      min-evictable-idle-time-millis: 300000
      validation-query: SELECT 'x'
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      #打开PSCache,并指定每个连接上PSCache的大小。oracle设为true,mysql设为false。分库分表较多推荐设置为false
      pool-prepared-statements: false
      max-pool-prepared-statement-per-connection-size: 20
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true

创建model  类多的话可以使用逆向工程创建

@Entity(name = "sys_user") //name值代表数据库对应的表名,如不写默认按照实体类的驼峰命名法单词中间加_
@JsonIgnoreProperties(value = { "hibernateLazyInitializer"}) //加这个注解是为了防止本项目把jpa对象直接转json有空值报错
public class SysUser {
    @Id
    @GeneratedValue
    private Integer id;
    /**
     *
     *   这里是映射数据表字段与实体字段 若数据库表字段为 user_name  这里需要写成
     *   @Column(name = "user_name") 
     *   private String userName;
     *   如果一致可以不写   
     */
    @Column(name = "name") 
    private String name;
    private String pwd;
        //get/set省略,记得加上
}

创建Repository

/**
 *  
 * JpaRepository<SysUser,Integer> 参数1 要映射的实体类
 *                                参数2 实体类主键的数据类型
 *  每个dao层接口都要继承这个类
 **/
@Repository
public interface SysUserRepository  extends JpaRepository<SysUser,Integer> {
}

创建service

@Service
public class UserService {
    @Autowired
    private SysUserRepository sysUserRepository;
    public SysUser getUser(Integer id){
        return  sysUserRepository.getOne(id);
    }
}

创建controller 这里我们让接口都返回json 使用@RestController注解

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @GetMapping("/{userId}")
    public SysUser user(@PathVariable  Integer userId){
        return userService.getUser(userId);
    }
}

创建主类

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

6.启动测试

查看下日志:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.7.RELEASE)

2020-12-17 10:05:32.976  INFO 3434 --- [           main] c.n.springboot.SpringbootJPAApplication  : Starting SpringbootJPAApplication on MacBook-Pro.local with PID 3434 (/Users/laoniu/IdeaProjects/datasource/target/classes started by laoniu in /Users/laoniu/IdeaProjects/datasource)
2020-12-17 10:05:32.979  INFO 3434 --- [           main] c.n.springboot.SpringbootJPAApplication  : No active profile set, falling back to default profiles: default
2020-12-17 10:05:33.606  INFO 3434 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-12-17 10:05:33.668  INFO 3434 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 55ms. Found 1 JPA repository interfaces.
2020-12-17 10:05:34.014  INFO 3434 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2020-12-17 10:05:34.021  INFO 3434 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-12-17 10:05:34.021  INFO 3434 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.41]
2020-12-17 10:05:34.096  INFO 3434 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-12-17 10:05:34.096  INFO 3434 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1058 ms
2020-12-17 10:05:34.150  INFO 3434 --- [           main] c.a.d.s.b.a.DruidDataSourceAutoConfigure : Init DruidDataSource
Thu Dec 17 10:05:34 CST 2020 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
2020-12-17 10:05:34.627  INFO 3434 --- [           main] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} inited
2020-12-17 10:05:34.774  INFO 3434 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-12-17 10:05:34.807  INFO 3434 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.4.25.Final
2020-12-17 10:05:34.903  INFO 3434 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2020-12-17 10:05:34.981  INFO 3434 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL57Dialect
2020-12-17 10:05:35.360  INFO 3434 --- [           main] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-12-17 10:05:35.367  INFO 3434 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-12-17 10:05:35.580  WARN 3434 --- [           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
2020-12-17 10:05:35.680  INFO 3434 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-12-17 10:05:35.878  INFO 3434 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2020-12-17 10:05:35.890  INFO 3434 --- [           main] c.n.springboot.SpringbootJPAApplication  : Started SpringbootJPAApplication in 3.227 seconds (JVM running for 3.93)
2020-12-17 10:05:49.330  INFO 3434 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-12-17 10:05:49.331  INFO 3434 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2020-12-17 10:05:49.335  INFO 3434 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 4 ms
Hibernate: select sysuser0_.id as id1_0_0_, sysuser0_.name as name2_0_0_, sysuser0_.pwd as pwd3_0_0_ from sys_user sysuser0_ where sysuser0_.id=?

 

可以看到最后一行是SpringDataJPA为我们生成的查询语句,我们并没有写sql,只是调用的SpringDataJPA自带的方法,让我们去看一下SpringDataJPA都为我们提供哪些可用的方法

7.Repository接口的使用

7.1SpringDataJPA提供的方法

按照SpringDataJPA规范可以让我们只写方法就可以进行操作数据库,让我们试一下

7.2编写Repository接口方法

//方法名称必须要遵循驼峰式命名规则,findBy(关键字)+属性名称(首字母大写)+查询条件(首字母大写)  
SysUser findByNameAndPwd(String name,String pwd);

这样就能完成基本的查询

删除用deleteBy开头方法

如果方法不能满足我的需求呢,我们还可以通过@Query注解手动写sql

8.@Query基本使用

   /***
     *
     * ?1表示第一个参数,?2表示第二个参数
     * 这里的写法是hql写法
     * nativeQuery = false 代表使用hql ,默认不设置的话就是false 默认使用的hql
     * 要想使用 原生的sql  改为 true即可
     */
    @Query(value = "from SysUser where name = ?1 and pwd =?2",nativeQuery = false)
    SysUser findByNameAndPwdUseSQL(String name,String pwd);

到此,SpringBoot整合SpringDataJPA基本的使用结束,代码已经推送至github,https://github.com/NiuXiangQian/springboot-jpa

到此这篇关于SpringBoot整合SpringDataJPA的示例的文章就介绍到这了,更多相关SpringBoot整合SpringDataJPA内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java String字符串和Unicode字符相互转换代码详解

    Java String字符串和Unicode字符相互转换代码详解

    这篇文章主要介绍了Java String字符串和Unicode字符相互转换代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-05-05
  • Java设计模式之迪米特原则精解

    Java设计模式之迪米特原则精解

    设计模式(Design pattern)代表了最佳的实践,通常被有经验的面向对象的软件开发人员所采用。设计模式是软件开发人员在软件开发过程中面临的一般问题的解决方案。本篇介绍设计模式七大原则之一的迪米特原则
    2022-02-02
  • mybatis查询SqlServer慢问题及解决

    mybatis查询SqlServer慢问题及解决

    这篇文章主要介绍了mybatis查询SqlServer慢问题及解决方案,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-08-08
  • HashMap和Hashtable的详细比较

    HashMap和Hashtable的详细比较

    这篇文章主要介绍了HashMap和Hashtable的详细比较的相关资料,需要的朋友可以参考下
    2017-04-04
  • JWT 设置token过期时间无效的解决

    JWT 设置token过期时间无效的解决

    这篇文章主要介绍了JWT 设置token过期时间无效的解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-07-07
  • 基于java高并发处理方案

    基于java高并发处理方案

    这篇文章主要介绍了基于java高并发处理方案,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-08-08
  • 使用SpringBoot中的Schedule定时发送邮件的方法

    使用SpringBoot中的Schedule定时发送邮件的方法

    在SpringBoot中,你可以使用@Scheduled注解来创建定时任务,@Scheduled注解可以应用于方法上,表示这个方法是一个定时任务,可以根据指定的时间间隔或固定时间执行,本文就给大家介绍一下如何使用SpringBoot中的Schedule定时发送邮件,需要的朋友可以参考下
    2023-08-08
  • idea中的update project按钮使用

    idea中的update project按钮使用

    这篇文章主要介绍了idea中的update project按钮使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-05-05
  • Java日常练习题,每天进步一点点(62)

    Java日常练习题,每天进步一点点(62)

    下面小编就为大家带来一篇Java基础的几道练习题(分享)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧,希望可以帮到你
    2021-08-08
  • Java中枚举类enum的values()方法举例详解

    Java中枚举类enum的values()方法举例详解

    这篇文章主要给大家介绍了关于Java中枚举类enum的values()方法举例详解,作为一种常用方法,可以在枚举中对数组里的枚举值进行遍历,这就是values()方法的使用,需要的朋友可以参考下
    2023-11-11

最新评论