Home > Software design >  Java Spring Rest Api Custom Repository
Java Spring Rest Api Custom Repository

Time:01-17

So i have a student 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<>();

} and i have repository

public interface StudentRepository extends JpaRepository<Student,Long> { } i want to create customrepository to find student idnumber, and while creating new student it will check all students if idnumber already exists throw exception.

CodePudding user response:

You can use the jpa repository method

studentRepo.findById(studentId)

To fetch a record in the database with the studentId. If you want it to find the record exists or not you can make the method return null and check whether the object is null or not and throw the appropriate exception. Like in the below example.

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

CodePudding user response:

No need to create a new repo as customrepository to implement custom query. You can write a new method to retrieve data.

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);
}

Through the service you can check whether a record is available or not and perform a respective action (throw an exception).

  • Related