Home > OS >  Provided id of the wrong type for class com.demo.model.Condidat. Expected: class com.demo.model.Cond
Provided id of the wrong type for class com.demo.model.Condidat. Expected: class com.demo.model.Cond

Time:03-28


Composite class

@AllArgsConstructor
@NoArgsConstructor
public class CandidatKey implements Serializable {
private static final long serialVersionUID = 1L;
@Setter
@Getter
private long id;
@Setter
@Getter
private String cin;
}

Candidat

@Entity
@Table(name = "candidat")
@AllArgsConstructor
@NoArgsConstructor
@IdClass(CandidatKey.class)
public class Candidat {
@Getter
@Setter
@GeneratedValue(strategy = GenerationType.IDENTITY)
 private long id;
@Getter
@Setter
@Column(name="cin")
@Id private String cin;
}

Controller:

 @CrossOrigin
 @RestController
 @RequestMapping("/api/v1/")
 public class CandidatController {
 @Autowired
private CandidatRepository candidatRepository;

@GetMapping("/candidats")
public List<Candidat> getAllCandidats(){
    return candidatRepository.findAll();
}
@GetMapping("/candidat/{id}")
public Optional<Candidat> getCandidat(@PathVariable("id") Long id) {
    return candidatRepository.findById(id);
}

im getting this error in http://localhost:8080/api/v1/candidat/1 :

ERROR 11716 --- [nio-8080-exec-7] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: Provided id of the wrong type for class com.example.demo.model.Condidat. Expected: class com.example.demo.model.CondidatKey, got class java.lang.Long; nested exception is java.lang.IllegalArgumentException: Provided id of the wrong type for class com.example.demo.model.Condidat. Expected: class com.example.demo.model.CondidatKey, got class java.lang.Long] with root cause

CodePudding user response:

Id of your Candidat entity is defined as a composite key of CandidateKey class. So findById method expects object of this type as a parameter, while the controller provides Long value passed as url variable.

CodePudding user response:

     public interface CondidatRepository extends 
     JpaRepository<Condidat, CondidatKey>{    {
     @Query(value = "select * from candidat c where c.cin 
     =? 
     1", nativeQuery = true)
     Optional<Condidat> findCondidat(@Param("cin") 
     String cin);  
}
  • Related