Optional casting issues with Spring JPARepository

I seem to be having the most obnoxious problem, I have a repository defined as follows:

@Repository public interface PropertyRepository extends JpaRepository<Property, Long> {} 

And I have a service as follows:

@Component("PropertyService") public class PropertyServiceImpl implements PropertyService {     @Autowired     private PropertyRepository repository;      public Optional<Property> findOne(Long id) {         return Optional.of(repository.findOne(id));     } } 

If I run that code, I get the following error on any line where I attempt to access the value from the optional, e.g. myOptional.get().

java.lang.ClassCastException: java.util.Optional cannot be cast to Property

I don't understand that as Optional is a generic. So just to test, if I then change the service method implementation to:

Property property = repository.findOne(id); return Optional.empty(); 

I get the same error on the first line. The findOne repo method is not returning an optional, so I don't understand that at all. If I change it to:

Optional<Property> property = repository.findOne(id); 

I then get:

Error:(14, 57) java: incompatible types: Property cannot be converted to java.util.Optional

Which is what id expect, as the repo isn't returning an Optional - but that leaves me confused on why it was complaining in the previous state.

Furthermore, if I just return a manually created Property instance from the service method, my app works as expected, and it also works as expected if I just return Optional.empty(). So it seems the issue is with the JPA Repository somehow.

Perhaps my assumptions on how this should be working are just flawed. Any help or pointers much appreciated.


Category: java Time: 2016-07-29 Views: 1

Related post

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development


Front-end development


development tools

Open Platform

Javascript development

.NET development

cloud computing


Copyright (C) avrocks.com, All Rights Reserved.

processed in 0.152 (s). 12 q(s)