簡體   English   中英

Java Spring Rest Api 自定義存儲庫

[英]Java Spring Rest Api Custom Repository

所以我有一個學生 class @Table(name = "student") public class Student {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private String firstname;
private String lastname;
private String idnumber;
private String adress;
private boolean active=Boolean.TRUE;
@OneToMany( mappedBy="student")
private Set<Contact> contacts = new HashSet<>();
@ManyToMany(mappedBy = "students")
private Set<Team> teams = new HashSet<>();

} 我有存儲庫

public interface StudentRepository extends JpaRepository<Student,Long> { } 我想創建 customrepository 來查找學生 idnumber,並且在創建新學生時它將檢查所有學生 idnumber 是否已經存在拋出異常。

無需創建新的 repo 作為 customrepository 來實現自定義查詢。 您可以編寫一個新方法來檢索數據。

public interface StudentRepository extends JpaRepository<Student, Long> {

    // using JPA method
    Optional<Student> findByIdnumber(String idNumber);

    // using JPA query | this is an optional method in case you need to implement any query in future
    // ?1 represents the first parameter of the method, which is 'idNumber'
    @Query(value = "SELECT s.id FROM Student s WHERE s.idnumber=?1", nativeQuery = true)
    String findIdByIdnumber(String idNumber);
}

通過該服務,您可以檢查記錄是否可用並執行相應的操作(拋出異常)。

您可以使用 jpa 存儲庫方法

studentRepo.findById(studentId)

使用 studentId 在數據庫中獲取記錄。 如果你想讓它找到記錄是否存在,你可以讓方法返回 null 並檢查 object 是否為 null 並拋出適當的異常。 就像下面的例子一樣。

Student student = studentRepo.findById(studentId).orElse(null);
if(student == null)
     throw new CustomException("student does not exist");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM