I am new to the concept of type casting and Spring in Java.
I have below entities:
@MappedSuperclass
public class Fish {}
@Entity
public class Whale extends Fish{
// There is no other property here..
}
@Entity
public class Shark extends Fish{
// There is no other property here..
}
I have created corresponding repositories for these entity:
public interface WhaleRepository extends CrudRepository<Whale, String> {}
public interface SharkRepository extends CrudRepository<Whale, String> {}
I have a single controller where depending on the endpoint I want to save the data ..
@RestController
public class FishController {
@ResponseBody
@RequestMapping(value = "{fish-type}")
public ResponseEntity<Long> create(@PathVariable("fish-type") String fishType, @RequestBody Fish fish){
if(fishType.equals("whale"}{
// Error: The method save(S) in the type CrudRepository<Whale,Long> is not applicable for the arguments (Fish)
new WhaleRepository().save(fish);
}
else if(fishType.equals("shark"}{
// Error: The method save(S) in the type CrudRepository<Shark,Long> is not applicable for the arguments (Fish)
new SharkRepository().save(fish);
}
}
}
Is there a way by which I can dynamically pick the repository and persist the data.