SpringBoot集成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);
    }
    
    

测试

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


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

1569215934648

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

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

1569215981164

按照id查询

1569216056599

自定义请求路径

/**
 * 默认请求路径都是实体类名加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

1569216323418

自定义查询方法

     /**@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);

1569217053731


posted @ 2019-09-23 14:10  笑谈渴饮匈奴血  阅读(456)  评论(0编辑  收藏  举报