Reproducing Spring Data Rest search controllers in Spring Boot 2.3 - java

Until Spring Boot 2.0, I could reproduce the controllers generated for query methods exposed by a mongodb repository.
Here is a code sample:
Domain Entity
#Document(collection = "foos")
public class Foo {
#Id
private String id;
private String name;
// getters/setters omitted
}
Mongo repository
public interface FooRepository extends MongoRepository<Foo, String> {
public Page<Foo> findByName(#Param("name") String name, Pageable pageable);
}
Spring Boot automatically exposes the search method through /foos/search/findByName?name=... with a result similar to this:
{
"_embedded" : {
"foos" : [ {
"name" : "qc",
"_links" : {
"self" : {
"href" : "http://localhost:8080/foos/56a8a8d5daffd28c9c907974"
},
"foo" : {
"href" : "http://localhost:8080/foos/56a8a8d5daffd28c9c907974"
}
}
} ]
},
"_links" : {
"self" : {
"href" : "http://localhost:8080/foos/search/findByName?name=qc&page=0&size=20"
}
},
"page" : {
"size" : 20,
"totalElements" : 1,
"totalPages" : 1,
"number" : 0
}
}
I could reproduce it with the following custom controller and configuration
#RestController
#RequestMapping("foos")
#RequiredArgsConstructor // lombok
public class FooQueryController {
private final FooRepository repository;
private final PagedResourcesAssembler pagedResourcesAssembler;
#GetMapping(value = "search/query",
produces = MediaType.APPLICATION_JSON_UT8_VALUE)
public ResponseEntity custom(#RequestParam("name") String name,
Pageable pageable,
PersistentEntityResourceAssembler resourceAssembler) {
var page = repository.findByName(name, pageable);
var model = pagedResourcesAssembler.toResource(page, resourceAssembler);
return ResponseEntity.ok(model);
}
}
// Enables injecting a PersistentEntityResourceAssembler in a RestController
// see https://jira.spring.io/browse/DATAREST-657 for details
#Configuration
#Order(Ordered.HIGHEST_PRECEDENCE)
#RequiredArgsConstructor
public class MvcConfiguration implements WebMvcConfigurer {
// WARNING: do NOT change the name of this member - it is injected with the
// RequestMappingHandlerAdapter$repositoryExporterHandlerAdapter().
private final RequestMappingHandlerAdapter repositoryExporterHandlerAdapter;
#Override
public void addArgumentResolvers(
List<HandlerMethodArgumentResolver> argumentResolvers) {
List<HandlerMethodArgumentResolver> customArgumentResolvers =
repositoryExporterHandlerAdapter.getCustomArgumentResolvers();
argumentResolvers.addAll(customArgumentResolvers);
}
}
With this I can send a request to /foos/search/query?name=... and get the expected response:
{
"_embedded" : {
"foos" : [ {
"name" : "qc",
"_links" : {
"self" : {
"href" : "http://localhost:8080/foos/56a8a8d5daffd28c9c907974"
},
"foo" : {
"href" : "http://localhost:8080/foos/56a8a8d5daffd28c9c907974"
}
}
} ]
},
"_links" : {
"self" : {
"href" : "http://localhost:8080/foos/search/query?name=qc&page=0&size=20"
}
},
"page" : {
"size" : 20,
"totalElements" : 1,
"totalPages" : 1,
"number" : 0
}
}
Switching to Spring Boot 2.3, using the Spring HATEOAS 1.0 API in the controller
#RestController
#RequestMapping("foos")
#RequiredArgsConstructor
public class FooQueryController {
private final FooRepository repository;
private final PagedResourcesAssembler pagedResourcesAssembler;
#GetMapping(value = "search/query",
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity custom(#RequestParam("name") String name,
Pageable pageable,
PersistentEntityResourceAssembler resourceAssembler) {
var page = repository.findByName(name, pageable);
var model = pagedResourcesAssembler.toModel(page, resourceAssembler);
return ResponseEntity.ok(model);
}
}
I now get the following result:
{"_embedded":{"foos":[{"id":"56a8a8d5daffd28c9c907974","name":"qc","embeddeds":{},"nested":false,"persistentEntity":{"idProperty":{"name":"id","rawType":"java.lang.String","association":false,"owner":{"idProperty":{"name":"id","rawType":"java.lang.String","association":false,"owner":{"idProperty":{"name":"id","rawType":"java.lang.String","association":false,"owner":{"idProperty":{"name":"id","rawType":"java.lang.String","association":false,"owner":{"idProperty":{"name":"id","rawType":"java.lang.String","association":false,"owner":{"idProperty":{"name":"id","rawType":"java.lang.String","association":false,"owner":{"idProperty":{"name":"id","rawType":"java.lang.String","association":false,"owner":{"idProperty":{"name":"id","rawType":"java.lang.String","association":false,"owner":{"idProperty":{"name":"id","rawType":"java.lang.String","association":false,"owner":{"idProperty":{"name":"id","rawType":"java.lang.String","association":false,"owner":{"idProperty":
With the following errors in Spring's log:
2020-08-06 18:11:20.968 WARN 9932 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Failure while trying to resolve exception [org.springframework.http.converter.HttpMessageNotWritableException]
java.lang.IllegalStateException: Cannot call sendError() after the response has been committed
at org.apache.catalina.connector.ResponseFacade.sendError(ResponseFacade.java:472) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver.sendServerError(DefaultHandlerExceptionResolver.java:550) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver.handleHttpMessageNotWritable(DefaultHandlerExceptionResolver.java:440) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver.doResolveException(DefaultHandlerExceptionResolver.java:210) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.resolveException(AbstractHandlerExceptionResolver.java:141) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.handler.HandlerExceptionResolverComposite.resolveException(HandlerExceptionResolverComposite.java:80) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.processHandlerException(DispatcherServlet.java:1300) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1111) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1057) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:626) ~[tomcat-embed-core-9.0.37.jar:4.0.FR]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733) ~[tomcat-embed-core-9.0.37.jar:4.0.FR]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.37.jar:9.0.37]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1589) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]
2020-08-06 18:11:20.979 ERROR 9932 --- [nio-8080-exec-1] 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.http.converter.HttpMessageNotWritableException: Could not write JSON: Infinite recursion (StackOverflowError); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: org.springframework.data.mongodb.core.mapping.CachingMongoPersistentProperty["owner"]->org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity["idProperty"]->org.springframework.data.mongodb.core.mapping.CachingMongoPersistentProperty["owner"]->org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity["idProperty"]->org.springframework.data.mongodb.core.mapping.CachingMongoPersistentProperty["owner"]->org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity["idProperty"]->org.springframework.data.mongodb.core.mapping.CachingMongoPersistentProperty["owner"]->org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity["idProperty"]->org.springframework.data.mongodb.core.mapping.CachingMongoPersistentProperty["owner"]->org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity["idProperty"]-> ... IT GOES ON AND ON LIKE THIS ... ->org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity["idProperty"])] with root cause
java.lang.StackOverflowError: null
at java.base/java.lang.ClassLoader.defineClass1(Native Method) ~[na:na]
at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016) ~[na:na]
at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:174) ~[na:na]
at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:800) ~[na:na]
at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:698) ~[na:na]
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:621) ~[na:na]
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:579) ~[na:na]
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178) ~[na:na]
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521) ~[na:na]
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:773) ~[jackson-databind-2.11.1.jar:2.11.1]
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:178) ~[jackson-databind-2.11.1.jar:2.11.1]
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:728) ~[jackson-databind-2.11.1.jar:2.11.1]
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:755) ~[jackson-databind-2.11.1.jar:2.11.1]
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:178) ~[jackson-databind-2.11.1.jar:2.11.1]
... IT GOES ON LIKE THIS FOR DOZENS AND DOZENS OF LINE
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:728) ~[jackson-databind-2.11.1.jar:2.11.1]
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:755) ~[jackson-databind-2.11.1.jar:2.11.1]
2020-08-06 18:11:21.553 ERROR 9932 --- [nio-8080-exec-1] s.e.ErrorMvcAutoConfiguration$StaticView : Cannot render error page for request [/foos/search/query] and exception [] as the response has already been committed. As a result, the response may have the wrong status code.
If if return the contents of var page = repository.findByName(name, pageable); instead of var model = pagedResourcesAssembler.toModel(page, resourceAssembler);, I get the following result:
{"content":[{"id":"56a8a8d5daffd28c9c907974","name":"qc"}],"pageable":{"sort":{"sorted":false,"unsorted":true,"empty":true},"offset":0,"pageNumber":0,"pageSize":20,"paged":true,"unpaged":false},"last":true,"totalPages":1,"totalElements":1,"size":20,"number":0,"sort":{"sorted":false,"unsorted":true,"empty":true},"numberOfElements":1,"first":true,"empty":false}
So the circular mess comes from the serialization pagedResourcesAssembler.toModel(page, resourceAssembler) (and probably the WebMvcConfigurer override).

I had the same StackOverflowError: null when I call PersistentEntityResourceAssembler.toModel(Object). My code returns a single EntityModel instead of a PagedModel. My problem is solved by switching to PersistentEntityResourceAssembler.toFullResource(Object).
The toModel(Object) uses excerpt projection while toFullResource(Object) does not. I don't have time to dig into the code to check what produces an infinite loop to cause stack overflow.
Look at the source code of PagedResourcesAssembler, PagedResourcesAssembler.toModel(Page, RepresentationModelAssembler) calls RepresentationModelAssember.toModel(Object).
So workaround 1 is copying the source code of PagedResourcesAssembler.toModel(Page, RepresentationModelAssembler) and use RepresentationModelAssember.toFullResource(Object).
Workaround 2 is extending the PagedResourcesAssembler and overriding the createModel(...) method.
Before making the workaround, I have one question. Why do you pass a PersistentEntityResourceAssembler to PagedResourcesAssembler? My code uses PersistentEntityResourceAssembler to add HTTP headers ETag and Last-Modified when my custom controller returns a single resource. What good does it have to use PersistentEntityResourceAssembler to build the response of a collection resource (paged resource)?

Thanks to this thread on Spring JIRA, I was able to:
convert the controller MultiValueMap parameters to a Predicate
use a RepositoryRestController instead of a RestController, ie be able to inject a PersistentEntityResourceAssembler into the controller method.
Custom models and models assembler, as suggested in the accepted answer, are not necessary.
Configure a QuerydslPredicateBuilder bean:
#Configuration
#RequiredArgsConstructor
public class QueryDslConfiguration {
private final ConversionService mvcConversionService;
private final QuerydslBindingsFactory querydslBindingsFactory;
#Bean
public QuerydslPredicateBuilder querydslPredicateBuilder() {
return new QuerydslPredicateBuilder(mvcConversionService, querydslBindingsFactory.getEntityPathResolver());
}
}
A service to convert a MultiValueMap to a Predicate:
#Service
#RequiredArgsConstructor(onConstructor = #__(#Autowired))
public class PredicateService {
private final QuerydslPredicateBuilder querydslPredicateBuilder;
private final QuerydslBindingsFactory querydslBindingsFactory;
public <T> Predicate getPredicateFromParameters(final MultiValueMap<String, String> parameters, Class<T> tClass) {
TypeInformation<T> typeInformation = ClassTypeInformation.from(tClass);
return querydslPredicateBuilder.getPredicate(typeInformation,
parameters,
querydslBindingsFactory.createBindingsFor(typeInformation));
}
}
Use the converter in a controller:
#RepositoryRestController
#RequiredArgsConstructor
public class FooController {
private final FooRepository repository;
private final PredicateService predicateService;
#GetMapping("/foos/search/query")
public PagedModel<Foo> query(
#RequestParam MultiValueMap<String, String> parameters,
Pageable pageable,
PersistentEntityResourceAssembler resourceAssembler) {
Predicate predicate = predicateService.getPredicateFromParameters(parameters, Foo.class);
Page<Parameter> page = repository.findAll(predicate,
return pagedResourcesAssembler.toModel(page, resourceAssembler);
}
}

Related

issue with consuming restful webservice from openweather Api?

i was trying to retreive weather details from openweathermap api , some how i am not able to get it working with below errors . Any help would be highly appreciated
Controller
#Controller
public class CurrentWeatherController {
private final StubWeatherService stubWeatherService;
private final LiveWeatherService liveWeatherService;
public CurrentWeatherController(StubWeatherService stubWeatherService, LiveWeatherService liveWeatherService) {
this.stubWeatherService = stubWeatherService;
this.liveWeatherService = liveWeatherService;
}
#GetMapping("/current-weather")
public String getCurrentWeather(Model model) {
model.addAttribute("currentWeather", liveWeatherService.getCurrentWeather("Detroit","us"));
return "current-weather";
}
public StubWeatherService getStubWeatherService() {
return stubWeatherService;
}
service code
#Service
public class LiveWeatherService {
private static final String WEATHER_URL = "http://api.openweathermap.org/data/2.5/weather?q={city},{country}&APPID={key}&units=metric";
private final String apiKey="526a647fcd4f3f465c0340c19d26ef3a";
private final RestTemplate restTemplate;
private final ObjectMapper objectMapper;
public LiveWeatherService(RestTemplateBuilder restTemplateBuilder, ObjectMapper objectMapper) {
this.restTemplate = restTemplateBuilder.build();
this.objectMapper = objectMapper;
}
public CurrentWeather getCurrentWeather(String city, String country) {
URI url = new UriTemplate(WEATHER_URL).expand(city, country,this.apiKey); // line 34 issue with accepting apikey
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
return convert(response);
}
private CurrentWeather convert(ResponseEntity<String> response) {
try {
JsonNode root = objectMapper.readTree(response.getBody());
return new CurrentWeather(root.path("weather").get(0).path("main").asText(),
BigDecimal.valueOf(root.path("main").path("temp").asDouble()),
BigDecimal.valueOf(root.path("main").path("feels_like").asDouble()),
BigDecimal.valueOf(root.path("wind").path("speed").asDouble()));
} catch (JsonProcessingException e) {
throw new RuntimeException("Error parsing JSON", e);
}
}
}
error
2-07 02:34:48.710 ERROR 43384 --- [nio-8080-exec-3]
o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for
servlet [dispatcherServlet] in context with path [] threw exception
[Handler dispatch failed; nested exception is java.lang.Error:
Unresolved compilation problem:
Type mismatch: cannot convert from UriTemplate to URI
] with root cause
java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from UriTemplate to URI
at com.meshupProjekt.service.LiveWeatherService.getCurrentWeather(LiveWeatherService.java:34)
~[classes/:na]
at com.meshupProjekt.controller.CurrentWeatherController.getCurrentWeather(CurrentWeatherController.java:36)
~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:567) ~[na:na]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197)
~[spring-web-5.3.2.jar:5.3.2]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141)
~[spring-web-5.3.2.jar:5.3.2]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
~[spring-webmvc-5.3.2.jar:5.3.2]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894)
~[spring-webmvc-5.3.2.jar:5.3.2]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
~[spring-webmvc-5.3.2.jar:5.3.2]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
~[spring-webmvc-5.3.2.jar:5.3.2]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1061)
~[spring-webmvc-5.3.2.jar:5.3.2]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:961)
~[spring-webmvc-5.3.2.jar:5.3.2]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
~[spring-webmvc-5.3.2.jar:5.3.2]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
~[spring-webmvc-5.3.2.jar:5.3.2]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:626) ~[tomcat-embed-core-9.0.41.jar:4.0.FR]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
~[spring-webmvc-5.3.2.jar:5.3.2]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733) ~[tomcat-embed-core-9.0.41.jar:4.0.FR]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
~[tomcat-embed-core-9.0.41.jar:9.0.41]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
~[tomcat-embed-core-9.0.41.jar:9.0.41]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
~[tomcat-embed-websocket-9.0.41.jar:9.0.41]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
~[tomcat-embed-core-9.0.41.jar:9.0.41]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
~[tomcat-embed-core-9.0.41.jar:9.0.41]
at org.springframework.web.servlet.resource.ResourceUrlEncodingFilter.doFilter(ResourceUrlEncodingFilter.java:67)
~[spring-webmvc-5.3.2.jar:5.3.2]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
~[tomcat-embed-core-9.0.41.jar:9.0.41]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
~[tomcat-embed-core-9.0.41.jar:9.0.41]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
~[spring-
For me your code is working like this:
String WEATHER_URL = "http://api.openweathermap.org/data/2.5/weather?q={city},{country}&APPID={key}&units=metric";
String apiKey = "526a647fcd4f3f465c0340c19d26ef3a";
var x = new UriTemplate(WEATHER_URL).expand("Darmstadt", "Deutschland", apiKey);
System.out.println(x);
Instead of URI I used var so that Java selects proper type.
Your compilation error might be caused by wrong import of URI class.

[Java| SpringBoot]The Repository is not getting injected

I've been getting into Java again after some years only dealing with javascript and typescript, and I'm trying to get into Spring Boot.
It sounds really fun and convenient, but I'm trying to do something simple and for some reason I can't get my repository to get injected into my service. It sounds something really simple, but I've been digging for hours and can't get it to work.I'm wondering if some of you can help me to understand what I'm doing wrong ,please.
Thanks in advance
Projects (Entity)
package com.example.demo.modules.projects.entities;
import javax.persistence.*;
#Entity
#Table
public class Projects {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column
private String project_name;
#Column
private String description;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getProject_name() {
return project_name;
}
public void setProject_name(String project_name) {
this.project_name = project_name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
The Repository
package com.example.demo.modules.projects.repositories;
import com.example.demo.modules.projects.entities.Projects;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface IProjectRepository extends JpaRepository<Projects, Long> {
}
CreateProjectsService
package com.example.demo.modules.projects.services;
import com.example.demo.modules.projects.entities.Projects;
import com.example.demo.modules.projects.repositories.IProjectRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class CreateProjectService {
#Autowired
IProjectRepository iProjectRepository;
public Projects execute(Projects project){
System.out.println("Received " + project.toString());
Projects CreatedProject= this.iProjectRepository.save(project);
System.out.println("Created " + CreatedProject);
return CreatedProject;
}
}
The Error
It seems to not be injecting/instantiating correctly.
2020-10-09 00:56:08.774 ERROR 5856 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException: Cannot invoke "com.example.demo.modules.projects.repositories.IProjectRepository.save(Object)" because "this.iProjectRepository" is null] with root cause
java.lang.NullPointerException: Cannot invoke "com.example.demo.modules.projects.repositories.IProjectRepository.save(Object)" because "this.iProjectRepository" is null
at com.example.demo.modules.projects.services.CreateProjectService.execute(CreateProjectService.java:17) ~[classes/:na]
at com.example.demo.ServerApplication.newEmployee(ServerApplication.java:26) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:878) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:792) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:652) ~[tomcat-embed-core-9.0.38.jar:4.0.FR]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733) ~[tomcat-embed-core-9.0.38.jar:4.0.FR]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.38.jar:9.0.38]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630) ~[na:na]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.38.jar:9.0.38]
at java.base/java.lang.Thread.run(Thread.java:832) ~[na:na]
The issue is because you did not allow Spring to instantiate CreateProjectService and takes control of the bean, probably you instantiated the object with new CreateProjectService().
The recommended approach is to create an interface e.g. ICreateProjectService like below:
public interface ICreateProjectService {
Projects execute(Projects project);
}
And then implement ICreateProjectService in CreateProjectService like below:
#Service
public class CreateProjectService implements ICreateProjectService {
#Autowired
private IProjectRepository iProjectRepository;
#Override
public Projects execute(Projects project) {
System.out.println("Received " + project.toString());
Projects CreatedProject= this.iProjectRepository.save(project);
System.out.println("Created " + CreatedProject);
return CreatedProject;
}
}
Then in your Controller layer, as an example of the service usage, autowire your service by injecting the interface, like below:
#Restcontroller
#RequestMapping("/api/v1")
public class CreateProjectRest {
#Autowired
private ICreateProjectService iCreateProjectService;
#PostMapping
public Projects execute(Projects project) {
createProjectService.execute(project);
// your code here
}
}
Now Spring is able to recognize CreateProjectService as a concrete implementation, instantiates it as a Spring bean, keeps it in Spring container and make it available for Dependency Injection wherever injected.
Hope this helps out.
UPDATE:
It is more advisable to inject dependencies via constructor than field or setter method.
#Restcontroller
#RequestMapping("/api/v1")
public class CreateProjectRest {
private ICreateProjectService iCreateProjectService;
/* No needed to annotate #Autowired after Spring 4.3.*/
public CreateProjectRest(ICreateProjectService iCreateProjectService){
this.iCreateProjectService = iCreateProjectService;
}
#PostMapping
public Projects execute(Projects project) {
createProjectService.execute(project);
// your code here
}
}

org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private java.lang.Integer

I just tried out setting up a demo CRUD api in hibernate and I've been unable to resolve the issue with this. I've tried this with multiple versions of Hibernate but none seem to work. I keep getting the error message "Error accessing field [private java.lang.Integer com.webapp.firstwebapp.Models.UserModel.id] by reflection for persistent property [com.webapp.firstwebapp.Models.UserModel#id] : com.webapp.firstwebapp.Models.UserModel#1bc31512",
"path": "/create/user", but everything seems fine. Here's the code for it:
FirstWebApp.java
package com.webapp.firstwebapp;
import java.io.File;
import com.webapp.firstwebapp.Models.UserModel;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
#SpringBootApplication
#RestController
public class FirstwebappApplication {
public static void main(String[] args) {
SpringApplication.run(FirstwebappApplication.class, args);
}
#GetMapping("/create/user")
public UserModel doSomething() throws Exception{
File file = new File("hibernate.cfg.xml");
UserModel userModel = new UserModel(122, "Jane Doe", "jane_doe");
StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure(file).build();
SessionFactory sessionFactory = new MetadataSources(serviceRegistry).addAnnotatedClass(UserModel.class).buildMetadata().buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
try{
session.save(userModel);
transaction.commit();
}catch(Exception e){
System.out.println(e);
StandardServiceRegistryBuilder.destroy(serviceRegistry);
throw e;
}
return userModel;
}
}
UserModel.java
package com.webapp.firstwebapp.Models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="users")
public class UserModel {
#Id
#Column(name="id", nullable = false, unique = true)
public Integer id;
#Column(name="name", nullable = false, unique = false)
public String name;
#Column(name="username", nullable = false, unique = true)
public String username;
// #OneToMany(mappedBy = "user")
public UserModel(){
}
public UserModel(Integer id, String name, String username){
this.id = id;
this.username= username;
this.name = name;
}
public void setId(Integer id){
this.id = id;
}
public Integer getId(){
return id;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setUsername(String username){
this.username = username;
}
public String getUsername(){
return username;
}
}
Is there something I'm missing or am I doing something wrong? Here is the full log report I'm getting on the console:
ERROR 11976 --- [nio-8080-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private java.lang.Integer com.webapp.firstwebapp.Models.UserModel.id] by reflection for persistent property [com.webapp.firstwebapp.Models.UserModel#id] : com.webapp.firstwebapp.Models.UserModel#1bc31512] with root cause
java.lang.IllegalArgumentException: Can not set java.lang.Integer field com.webapp.firstwebapp.Models.UserModel.id to com.webapp.firstwebapp.Models.UserModel
at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167) ~[na:na]
at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171) ~[na:na]
at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58)
~[na:na]
at java.base/jdk.internal.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36) ~[na:na]
at java.base/java.lang.reflect.Field.get(Field.java:418) ~[na:na]
at org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:71) ~[hibernate-core-5.4.21.Final.jar:5.4.21.Final]
at org.hibernate.tuple.entity.AbstractEntityTuplizer.getIdentifier(AbstractEntityTuplizer.java:230) ~[hibernate-core-5.4.21.Final.jar:5.4.21.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.getIdentifier(AbstractEntityPersister.java:5150) ~[hibernate-core-5.4.21.Final.jar:5.4.21.Final]
at org.hibernate.id.Assigned.generate(Assigned.java:31) ~[hibernate-core-5.4.21.Final.jar:5.4.21.Final]
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:115) ~[hibernate-core-5.4.21.Final.jar:5.4.21.Final]
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:194) ~[hibernate-core-5.4.21.Final.jar:5.4.21.Final]
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38) ~[hibernate-core-5.4.21.Final.jar:5.4.21.Final]
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:179) ~[hibernate-core-5.4.21.Final.jar:5.4.21.Final]
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32) ~[hibernate-core-5.4.21.Final.jar:5.4.21.Final]
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:75) ~[hibernate-core-5.4.21.Final.jar:5.4.21.Final]
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:102) ~[hibernate-core-5.4.21.Final.jar:5.4.21.Final]
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:637) ~[hibernate-core-5.4.21.Final.jar:5.4.21.Final]
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:630) ~[hibernate-core-5.4.21.Final.jar:5.4.21.Final]
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:625) ~[hibernate-core-5.4.21.Final.jar:5.4.21.Final]
at com.webapp.firstwebapp.FirstwebappApplication.doSomething(FirstwebappApplication.java:39) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.3.0-SNAPSHOT.jar:5.3.0-SNAPSHOT]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.3.0-SNAPSHOT.jar:5.3.0-SNAPSHOT]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105) ~[spring-webmvc-5.3.0-SNAPSHOT.jar:5.3.0-SNAPSHOT]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888) ~[spring-webmvc-5.3.0-SNAPSHOT.jar:5.3.0-SNAPSHOT]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:802) ~[spring-webmvc-5.3.0-SNAPSHOT.jar:5.3.0-SNAPSHOT]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.3.0-SNAPSHOT.jar:5.3.0-SNAPSHOT]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1061) ~[spring-webmvc-5.3.0-SNAPSHOT.jar:5.3.0-SNAPSHOT]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:961) ~[spring-webmvc-5.3.0-SNAPSHOT.jar:5.3.0-SNAPSHOT]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.0-SNAPSHOT.jar:5.3.0-SNAPSHOT]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.3.0-SNAPSHOT.jar:5.3.0-SNAPSHOT]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:626) ~[tomcat-embed-core-9.0.37.jar:4.0.FR]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.3.0-SNAPSHOT.jar:5.3.0-SNAPSHOT]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733) ~[tomcat-embed-core-9.0.37.jar:4.0.FR]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.37.jar:9.0.37]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.0-SNAPSHOT.jar:5.3.0-SNAPSHOT]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.0-SNAPSHOT.jar:5.3.0-SNAPSHOT]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.0-SNAPSHOT.jar:5.3.0-SNAPSHOT]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.0-SNAPSHOT.jar:5.3.0-SNAPSHOT]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.0-SNAPSHOT.jar:5.3.0-SNAPSHOT]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.0-SNAPSHOT.jar:5.3.0-SNAPSHOT]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1589) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na] at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na] at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]
2020-09-06 19:00:23.731 INFO 11976 --- [ Thread-5] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
AS the error says "Error accessing field [private java.lang.Integer com.webapp.firstwebapp.Models.UserModel.id]
This is related to the scope for the attributes of UserModel entity
You have to make public access modifiers for attributes of UserModel Entity

I've been getting this error in my Postman (POST and DELETE come out with this error), hoping someone could resolve this

"timestamp": "2020-01-19T08:36:05.729+0000",
"status": 405,
"error": "Method Not Allowed",
"message": "Request method 'POST' not supported",
"trace": "org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported\r\n\tat org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping.handleNoMatch(RequestMappingInfoHandlerMapping.java:201)\r\n\tat org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.lookupHandlerMethod(AbstractHandlerMethodMapping.java:421)\r\n\tat org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:367)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.getHandlerInternal(RequestMappingHandlerMapping.java:449)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.getHandlerInternal(RequestMappingHandlerMapping.java:67)\r\n\tat org.springframework.web.servlet.handler.AbstractHandlerMapping.getHandler(AbstractHandlerMapping.java:395)\r\n\tat org.springframework.web.servlet.DispatcherServlet.getHandler(DispatcherServlet.java:1234)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1016)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)\r\n\tat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)\r\n\tat org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)\r\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:660)\r\n\tat org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)\r\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:741)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)\r\n\tat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)\r\n\tat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)\r\n\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)\r\n\tat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)\r\n\tat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)\r\n\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)\r\n\tat org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367)\r\n\tat org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)\r\n\tat org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860)\r\n\tat org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1598)\r\n\tat org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)\r\n\tat java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)\r\n\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)\r\n\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\r\n\tat java.lang.Thread.run(Unknown Source)\r\n",
"path": "/automobil/6"
}
where trace value unescapes to:
org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported
at org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping.handleNoMatch(RequestMappingInfoHandlerMapping.java:201)
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.lookupHandlerMethod(AbstractHandlerMethodMapping.java:421)
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:367)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.getHandlerInternal(RequestMappingHandlerMapping.java:449)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.getHandlerInternal(RequestMappingHandlerMapping.java:67)
at org.springframework.web.servlet.handler.AbstractHandlerMapping.getHandler(AbstractHandlerMapping.java:395)
at org.springframework.web.servlet.DispatcherServlet.getHandler(DispatcherServlet.java:1234)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1016)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1598)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Here is my Controler class
#Autowired
private AutomobiliDaoService service;
#GetMapping(path = "/automobil")
public List<PolovniAutomobili> getAll() {
return service.findAll();
}
#GetMapping(path = "/automobil/{id}")
public PolovniAutomobili getAutomobili(#PathVariable int id) {
return service.findOne(id);
}
#RequestMapping(method = RequestMethod.POST, value = "/automobil")
public void addAutomobili(#RequestBody PolovniAutomobili polovniAutomobili) {
service.addAutomobil(polovniAutomobili);
}
#RequestMapping(method = RequestMethod.DELETE, value = "/automobil")
public void deleteAutomobili(#RequestBody PolovniAutomobili polovniAutomobili) {
service.deleteAutomobil(polovniAutomobili);
}
Here is my Component class
public static List<PolovniAutomobili> automobil = new ArrayList<>();
static {
automobil.add(new PolovniAutomobili(1, 2012, "Polo", "Volkswagen", 75.00));
automobil.add(new PolovniAutomobili(2, 2018, "Arteon", "Volkswagen", 155.00));
automobil.add(new PolovniAutomobili(3, 2006, "Clio", "Renault", 55.00));
automobil.add(new PolovniAutomobili(4, 2011, "Punto", "Fiat", 60.00));
automobil.add(new PolovniAutomobili(5, 2010, "Spark", "Chevrollete", 65.00));
}
public List<PolovniAutomobili> findAll() {
return automobil;
}
public PolovniAutomobili findOne(int id) {
for(PolovniAutomobili polovniautomobili : automobil) {
if(polovniautomobili.getId()==id) {
return polovniautomobili;
}
}
return null;
}
public void addAutomobil(PolovniAutomobili polovniAutomobili) {
automobil.add(polovniAutomobili);
}
public void deleteAutomobil(PolovniAutomobili polovniAutomobili) {
automobil.remove(polovniAutomobili);
}
You are posting to /automobil/6 but in your controller you only have a POST mapping for /automobil.
Either post your data to /autmobil or change your post mapping to /autmobil/{id} with a path variable for the id.
When you want to add new contents, you must use POST method, while when you want to retrieve an existing content, you must use GET method; when you want to remove an existing content, you must use DELETE method.
Add a new car
You need a POST method.
#PostMapping("automobil")
public void addAutomobili(#RequestBody PolovniAutomobili polovniAutomobili) {
service.addAutomobil(polovniAutomobili);
}
You can provide those data in postman (based on what you add in the comments) like this:
Delete an existing car
You need the DELETE method. To follow RESTfull guidelines, is better to refere to the resource with the path variable.
#DeleteMapping("automobil/{automobilId}")
public void addAutomobili(#PathVariable Integer automobilId) {
service.deleteAutomobil(automobilId);
}
You have to modify the method deleteAutomobil of your component (which usually is called Service).
It could be better to use a Map instead of a List (because you manage ids to identify cars). In this case delete would be also easier:
public void deleteAutomobili(Integer automobilId) {
if(automobilMap.containsKey(automobilId))
automobilMap.remove(automobilId);
else {
// notify that resource doesn't exists
}
}
And this is the call with Postman (note that there's no more a body):
A Map is a structure where elements are stored as key-value pairs. You can access to a element through a key. Remember that each key has to be unique.
Your Service class should look like this:
public static Map<Integer, PolovniAutomobili> automobil = new HashMap<>();
static {
automobil.put(1, new PolovniAutomobili(1, 2012, "Polo", "Volkswagen", 75.00));
automobil.put(2, new PolovniAutomobili(2, 2018, "Arteon", "Volkswagen", 155.00));
automobil.put(3, new PolovniAutomobili(3, 2006, "Clio", "Renault", 55.00));
automobil.put(4, new PolovniAutomobili(4, 2011, "Punto", "Fiat", 60.00));
automobil.put(5, new PolovniAutomobili(5, 2010, "Spark", "Chevrollete", 65.00));
}
public List<PolovniAutomobili> findAll() {
return automobil.values();
}
public PolovniAutomobili findOne(int id) {
// if id is not a ky, it will return null (you can manage it)
return automobil.get(id);
}
public void addAutomobil(PolovniAutomobili polovniAutomobili) {
automobil.put(polovniAutomobili.getId(), polovniAutomobili);
}
public void deleteAutomobil(int id) {
if(automobil.containsKey(id))
automobil.remove(id);
else
System.out.println("Id not found");
}

Error 500 using EntityManager in PostRequest

FINAL EDIT: Sorry I'm sure this post is very hard to follow, I'm updating it for future posterity. I never figured out what is the issue with my #PersistenceContext annotation, I ended up giving up and just moved on to using a CrudRepository instead.
our repository interface that implements from CrudRepository:
public interface RepositoryCar extends CrudRepository<Car, Long> {
}
Make a service Interface (not necessary but it's better practice):
public interface ServiceInterface {
Car addCar(Car car);
Car findCar(long carId);
}
make the implementing subclass #Service:
#Service
#Transactional
public class ServiceCar implements ServiceInterface{
//autowire this so it can instantiate your CrudRepository class.
#Autowired
RepositoryCar repositoryCar;
public Car addCar(Car car) {
return repositoryCar.save(car);
}
public Car findCar(long carId) {
Optional<Car> present=repositoryCar.findById(carId);
if(present.isPresent())
{
return present.get();
}
else
return null;
}
}
So that's my cluster of a post, I'm still curious as to why my #PersistenceContext wasn't picked up on somehow, but all my endpoints were setup correctly, I would still love to hear an explanation. I just moved on and used a CrudRepository though, there are multiple ways to do this.
Original post below:
I am trying to make a PostRequest and store information about my Car object using Spring Boot. I was following a guide where I have done this previously and it worked, so I'm trying to refollow that guide and my prior example, but I seem to be missing something. I get a generic error 500, and I'm not sure where to go from here.
my Car class:
#Entity
#Table(name = "cars")
public class Car {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String make;
private String model;
private String color;
private int year;
public Car(String make, String model, String color, int year) {
this.make = make;
this.model = model;
this.color = color;
this.year = year;
}
//getters and setters
My CarController class:
#RestController
#RequestMapping("/cars")
public class CarsController {
CarsRepository repository;
public CarsController(CarsRepository repository) {
this.repository = repository;
}
#PostMapping
public Car addCar(#RequestBody Car car) {
repository.addCar(car);
return car;
}
#GetMapping
public CarsRepository getCars() {
return repository;
}
}
My Car Repository:
#Repository
public class CarsRepository {
#PersistenceContext
EntityManager entityManager;
#Transactional
public void addCar(Car car) {
entityManager.persist(car);
}
public Car find(Long id) {
return entityManager.find(Car.class, id);
}
}
My Application.yml:
spring:
jpa:
generate-ddl: true
properties.hibernate.dialect: org.hibernate.dialect.MySQL5InnoDBDialect
datasource:
url: jdbc:mysql://localhost:3306/cars?useSSL=false
username: root
In my prior examples that work, I have used this same application.yml, and I double checked that I do not have a password set, so I have omitted that field.
I made a database and table. The following SQL code makes the table. Making the table in unnecessary as the table is automatically generated, I dropped the table and just had the database exist at the end of all this:
CREATE TABLE car (
id BIGINT(20) NOT NULL AUTO_INCREMENT,
make VARCHAR(20),
model VARCHAR(20),
color VARCHAR(20),
year INT,
PRIMARY KEY (id)
)
ENGINE = innodb
DEFAULT CHARSET = utf8;
My main SpringBootApplication class is very straightforward:
package study.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
I was wondering if my table was set up incorrectly somehow, so I copy pasted my prior working example and it too gave me an error 500, so I do not think my table is incorrect because I'm certain my prior table for a different Application works.
When I do my post request in PostMan, I always get back an error 500, so I changed it from EntityManger to just an in memory HashMap, and it works fine, so I'm certain it's the EntityManager that is the problem.
Is there some component that I'm missing here, or is something I've done wrong? I have spent far too much time on this, but it looks like I'm following my past example identically, but obviously not.
My post request:
{
"make" : "make",
"model" : "model",
"color" : "blue",
"year" : 2000
}
and the response is pretty useless, it just says
{
"timestamp": "2019-06-29T03:29:06.110+0000",
"status": 500,
"error": "Internal Server Error",
"message": "No message available",
"path": "/cars/"
}
Thank you for any help, it's greatly appreciated.
EDIT: I now realize I am actually getting some useful error message in the logs, as Dmitriy pointed out. I am getting a NullPointer Exception. Here is the entire stacktrace:
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException: null
at study.example.CarsRepository.addCar(CarsRepository.java:19) ~[main/:na]
at study.example.CarsController.addCar(CarsController.java:23) ~[main/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_211]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_211]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_211]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_211]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209) ~[spring-web-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) ~[spring-web-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:891) ~[spring-webmvc-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) ~[spring-webmvc-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991) ~[spring-webmvc-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) ~[spring-webmvc-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974) ~[spring-webmvc-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:877) ~[spring-webmvc-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851) ~[spring-webmvc-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.34.jar:8.5.34]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) ~[spring-web-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.0.10.RELEASE.jar:5.0.10.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493) [tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.catalina.valves.RemoteIpValve.invoke(RemoteIpValve.java:685) [tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800) [tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:806) [tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498) [tomcat-embed-core-8.5.34.jar:8.5.34]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.34.jar:8.5.34]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_211]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_211]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.34.jar:8.5.34]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_211]
EDIT: I'm pretty sure it's my build.gradle that is the problem, because I don't see what else it could be. I'm surprised that it even compiles if that's the problem to be honest, but here it is anyways:
buildscript {
ext {
springBootVersion = "2.0.6.RELEASE"
springVersion = "5.0.10.RELEASE"
hibernateVersion = "5.2.17.Final"
slf4jVersion = "1.7.25"
junitVersion = "4.12"
mysqlVersion = "5.1.40"
}
repositories {
mavenCentral()
}
dependencies {
classpath "org.springframework.boot:spring-boot-gradle-plugin:$springBootVersion"
}
}
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
repositories {
mavenCentral()
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-web:$springBootVersion")
compile "com.fasterxml.jackson.dataformat:jackson-dataformat-csv:2.7.0"
compile("mysql:mysql-connector-java:6.0.6")
compile "org.springframework.boot:spring-boot-starter-tomcat"
compile "org.hibernate:hibernate-core:$hibernateVersion"
compile "org.slf4j:slf4j-api:$slf4jVersion"
testCompile("org.springframework.boot:spring-boot-starter-test:$springBootVersion")
}
springBoot {
buildInfo()
}
bootRun.environment([
"WELCOME_MESSAGE": "hello"
])
In your code for the class CarsRepository.java , you have provided the annotation #Transactional on the method .Try using it like below :
#Repository
#Transactional
public class CarsRepository {
#PersistenceContext
EntityManager entityManager;
public void addCar(Car car) {
entityManager.persist(car);
}
public Car find(Long id) {
return entityManager.find(Car.class, id);
}
}
#PersistenceContext: A persistence context handles a set of entities
which hold data to be persisted in some persistence store (e.g. a
database). In particular, the context is aware of the different states
an entity can have (e.g. managed, detached) in relation to both the
context and the underlying persistence store.

Categories

Resources