1. 程式人生 > >SpringBoot 使用JPA操作資料庫

SpringBoot 使用JPA操作資料庫

Spring-data-jpa的出現使我們不需要編寫sql語句就能實現對資料庫簡單的增刪改查,使用也非常方便

第一步:編寫一個繼承自JpaRepository的介面就能完成資料訪問

import com.oldbig.domain.Girl;
import org.springframework.data.jpa.repository.JpaRepository;


public interface GirlRepository extends JpaRepository<Girl,Integer>{

}

第二步:在pom.xml中新增相關依賴:

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

第三步:配置我們的資料庫
在application.xml中配置:

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource
.driver-class-name=com.mysql.jdbc.Driver jpa.hibernate.ddl-auto=update

這裡的jpa配置為hibernate的配置屬性,這是由於jpa封裝了hibernate的緣故,jpa.hibernate.ddl-auto有以下屬性:
create:每次載入hibernate時都會刪除上一次的生成的表,然後根據你的model類再重新來生成新表,哪怕兩次沒有任何改變也要這樣執行,這就是導致資料庫表資料丟失的一個重要原因。
create-drop:每次載入hibernate時根據model類生成表,但是sessionFactory一關閉,表就自動刪除。
update:最常用的屬性,第一次載入hibernate時根據model類會自動建立起表的結構(前提是先建立好資料庫),以後載入hibernate時根據model類自動更新表結構,即使表結構改變了但表中的行仍然存在不會刪除以前的行。要注意的是當部署到伺服器後,表結構是不會被馬上建立起來的,是要等應用第一次執行起來後才會。
validate:每次載入hibernate時,驗證建立資料庫表結構,只會和資料庫中的表進行比較,不會建立新表,但是會插入新值。

第四步:建立實體類(對應我們的資料庫中的表,裡面的例項代表我們表中的行,必須要有@Entity註解,必須要有唯一主鍵)

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.Min;

@Entity
public class Girl {
    @Id
    @GeneratedValue //自增
    private Integer id ;

    private String cupSize;
    @Min(value = 18,message = "未成年少女禁止入內")
    private Integer age;

    // 省略建構函式

    // 省略getter和setter
}

這樣點選執行專案,就會自動幫我們建立好對應的表
這裡寫圖片描述

就能通過我們的資料庫介面類GirlRepository來訪問我們的資料庫,這裡在service通過@Autowired將其注入,就能直接操作資料庫了:

@Service
public class GirlService {
    @Autowired
    private GirlRepository girlRepository;

    public Integer getAge(Integer id) throws Exception{
        Girl girl = girlRepository.findOne(id);
        Integer age = girl.getAge();

        return age;

    }
}

拓展:
一,拓展資料訪問介面類的方法:

public interface GirlRepository extends JpaRepository<Girl,Integer>{
    //通過年齡來查詢
    List<Girl> findByAge(Integer age);
    //通過年齡和cupSize
    List<Girl> findByAgeAndCupSize(Integer age,String cupSize);
    //通過年齡或者cupSize
    List<Girl> findByAgeOrCupSize(Integer age,String cupSize);
    //啟用order by
    List<Girl> findByAgeOrderByCupSize(Integer age)
    //啟用 distinct 標誌,消除重複匹配到的資料
     List<Girl> findDistinctByAgeOrCupSize(Integer age)


 }