欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot集成JPA

程序员文章站 2022-09-27 17:02:14
JPA是一种规范,而Spring Data JPA可以有效简化关系型数据库访问代码。 ......

在springboot中,通过spring data jpa 和 spring data rest可以快速构建出一个restful应用。

关于spring data jpa:jpa是一种规范,而spring data jpa可以有效简化关系型数据库访问代码。

关于spring data:spring data是spring的一个子项目,致力于简化数据库访问。


jpa规范:

jpa中有种定义,将java对象【pojo】映射到数据库。


@entity(name=“t_book”)

表明该类为一个实体类,它默认对应数据库中的表名是t_book,在项目启动时会根据该类自动生成一张表。

【如果不配置name,默认表名为类名】


@id

表示该属性是一个主键,@generatedvalue(strategy = generationtype.identity)表示主键自动生成,strategy表示主键生成策略。

创建工程

  • 导入pom依赖

    <?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelversion>4.0.0</modelversion>
    
      <groupid>org.sang</groupid>
      <artifactid>jparestful</artifactid>
      <version>0.0.1-snapshot</version>
      <packaging>jar</packaging>
    
      <name>jparestful</name>
      <description>demo project for spring boot</description>
    
      <parent>
          <groupid>org.springframework.boot</groupid>
          <artifactid>spring-boot-starter-parent</artifactid>
          <version>2.0.3.release</version>
          <relativepath/> <!-- lookup parent from repository -->
      </parent>
    
      <properties>
          <project.build.sourceencoding>utf-8</project.build.sourceencoding>
          <project.reporting.outputencoding>utf-8</project.reporting.outputencoding>
          <java.version>1.8</java.version>
      </properties>
    
      <dependencies>
          <dependency>
              <groupid>org.springframework.boot</groupid>
              <artifactid>spring-boot-starter-data-jpa</artifactid>
          </dependency>
          <dependency>
              <groupid>org.springframework.boot</groupid>
              <artifactid>spring-boot-starter-data-rest</artifactid>
          </dependency>
          <dependency>
              <groupid>com.alibaba</groupid>
              <artifactid>druid</artifactid>
              <version>1.1.9</version>
          </dependency>
          <dependency>
              <groupid>mysql</groupid>
              <artifactid>mysql-connector-java</artifactid>
              <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>
    
  • 配置数据库连接

    spring.datasource.type=com.alibaba.druid.pool.druiddatasource
    spring.datasource.username=noneplus
    spring.datasource.password=noneplus564925080!
    spring.datasource.url=jdbc:mysql://47.103.6.247:3306/restful-jpa?servertimezone=utc
    spring.jpa.hibernate.ddl-auto=update
    spring.jpa.database=mysql
    spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.mysql57dialect
    spring.jpa.show-sql=true
    
    ##每页默认记录数,缺省值为20
    #spring.data.rest.default-page-size=2
    ##分页查询页码参数名,缺省值为page
    #spring.data.rest.page-param-name=page
    ##分页查询记录数参数名,缺省值为size
    #spring.data.rest.limit-param-name=size
    ##分页查询排序参数名,缺省值为sort
    #spring.data.rest.sort-param-name=sort
    ##base-path表示给所有请求路径都加上前缀
    #spring.data.rest.base-path=/api
    ##添加成功时是否返回添加内容
    #spring.data.rest.return-body-on-create=true
    ##更新成功时是否返回更新内容
    #spring.data.rest.return-body-on-update=true
  • 创建实体类

    @entity(name = "t_book")
    public class book {
        @id
        @generatedvalue(strategy = generationtype.identity)
        private integer id;
        private string name;
        private string author;
        //省略getter/setter
    
        @override
        public string tostring() {
            return "book{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", author='" + author + '\'' +
                    '}';
        }
    
        public integer getid() {
            return id;
        }
    
        public void setid(integer id) {
            this.id = id;
        }
    
        public string getname() {
            return name;
        }
    
        public void setname(string name) {
            this.name = name;
        }
    
        public string getauthor() {
            return author;
        }
    
        public void setauthor(string author) {
            this.author = author;
        }
    }
    
  • 创建bookrepository

    public interface bookrepository extends jparepository<book, integer> {
    
    }
    
  • jparepository

    //
    // source code recreated from a .class file by intellij idea
    // (powered by fernflower decompiler)
    //
    
    package org.springframework.data.jpa.repository;
    
    import java.util.list;
    import org.springframework.data.domain.example;
    import org.springframework.data.domain.sort;
    import org.springframework.data.repository.norepositorybean;
    import org.springframework.data.repository.pagingandsortingrepository;
    import org.springframework.data.repository.query.querybyexampleexecutor;
    
    @norepositorybean
    public interface jparepository<t, id> extends pagingandsortingrepository<t, id>, querybyexampleexecutor<t> {
        list<t> findall();
    
        list<t> findall(sort var1);
    
        list<t> findallbyid(iterable<id> var1);
    
        <s extends t> list<s> saveall(iterable<s> var1);
    
        void flush();
    
        <s extends t> s saveandflush(s var1);
    
        void deleteinbatch(iterable<t> var1);
    
        void deleteallinbatch();
    
        t getone(id var1);
    
        <s extends t> list<s> findall(example<s> var1);
    
        <s extends t> list<s> findall(example<s> var1, sort var2);
    }
    


测试

【在进行这个节点测试之前,需要把代码的其他部分注释掉,之后会有一些自定义的功能】


在数据库添加几条测试数据

SpringBoot集成JPA

打开postman,输入http://localhost:8080/books

【默认请求路径都是实体类名小写加s】

SpringBoot集成JPA

按照id查询

SpringBoot集成JPA

自定义请求路径

/**
 * 默认请求路径都是实体类名加s
 *
 * 自定义请求类名:
 * @repositoryrestresource (path = "bs",collectionresourcerel = "bs",itemresourcerel = "b")
 * path属性指用bs替代原先的books,collectionresourcerel表示将返回的json集合中的book集合改为bs,
 * itemresourcerel表示将单个book的key改为b
 */
@repositoryrestresource(path = "bs",collectionresourcerel = "bs",itemresourcerel = "b")
public interface bookrepository extends jparepository<book, integer> {

访问:http://localhost:8080/bs

SpringBoot集成JPA

自定义查询方法

     /**@restresource注解定义:默认请求路径就是方法名,path可自定义路径
     * http://localhost:8080/bs/search/author?author=余华
     * http://localhost:8080/bs/search/name?name=白夜行
     * @param author
     * @return
     */
    @restresource(path = "author",rel = "author")
    list<book> findbyauthorcontains(@param("author") string author);
    @restresource(path = "name",rel = "name")
    book findbynameequals(@param("name") string name);

SpringBoot集成JPA


代码参考

https://github.com/hcj-shadow/springbootplus