SpringDataJPA筆記(3)-基於SpringBoot基礎用法

基於SpringBoot的基礎用法

STEP1. 引入POM依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

這裏有一個使用Specification查詢時很好用的工具包,感謝做工具包的同學

<!-- https://mvnrepository.com/artifact/com.github.wenhao/jpa-spec -->
<dependency>
    <groupId>com.github.wenhao</groupId>
    <artifactId>jpa-spec</artifactId>
	<version>3.2.4</version>
</dependency>

STEP2. 配置文件application.yml

spring:
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true #打印sql語句,方便調試
    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect #設置數據庫引擎爲InnoDB
    properties:
      hibernate:
        format-sql: true #是否格式化輸出字符串,增強SQL的可讀性 

STEP3. 實體類

這裏寫了一個抽象實體類和兩個具體的實體類

抽象類

AnimalEntity.java

@Data
@EqualsAndHashCode(callSuper = false)
@MappedSuperclass
public abstract class AnimalEntity<ID> implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private ID id;


    @Temporal(TemporalType.TIMESTAMP)
    @CreationTimestamp
    @Column(name = "gmt_create", nullable = false, updatable = false)
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    protected Date gmtCreate;

    @Temporal(TemporalType.TIMESTAMP)
    @UpdateTimestamp
    @Column(name = "gmt_update", nullable = true, insertable = false)
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @JSONField
    protected Date gmtUpdate;

    private String name;

    private Integer age;

    private String sex;

    private Integer height;

    private Integer weight;

    private Long pid;

}

實際會對應數據庫表的實體類

CatEntity.java

@Data
@Entity
@Table(name = "cat_tb")
@EqualsAndHashCode(callSuper = false)
public class CatEntity extends AnimalEntity<Long> {


    private static final long serialVersionUID = 7456065103323391049L;

    private String miao;
}

DogEntity.java

@Data
@Entity
@Table(name = "dog_tb")
@EqualsAndHashCode(callSuper = false)
public class DogEntity extends AnimalEntity<Long> {


    private static final long serialVersionUID = 7456065103323391049L;

    private String wang;
}

STEP4. repository類

同樣寫了一個base類和兩個對應的操作類

@NoRepositoryBean
public interface BaseRepository<T, ID extends Serializable> extends JpaRepository<T, ID>, JpaSpecificationExecutor<T>, Serializable {
}
public interface CatRepository extends BaseRepository<CatEntity, Long> {
}
public interface DogRepository extends BaseRepository<DogEntity, Long> {
}

然後寫一個測試的controller來測試

這是幾個基礎的單表查詢

ChapterThreeController

 @ApiOperation(value = "獲取所有的貓", httpMethod = "GET")
    @GetMapping("/find/cat")
    public List<CatEntity> findCat() {
        return catRepository.findAll();
    }

    @ApiOperation(value = "findById", httpMethod = "GET")
    @GetMapping("/find/cat/{id}")
    public CatEntity findOneCatById(@PathVariable Long id) {
        return catRepository.findById(id).orElse(null);
    }

    @ApiOperation(value = "分頁查詢", httpMethod = "GET")
    @GetMapping("/find/cat/page")
    public Page<CatEntity> findCatByPage(@RequestParam int pageSize, @RequestParam int pageNum) {
        Pageable pageable = PageRequest.of(pageNum, pageSize);
        return catRepository.findAll(pageable);
    }

    @ApiOperation(value = "分頁排序查詢", httpMethod = "GET")
    @GetMapping("/find/cat/order")
    public Page<CatEntity> findCatByPageOrder(@RequestParam int pageSize, @RequestParam int pageNum) {
        Pageable pageable = PageRequest.of(pageNum, pageSize, new Sort(Sort.Direction.DESC, "id"));
        return catRepository.findAll(pageable);
    }

    @ApiOperation(value = "分頁條件查詢", httpMethod = "GET")
    @GetMapping("/find/cat/search")
    public Page<CatEntity> findCatByPageOrder(@RequestParam int pageSize, @RequestParam int pageNum, @RequestParam String miao) {
        Pageable pageable = PageRequest.of(pageNum, pageSize, new Sort(Sort.Direction.DESC, "id"));
        Specification<CatEntity> specification = Specifications.<CatEntity>and().eq(!StringUtils.isEmpty(miao), "miao", miao).build();
        return catRepository.findAll(specification, pageable);
    }

源碼參考 GITHUB
歡迎關注微信交流
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章