SpringBoot整合SpringDataJPA

14 篇文章 0 订阅
3 篇文章 0 订阅

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

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java劝退师、

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值