简体   繁体   中英

JPA repository method findByField returns all data

I'm new with Spring Boot. I try to develop a simple CRUD app using Spring Boot for the backend. I have some issues with the methods in JPA repository. Only one method works, the others return all data, as findAll() does.

when I try http://localhost:8080/api/professeurs?nom=CHRAYAH it works and returns the correct row.

But when I try http://localhost:8080/api/professeurs?prenom=Yassine it returns all rows.

So, only profRepository.findByNom() works, but profRepository.findByPrenom() and other methods don't.

This is my code

ProfRepository

package com.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import com.model.Professeur;

@Repository
public interface ProfRepository  extends JpaRepository<Professeur, Long> {
    
      List<Professeur> findByNom(String name);
      @Query("SELECT p FROM Prof p where p.prenom=?1")
      List<Professeur> findByPrenom(String prenom);
      List<Professeur> findByEmail(String email);
      List<Professeur> findByNomContaining(String name);
      
}

Professeur.java (model)

package com.model;

import javax.persistence.*;

@Entity(name="Prof")
@Table(name = "professeurs") 

public class Professeur {
    
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @Column(name = "nom"  )
    private String nom;

    @Column(name = "prenom")
    private String prenom;

    @Column(name = "email")
    private String email;

    @Column(name = "password")
    private String password;

    @Column(name = "cours")
    private String cours;



    public Professeur() {

    }


    public Professeur(String nom, String prenom, String email, String password, String cours) {
        this.nom = nom;
        this.prenom= prenom;
        this.email = email;
        this.password = password;
        this.cours = cours;
    }

    public long getId() {
        return id;
    }

    public String getNom() {
        return nom;
    }

    public void setNom(String nom) {
        this.nom = nom;
    }

    public String getPrenom() {
        return prenom;
    }

    public void setPrenom(String prenom) {
        this.prenom = prenom;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
    
    public String getCours() {
        return this.cours;
    }

    public void setCours(String cours) {
        this.cours = cours;
    }


    @Override
    public String toString() {
        return "Professeur [id=" + id + ", nom=" + nom+ ", prenom=" + prenom + ", cours=" + cours + ", email=" + email + "]";
    }
}

ProfesseurController

package com.controller;


import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


import  com.model.Professeur;

import com.repository.AppRepository;

import com.repository.ProfRepository;

@CrossOrigin(origins = "http://localhost:4200")
@RestController
@RequestMapping("/api")

public class ProfesseurController {
    
    

      @Autowired
      ProfRepository profRepository;
      @GetMapping("/professeurs")
      public ResponseEntity<List<Professeur>> getAllProfs(@RequestParam(required = false) String nom) {
            try {
              List<Professeur> professeurs = new ArrayList<Professeur>();

              if (nom == null)
               profRepository.findAll().forEach(professeurs::add);
              else
                  profRepository.findByNomContaining(nom).forEach(professeurs::add);

              if (professeurs.isEmpty()) {
                return new ResponseEntity<>(HttpStatus.NO_CONTENT);
              }

              return new ResponseEntity<>(professeurs, HttpStatus.OK);
            } catch (Exception e) {
              return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
            }
          }
    
      
      @GetMapping("/professeurs/{id}")
      public ResponseEntity<Professeur> getProfById(@PathVariable("id") long id) {
        Optional<Professeur> profData = profRepository.findById(id);

        if (profData.isPresent()) {
          return new ResponseEntity<>(profData.get(), HttpStatus.OK);
        } else {
          return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
      }
     
      
      
      @PostMapping("/professeurs")
      public ResponseEntity<Professeur> createProf(@RequestBody Professeur professeur) {
        try {
            Professeur _professeur = profRepository
              .save(new Professeur (professeur.getNom(), professeur.getPrenom(), professeur.getEmail(),professeur.getPassword(), professeur.getCours()));
          return new ResponseEntity<>(_professeur, HttpStatus.CREATED);
        } catch (Exception e) {
          return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
        }
      }
      
      
      
      
      @PutMapping("/professeurs/{id}")
      public ResponseEntity<Professeur> updateProf(@PathVariable("id") long id, @RequestBody Professeur professeur) {
        Optional<Professeur> profData = profRepository.findById(id);

        if (profData.isPresent()) {
            Professeur _professeur = profData.get();
            _professeur.setNom(professeur.getNom());
            _professeur.setPrenom(professeur.getPrenom());
            _professeur.setEmail(professeur.getEmail());
            _professeur.setPassword(professeur.getPassword());
            _professeur.setCours(professeur.getCours());
          return new ResponseEntity<>(profRepository.save(_professeur), HttpStatus.OK);
        } else {
          return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
      }
      
      
      
      @DeleteMapping("/professeurs/{id}")
      public ResponseEntity<HttpStatus> deleteProf(@PathVariable("id") long id) {
        try {
        profRepository.deleteById(id);
          return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        } catch (Exception e) {
          return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
      }
      
      
      @DeleteMapping("/professeurs")
      public ResponseEntity<HttpStatus> deleteAllEleves() {
        try {
         profRepository.deleteAll();
          return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        } catch (Exception e) {
          return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }

      }
      
      
      
      
      
      @GetMapping("/professeurs/nom")
      public ResponseEntity<List<Professeur>> findByNom(@PathVariable("nom") String nom) {
        try {
          List<Professeur> professeurs = profRepository.findByNom(nom);

          if (professeurs .isEmpty()) {
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
          }
          return new ResponseEntity<>(professeurs , HttpStatus.OK);
        } catch (Exception e) {
          return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
      }

      
      @GetMapping("/professeurs/email")
      public ResponseEntity<List<Professeur>> findByEmail(@PathVariable("email") String email) {
        try {
          List<Professeur> professeurs = profRepository.findByEmail(email);

          if (professeurs .isEmpty()) {
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
          }
          return new ResponseEntity<>(professeurs , HttpStatus.OK);
        } catch (Exception e) {
          return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
      }
      
      
      
      @GetMapping("/professeurs/prenom")
      public ResponseEntity<List<Professeur>> findByPrenom(@PathVariable("prenom") String prenom) {
        try {
          List<Professeur> professeurs = profRepository.findByPrenom(prenom);

          if (professeurs .isEmpty()) {
              System.out.println("pas de prof avec ce nom");
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
          }
          return new ResponseEntity<>(professeurs , HttpStatus.OK);
        } catch (Exception e) {
          return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
      }
}

I just found out that I should change @GetMapping("/professeurs/prenom") to @GetMapping("/professeurs/prenom/{prenom}")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM